-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunGame.py
executable file
·369 lines (302 loc) · 12.1 KB
/
runGame.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
from soldiers import *
from towers import *
from economy import Economy
from output import ConsoleOutput
import time
import math
import random
import gamemap
from pprint import pformat
#import pygame;
#from pygame.locals import *;
from termcolor import colored
#from utils import Utils;
class Game(object):
# Static method definitions
@staticmethod
def getInstanceOf(sClassName, economy, gameMap):
return eval("soldiers." + sClassName +"(economy, gameMap)");
@staticmethod
def selectArmy(eEconomy, gameMap, armyColor, output,
aUnitPool = [
# "AssassinClass",
# "BarbarianClass",
# "CartographerClass",
# "DruidClass",
# "EnchanterClass",
# "KnightClass",
"MageClass",
# "RangerClass",
"SoldierClass",
"TechnicianClass",
# "BridgeBuilderClass",
# "WizardClass",
]):
iTotalValue = 0;
aArmy = [];
curMoney = eEconomy.maxMoney;
output.log("\nStarting money:" + str(curMoney) + "$");
output.dump();
while (curMoney > 0):
curChoice = random.choice(aUnitPool);
# If we exceed our money
if (eEconomy.cost(Game.getInstanceOf(curChoice, eEconomy, gameMap)) > curMoney):
curChoice = None;
# Try linearly
for cChoice in aUnitPool:
# If we have enough money
if eEconomy.cost(Game.getInstanceOf(cChoice, eEconomy, gameMap)) <= curMoney:
# buy the army
curChoice = cChoice;
# If we found nothing we can afford
if (curChoice == None):
output.log("\nTotal army value: %d$\n"%(iTotalValue));
# quit
return aArmy;
# else buy the army
armyToAdd = Game.getInstanceOf(curChoice, eEconomy, gameMap);
# assign color
armyToAdd.color = armyColor;
aArmy.append(armyToAdd);
output.log("Selected %s for %d$. " %(str(curChoice), eEconomy.cost(armyToAdd)));
# update our running total of money
curMoney -= eEconomy.cost(armyToAdd);
iTotalValue += eEconomy.cost(armyToAdd);
output.log("\nTotal army value: %d$\n"%(iTotalValue));
# Class method definitions
def dealDamage(self, oFrom, oTo):
output = self.output;
output.log("%s attacks %s with a %s attack.\t"%(str(oFrom) + str(id(oFrom))[:-3], str(oTo) + str(id(oTo))[:-3], oFrom.damageType) );
actualDefence = oTo.defence;
if oFrom.damageType in oTo.immunities:
output.log("Target is immune!");
return oTo;
if oFrom.damageType in oTo.resistances:
actualDefence = oTo.defence * 2.0;
if oFrom.damageType in oTo.vulnerabilities:
actualDefence = oTo.defence * 0.5;
dDmg = round(max(oFrom.attack * math.pow(1.05, (10 - actualDefence)), 1.0));
oTo.currentHp -= dDmg;
output.log("Target is hit for %d damage. %d hit points remaining."%(dDmg, oTo.currentHp));
return oTo;
def printGameState(self):
self.output.dump();
def repaintTerrain(self):
self.output.drawMap(self.gameMap, self.aAttackers, []);
def interactWithTrap(self, actor, trap, friends, foes, traps=[]):
self.act(actor, trap, friends, foes, traps);
if (trap.hp <= 0):
self.gameMap.traps.remove(trap);
# Reward actor
actor.score += self.economy.trapValue(trap);
else:
self.act(trap, actor, [], [actor]);
return actor.currentHp > 0;
def interactWithHome(self, actor):
actor.fullness = 100;
self.output.log(str(actor) + " got provisions!")
return True
def interactWithTreasure(self, actor, treasure, friends, foes):
treasure.applyEffectTo(actor);
self.gameMap.treasures.remove(treasure);
# Reward actor
actor.score += self.economy.treasureValue(treasure);
return True;
def interactWithFoe(self, actor, foe, friends, foes):
# DEBUG LINES
#output.log(str(actor) + " in " + str(actor.x) + "," + str(actor.y) + " attacks \n\t" + str(foe))
self.act(actor, foe, friends, foes);
return actor.currentHp > 0;
def act(self, actor, target, friends, foes, traps = []):
output = self.output;
if (isinstance(actor, SoldierClass)):
try:
output.color(actor.color);
except:
pass
# Use abilities, if they exist
if len(actor.abilities) > 0:
# DEBUG LINES
#output.log("Using ability!");
for aCurAbility in actor.abilities:
# DEBUG LINES
#output.log("Ability group:" + aCurAbility.group);
foe = None;
if aCurAbility.group == "traps":
if target in traps:
foe = target;
# DEBUG LINES
# print "Found TRAP!";
# raw_input();
else:
if aCurAbility.group == "foes":
if target in foes:
foe = target;
# If not applicable as a foe or trap
if (foe == None):
continue;
# Check probability for probability-based abilities
try:
if (float(aCurAbility.frequency) > 0) and (float(aCurAbility.frequency) < 1):
fCurProbability = float(aCurAbility.frequency);
fRoll = random.random();
if fRoll <= fCurProbability:
# DEBUG LINES
#output.log("Rolled %4.2f with a chance of %4.2f"%(fRoll, fCurProbability));
if (aCurAbility.applyTo(foe, friends, foes) != None):
output.log(str(aCurAbility));
continue;
except:
# DEBUG LINES
#output.log("\n" + str(aCurAbility) + "\n");
pass; # Ignore
# Try to apply ability for other types of frequency
if (aCurAbility.applyTo(foe, friends, foes, traps) != None):
output.log(str(aCurAbility));
# else:
# # DEBUG LINES
# print "Could not use " + str(type(aCurAbility));
# Remove battle abilities
if aCurAbility.frequency == "battle":
actor.abilities.remove(aCurAbility);
# Decrease (and possibly remove) abilities with uses
try:
if (int(aCurAbility.frequency) >= 1):
iCurUses = int(aCurAbility.frequency);
iCurUses -= 1;
if iCurUses == 0:
actor.abilities.remove(aCurAbility);
else:
aCurAbility.frequency = str(iCurUses);
except:
pass; # Ignore
# Deal damage, if target is still a foe
if target in foes:
target.currentHp = self.dealDamage(actor, target).currentHp;
# Reset color
output.color();
def __init__(self, economy, gameMap, army, output, msgBaseDelaySecs = 0.10):
# Init map
self.economy = economy;
self.gameMap = gameMap;
self.aAttackers = army;
# Init output
self.output = output;
self.msgBaseDelaySecs = msgBaseDelaySecs;
def run(self):
output = self.output;
msgBaseDelaySecs = self.msgBaseDelaySecs;
output.log("Game begins!");
self.dead = [];
output.dump();
time.sleep(2 * msgBaseDelaySecs);
# Position armies
iX = 0; iY = 2;
for oItemA in self.aAttackers:
oItemA.x = iX;
oItemA.y = iY;
iX += 1;
if (iX == self.gameMap.xSize):
iX = 0;
iY += 1;
# Main game loop
iGameTime = 0;
self.repaintTerrain();
iRowCnt = 0;
while (True):
bShouldRepaint = False;
iGameTime += 1; # Next moment
if (iGameTime % 100 == 0):
output.log("The time is now %d..."%(iGameTime));
self.gameTime = iGameTime;
bEndConditions = False;
# Local vars
aAttackers = self.aAttackers;
aDefenders = self.gameMap.foes
bActed = False;
# Check attackers
aToRemove = []
for cCurAttacker in aAttackers:
if (cCurAttacker.currentHp <= 0 or cCurAttacker.fullness <= 0):
output.log(colored("\nAttacker", cCurAttacker.color) + str(id(cCurAttacker)) + " has died!");
if cCurAttacker.fullness <= 0:
output.log("...in fact it was STARVATION...");
# Put to dead
self.dead += [(cCurAttacker, iGameTime)];
aToRemove += [cCurAttacker];
bActed = True;
else:
if self.timeToAct(cCurAttacker):
# Reduce fullness
cCurAttacker.fullness -= 1;
bActed = cCurAttacker.act(aAttackers, self.gameMap.foes, self);
# Update attackers list
aAttackers = list(set(aAttackers) - set(aToRemove))
self.aAttackers = aAttackers
if (len(aToRemove) > 0):
output.log("Remaining attackers: " + ",".join(map(str, aAttackers)))
# DEBUG LINES
# output.log("\n" + str(cCurAttacker) + "\n");
# output.log(pformat(vars(cCurAttacker)) + "\n");
# Also check defenders
for cCurDefender in filter(lambda x: isinstance(x, SoldierClass), aDefenders):
if (cCurDefender.currentHp <= 0):
output.log("\nDefender" + str(id(cCurDefender)) + " has died!");
self.gameMap.foes.remove(cCurDefender)
bActed = True
else:
if self.timeToAct(cCurDefender):
bActed = bActed or cCurDefender.act(aDefenders, aAttackers, self, canMove = False, canInteractWTraps = False, canInteractWFoes = True,
canInteractWTreasure = False, canInteractWHome = False); # Cannot only interact with foes
if (bActed):
self.repaintTerrain();
output.log("\n");
self.printGameState();
# time.sleep(3 * msgBaseDelaySecs);
iRowCnt += 1;
if (iRowCnt >= 5 or bShouldRepaint):
if (bShouldRepaint):
time.sleep(10 * msgBaseDelaySecs);
iRowCnt = 0;
# TODO: Remove
bEndConditions = (len(self.aAttackers) == 0) or (iGameTime >= 1000);
# End of game
if (bEndConditions):
break;
dScore = self.getScore(iGameTime, self.aAttackers, self.dead);
output.log("Score: %d after %d time"%(dScore, iGameTime));
if (len(self.aAttackers) == 0):
output.log("\n\nNo Attackers left! Defenders win!");
else:
output.log("Foraging complete! %d died and %d remain."%(len(self.dead), len(self.aAttackers)));
# Final output
output.dump();
return dScore;
def timeToAct(self, actor):
return (self.gameTime % math.floor(1000.0 / actor.attackSpeed)) == 0
def getScore(self, iGameTime, aSurvivors, aDead):
dScore = iGameTime;
for curSurvivor in aSurvivors:
dScore += self.economy.cost(curSurvivor) + curSurvivor.score;
# Also take into account dead
for soldier,dieTime in self.dead:
dScore += (soldier.score / 2) * float(dieTime) / float(iGameTime)
return dScore;
if __name__ == "__main__":
# Init economy and map
economy = Economy(500);
gameMap = gamemap.GameMap(economy, 10, 10, 0.1, 0.1, 0.05, 0.05);
# Init messaging
output = ConsoleOutput();
# Init army
# Set colors
sAttackerColor = "white";
army = Game.selectArmy(economy, gameMap, sAttackerColor, output);
# Output game data
sGameStats = ("Traps: %d, Treasures: %d, Foes: %d, Army: %d"%(len(gameMap.traps), len(gameMap.treasures), len(gameMap.foes), len(army)))
# Init game
g = Game(economy, gameMap, army, output, 0.05);
evaluation = g.run();
print("Final evaluation of the map",evaluation);
print("Map info: " + sGameStats)
g.output.saveToFile("log.txt")