Debian Codegraph @

tools/unitstats.py

raw
1 #! /usr/bin/env python
2 # ____ _ __
3 # / __ )____ _____ | | / /___ ___________
4 # / __ / __ \/ ___/ | | /| / / __ `/ ___/ ___/
5 # / /_/ / /_/ (__ ) | |/ |/ / /_/ / / (__ )
6 # /_____/\____/____/ |__/|__/\__,_/_/ /____/
7 #
8 # A futuristic real-time strategy game.
9 # This file is part of Bos Wars.
10 #
11 # Script that generates all the distribution packages.
12 # (c) Copyright 2007 by Francois Beerten
13 #
14 # Bos Wars is free software; you can redistribute it and/or modify
15 # it under the terms of the GNU General Public License as published
16 # by the Free Software Foundation; only version 2 of the License.
17 #
18 # Bos Wars is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
22 import os
23 import sys
24 import csv
25 import re
26
27 importantkeys = ['Name',
28 'EnergyValue', 'MagmaValue',
29 'MaxEnergyUtilizationRate', 'MaxMagmaUtilizationRate',
30 'EnergyProductionRate', 'MagmaProductionRate',
31 'EnergyStorageCapacity', 'MagmaStorageCapacity',
32 'HitPoints', 'SightRange', 'Armor', 'BasicDamage',
33 'PiercingDamage', 'MaxAttackRange', 'MovementDelay',
34 'AttackDelay']
35
36 def findunits():
37 u = os.listdir('units')
38 u = [x for x in u if not x.startswith('.')]
39 return u
40
41 def findunitscripts(directory):
42 base = 'units/' + directory + '/'
43 s = os.listdir(base)
44 s = [base + x for x in s if x.endswith('.lua')]
45 return s
46
47 def findallscripts():
48 scripts = []
49 units = findunits()
50 for u in units:
51 scripts.extend(findunitscripts(u))
52 return scripts
53
54 def parseKvList(kvlist):
55 d = {}
56 key = kvlist[0]
57 for i in kvlist[1]:
58 if key:
59 d[key] = i
60 key = None
61 else:
62 key = i
63 return key
64
65 def replaceTabs(s):
66 return s.replace('\t', ' ' * 4)
67
68 class ParsedScript:
69 def __init__(self, path):
70 self.path = path
71 self.units = []
72 def regenerate(self, f):
73 f.write(self.head)
74 for unit in self.units:
75 unit.regenerate(f)
76
77 class ParsedUnit:
78 def __init__(self):
79 self.orderedkeys = []
80 self.stats = {}
81 def regenerateStats(self, f):
82 keys = self.stats.keys()
83 keys.sort()
84 for k in self.orderedkeys[:-1]:
85 f.write(' ' + k + ' = ' + self.stats[k] + ',\n')
86 k = self.orderedkeys[-1]
87 f.write(' ' + k + ' = ' + self.stats[k] + '\n')
88 def regenerate(self, f):
89 f.write('DefineUnitType("' + self.internalname + '", {\n')
90 self.regenerateStats(f)
91 f.write('})')
92 f.write(self.rest)
93 def writeCsv(self, statsfile):
94 statsfile.writerow(self.stats)
95
96
97 def stripComments(s):
98 s = s.split('\n')
99 new = []
100 for i in s:
101 i = i.split('--', 1)
102 new.append(i[0])
103 return '\n'.join(new)
104
105 def parseDefineUnitType(text):
106 unit = ParsedUnit()
107 body, rest = text.split('})', 1)
108 unit.rest = replaceTabs(rest)
109 body = stripComments(body)
110 internalname, stats = body.split(', {', 1)
111 unit.internalname = internalname.strip().strip('"')
112 stats = stats.split('=')
113 prevKey = stats[0].strip()
114 for x in stats[1:-1]:
115 x = x.split(',')
116 unit.stats[prevKey] = replaceTabs(','.join(x[:-1]).strip())
117 unit.orderedkeys.append(prevKey)
118 prevKey = x[-1].strip()
119 if len(stats) > 2:
120 unit.orderedkeys.append(prevKey)
121 unit.stats[prevKey] = replaceTabs(stats[-1].strip())
122 return unit
123
124 def parseWaits(text, section):
125 section += ' ='
126 if section not in text:
127 return 0
128 _, text = text.split(section, 1)
129 text,_ = text.split('}',1)
130 if 'unbreakable' in text:
131 _, text, _ = text.split('"unbreakable', 2)
132 m =re.findall(r'"wait \d+"', text)
133 waits = 0
134 for i in m:
135 v = int(i[6:-1])
136 waits += v
137 return waits
138
139 def parseScript(path):
140 parsedscript = ParsedScript(path)
141 s = file(path, 'rt').read()
142 elements = s.split('DefineUnitType(')
143 parsedscript.head = elements[0]
144 movement = parseWaits(s, 'Move')
145 attackwait = parseWaits(s, 'Attack')
146 for e in elements[1:]:
147 unit = parseDefineUnitType(e)
148 unit.stats['MovementDelay'] = movement
149 unit.stats['AttackDelay'] = attackwait
150 parsedscript.units.append(unit)
151 return parsedscript
152
153
154 def parseAllScripts():
155 units = []
156 scriptpaths = findallscripts()
157 scripts = []
158 for i in scriptpaths:
159 if 'crystal' not in i:
160 parsedscript = parseScript(i)
161 scripts.append(parsedscript)
162 units.extend(parsedscript.units)
163 return units, scripts
164
165 def generateStatsFile(units):
166 rawcsvfile = file('unitstats.csv', 'wb')
167 statsfile = csv.DictWriter(rawcsvfile, importantkeys, extrasaction='ignore',
168 delimiter=';', quotechar="'")
169 title = {}
170 for i in importantkeys:
171 title[i]=i
172 statsfile.writerow(title)
173 for unit in units:
174 unit.writeCsv(statsfile)
175
176
177 def regenerateScripts(scripts):
178 for i in scripts:
179 f = file(i.path, 'wt')
180 i.regenerate(f)
181
182 def readUnitStats():
183 rawcsvfile = file('unitstats.csv', 'rb')
184 stats = csv.DictReader(rawcsvfile, delimiter=';', quotechar="'")
185 newstats = {}
186 for r in stats:
187 newstats['"%s"' % r['Name']] = r
188 return newstats
189 def removeCommas(old):
190 return ''.join(old.split(','))
191 def updateUnitStats(units):
192 stats = readUnitStats()
193 for unit in units:
194 name = unit.stats['Name']
195 if stats.has_key(name):
196 up = stats[name]
197 for k in up.keys():
198 if unit.stats.has_key(k) and k != 'Name':
199 unit.stats[k] = removeCommas(up[k])
200
201 Usage = """
202 Unit stats generation tool.
203 Usage: %s <command>
204
205 Command:
206 csv
207 regenerate
208 update
209
210 When updating, the unitstats.csv file should use the semicolon (;) as
211 delimiter and single quote (') as string quote.
212 """
213 def printUsage(args):
214 print Usage % args[0]
215
216 def main(args):
217 if len(args) == 1:
218 printUsage(args)
219 return
220 units, scripts = parseAllScripts()
221 if args[1] == 'csv':
222 generateStatsFile(units)
223 elif args[1] == 'regenerate':
224 regenerateScripts(scripts)
225 elif args[1] == 'update':
226 updateUnitStats(units)
227 regenerateScripts(scripts)
228 elif args[1] == 'tupdate':
229 updateUnitStats([units[0]])
230 regenerateScripts(scripts)
231 else:
232 printUsage(args)
233 return
234
235
236 if __name__ == '__main__':
237 main(sys.argv)
238