-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforagers.py
executable file
·411 lines (342 loc) · 13.1 KB
/
foragers.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#!/usr/bin/python
import pygame
from pygame.locals import *
from game import Game
from output import Output
from spritesheet import Spritesheet
from economy import Economy
from soldiers import SoldierClass
import gamemap
import copy
class App(Game, Output):
# Output parameter has been removed (because the output is the app object itself
def __init__(self, economy, gameMap, army, msgBaseDelaySecs = 0.10):
# Init GAME parent
Game.__init__(self, economy, gameMap, army, self, msgBaseDelaySecs)
self._running = True
self.screen = None
# Init for Output part
self.lastMessages = [];
self.msg = "";
self.nextColor = (128, 128, 128);
self.msgBaseDelaySecs = msgBaseDelaySecs;
self.maxMessages = 10;
# Game overrides
def run(self):
self.on_execute()
return self.finalScore
# App methods
def on_init(self):
self._running = True
pygame.init()
pygame.font.init()
self.font = pygame.font.Font(None, 20)
self.TILE_HEIGHT = 32
self.TILE_WIDTH = 32
self.MESSAGE_BOX_WIDTH = 400
self.size = self.weight, self.height = self.gameMap.xSize * self.TILE_WIDTH + self.MESSAGE_BOX_WIDTH, \
self.gameMap.ySize * self.TILE_HEIGHT
self.msgBoxLeft = self.gameMap.xSize * self.TILE_WIDTH
self.output = self
self.screen = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)
# msgBaseDelaySecs = self.msgBaseDelaySecs;
# Default spritesheet assets
self.sprites = Spritesheet("assets/fantasy-tileset-8cols-26rows-32x32pixels.png")
self.spritesPlural = Spritesheet("assets/fantasy-tileset-8cols-26rows-32x32pixels-shadow.png")
self.enemySprites = Spritesheet("assets/fantasy-tileset-8cols-26rows-32x32pixels-red.png")
output = self.output;
self.gameTime = 0;
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;
def on_event(self, event):
if event.type == pygame.QUIT:
self._running = False
def on_loop(self):
# If stopped running
if not self._running:
# Quit the loop
return
# Main game loop
output = self.output;
iGameTime = self.gameTime;
# msgBaseDelaySecs = self.msgBaseDelaySecs;
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("\nAttacker" + 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();
self.printGameState();
else:
self.printGameState();
# time.sleep(3 * msgBaseDelaySecs);
# End of game
bEndConditions = (len(self.aAttackers) == 0) or (iGameTime > 1000);
if (bEndConditions):
self._running = False;
def on_render(self):
self.repaintTerrain()
def on_cleanup(self):
pygame.quit()
def on_execute(self):
output = self
if self.on_init() == False:
self._running = False
while( self._running ):
for event in pygame.event.get():
self.on_event(event)
self.on_loop()
self.on_render()
dScore = self.getScore(self.gameTime, self.aAttackers, self.dead);
output.log("Score: %d after %d time"%(dScore, self.gameTime));
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();
self.finalScore = dScore
self.on_cleanup()
# Output object override
def log(self, msg):
msg = msg.strip();
if (len(msg) == 0):
return;
if (self.nextColor == None):
self.nextColor = (128, 128, 128)
else:
# Round robin in color
tmpColor = [];
for iColorCnt in range(3):
if (self.nextColor[iColorCnt] + 4) > 255:
tmpColor += [128]
else:
tmpColor += [self.nextColor[iColorCnt] + 4]
self.nextColor = tuple(tmpColor)
self.msg += msg;
self.lastMessages += [(msg, self.nextColor)];
if (len(self.lastMessages) > self.maxMessages):
self.lastMessages = self.lastMessages[-self.maxMessages:];
def dump(self):
if (len(self.lastMessages) > self.maxMessages):
self.lastMessages = self.lastMessages[-self.maxMessages:];
# DEBUG LINES
# print "\n".join(self.lastMessages);
iMsgY = 0
for curMsg in self.lastMessages:
msgImg = self.font.render(curMsg[0], 0, curMsg[1], (0, 0, 0))
msgRect = msgImg.get_rect()
msgDstRect = Rect(self.msgBoxLeft, iMsgY , msgRect.width, msgRect.height)
# Update screen
self.screen.blit(msgImg, msgDstRect)
iMsgY += msgRect.height + 5
self.msg = "";
# TODO: Implement (?)
def write(self): pass
def writeln(self): pass
def clear(self):
self.msg = "";
self.lastMessages = [];
def color(self, sColor = None):
self.nextColor = sColor;
def drawMap(self, mapToDraw, attackers, defenders, trapColor = (255, 0, 0),
treasureColor = (0, 255, 255), terrainColor = (0, 255, 255)):
# ZERO-BASED row,col for default spritesheet (assets/fantasy-tileset-8cols-26rows-32x32pixels.png)
# Define mapping between ASCII and image representation
# Soldiers
SOLDIERS_ROW = 18;
isSoldier = lambda x: x.lower()[0] in [" ", "/", "_"];
ASSASIN_COL = 0;
DRUID_COL = 1;
BARBARIAN_COL = 2;
SOLDIER_COL = 3;
RANGER_COL = 4;
KNIGHT_COL = 5;
MAGE_COL = 6;
ENCHANTER_COL = 6; # TODO: Find other icon
WIZARD_COL = 7;
soldierMap = {"X": ASSASIN_COL,
"D": DRUID_COL,
"B": BARBARIAN_COL,
"S" : SOLDIER_COL,
"R" : RANGER_COL,
"K" : KNIGHT_COL,
"M" : MAGE_COL,
"E" : ENCHANTER_COL,
"W" : WIZARD_COL
}
# Towers
TOWERS_ROW = 14;
isTower = lambda x: x.lower()[0] in ["|", ">", ","];
FIRE_ELEMENTALIST_COL = 1;
FORT_COL = 3
ILLUSIONIST_COL = 6
TOWER_COL = 0
WIZARD_TOWER_COL = 4
towerMap = {"E" : FIRE_ELEMENTALIST_COL, "F" : FORT_COL,
"I" : ILLUSIONIST_COL, "T" : TOWER_COL,"W" : WIZARD_TOWER_COL,};
# Traps
TRAPS_ROW = 2;
isTrap = lambda x: x.lower()[1] in ["^", "_", "@", "*"];
ARROWSLIT_COL = 1;
EXPLOSION_COL = 0
LABYRINTH_COL = 3
PIT_COL = 4
TRAPCLASS_COL = 1
trapMap = {"^" : ARROWSLIT_COL, "*" : EXPLOSION_COL,
"@" : LABYRINTH_COL, "_" : PIT_COL,"#" : TRAPCLASS_COL,};
# Fields
FIELD_ROW = 0
FIELD_COL = 3
# Treasures
TREASURE_ROW = 15
TREASURE_COL = 1
mapInstance = copy.deepcopy(mapToDraw);
# Init squares
mapInstance.squares = [[ '...' for iCnt in range(0, mapInstance.xSize) ] for iCnt in range(0, mapInstance.ySize)];
isTerrain = lambda x : x == "..."
# Init map ASCII representation
for iCnt in range(0, mapInstance.xSize):
for iCnt2 in range(0, mapInstance.ySize):
squareTreasures = mapInstance.getTreasures(iCnt, iCnt2);
squareTraps = mapInstance.getTraps(iCnt, iCnt2);
squareFoes = mapInstance.getFoes(iCnt, iCnt2);
# If treasure in square
if (len(squareTreasures)) > 0:
# Show the first
mapInstance.squares[iCnt][iCnt2] = str(squareTreasures[0]);
else:
if len(squareFoes) > 0:
# Show the first
mapInstance.squares[iCnt][iCnt2] = str(squareFoes[0]);
else:
# If trap in square
if (len(squareTraps)) > 0:
# Show the first
mapInstance.squares[iCnt][iCnt2] = str(squareTraps[0]);
# Render soldiers
for cItem in attackers:
iAttCnt = len(filter(lambda x: x == cItem.x and y == cItem.y, attackers))
if iAttCnt > 1:
# Indicate attacker with starting a letter
mapInstance.squares[cItem.x][cItem.y] = "a" + str(cItem);
else:
# Indicate multiple attackers with starting A letter
mapInstance.squares[cItem.x][cItem.y] = "A" + str(cItem);
for cItem in defenders:
mapInstance.squares[cItem.x][cItem.y] = str(cItem);
# Show map
for curRow in range(mapInstance.ySize):
for curCol in range(mapInstance.xSize):
sCurSq = mapInstance.squares[curCol][curRow]
sprites = self.enemySprites
if sCurSq[0] == "a":
sprites = self.sprites
sCurSq = sCurSq[1:]
else:
if sCurSq[0] == "A":
sprites = self.spritesPlural
sCurSq = sCurSq[1:]
else:
if isTerrain(sCurSq):
sprites = self.sprites
img = None
if isSoldier(sCurSq):
img = sprites.image_at_col_row(soldierMap[sCurSq[1]], SOLDIERS_ROW)
if isTower(sCurSq):
img = sprites.image_at_col_row(towerMap[sCurSq[1]], TOWERS_ROW)
if isTrap(sCurSq):
img = sprites.image_at_col_row(trapMap[sCurSq[1]], TRAPS_ROW)
if isTerrain(sCurSq):
img = sprites.image_at_col_row(FIELD_COL, FIELD_ROW)
if img == None: # Treasure
img = sprites.image_at_col_row(TREASURE_COL, TREASURE_ROW)
TILE_HEIGHT = self.TILE_HEIGHT
TILE_WIDTH = self.TILE_WIDTH
src = Rect(0, 0, TILE_WIDTH, TILE_HEIGHT)
dst = Rect(curCol * TILE_WIDTH, curRow * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT)
self.screen.blit(img, dst, src)
# Get rid of deep map copy
del mapInstance;
# Actually render
pygame.display.flip()
def saveToFile(self, sFilename):
fOut = open(sFilename, 'w')
fOut.write(self.msg)
fOut.close()
if __name__ == "__main__" :
# Init economy and map
economy = Economy(5000);
gameMap = gamemap.GameMap(economy, 20, 20);
output = Output()
# Init army
# Set colors
sAttackerColor = (255, 255, 255);
army = Game.selectArmy(economy, gameMap, sAttackerColor, output,
[
"AssassinClass",
"BarbarianClass",
"DruidClass",
"EnchanterClass",
"KnightClass",
"MageClass",
"RangerClass",
"SoldierClass",
"WizardClass",
# "CartographerClass",
# "TechnicianClass",
# "BridgeBuilderClass",
]);
theApp = App(economy, gameMap, army)
theApp.on_execute()
print "Score: " + str(theApp.finalScore)