/
bomber.py
569 lines (424 loc) · 14.6 KB
/
bomber.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
#!/usr/bin/env python
"""Bomberman Clone"""
from collections import deque
from udeque import udeque
from arena import Arena
import os
import random
import codecs
class GameObject(object):
"""
Extendable class for items represented in the game arena
Mostly populated with debugging helpers
"""
DEBUG_CHR = ' '
ZINDEX = 0
def __init__(self, state, coords):
self.state = state
self.coords = coords
if self.state:
self.state.arena.coords_add(self.coords, self)
def __str__(self):
"""Output debug information"""
return self.DEBUG_CHR
def remove(self):
"""Lots of game objects need to remove themselves, so it's centralised here"""
self.state.arena.coords_remove(self.coords, self)
def __repr__(self):
try:
return '<%s %s [%s] 0x%x>' % (self.__class__.__name__, self._more_repr(), str(self.coords), id(self))
except AttributeError:
return '<%s %s 0x%x>' % (self.__class__.__name__, str(self.coords), id(self))
class Block(GameObject):
"""The indestructible block"""
DEBUG_CHR = 'B'
ZINDEX = 1
class Powerup(GameObject):
"""Base class for powerups"""
ZINDEX = 1
def flamed(self, _):
"""When flamed, remove"""
self.remove()
class PowerupFlame(Powerup):
"""Longer flames!"""
DEBUG_CHR = 'f'
ZINDEX = 1
def picked_up(self, player):
"""When picked up by a player, increased that player's powerup stats"""
player.flame += 1
self.remove()
class PowerupBomb(Powerup):
"""More bombs!"""
DEBUG_CHR = 'b'
ZINDEX = 1
def picked_up(self, player):
"""When picked up by a player, increased that player's powerup stats"""
player.bomb += 1
self.remove()
class DestructibleBlock(GameObject):
"""The destructible block"""
DEBUG_CHR = '.'
ZINDEX = 1
def flamed(self, _):
"""What to do when I get flamed; remove self, spawn a powerup (maybe)"""
self.remove()
rand = random.random()
if 0.00 <= rand < 0.15:
PowerupFlame(state=self.state, coords=self.coords)
elif 0.15 <= rand < 0.30:
PowerupBomb(state=self.state, coords=self.coords)
class SpawnPoint(GameObject):
"""Starting point for spawned players"""
DEBUG_CHR = 'S'
ZINDEX = 1
def flamed(self, flame):
"""SpawnPoints are indestructible"""
pass
def picked_up(self, player):
"""SpawnPoints cannot be picked up"""
pass
class Player(GameObject):
"""Represent a player"""
DEBUG_CHR = 'P'
ZINDEX = 3
# constants for actions
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
BOMB = 5
def __init__(self, *args, **kwargs):
"""Set up some defaults"""
super(Player, self).__init__(state=None, coords=None)
self._bombs_live = []
self.number = None
self.flame = 1
self.bomb = 1
self.kills = 0
self.deaths = 0
self.suicides = 0
self.name = 'Nameless'
def _more_repr(self):
return "#:%r, f:%r, b:%r" % (self.number, self.flame, self.bomb)
def spawn(self, number, state, coords):
"""Do our (delayed) init"""
self.number = number
super(Player, self).__init__(state=state, coords=coords)
def __str__(self):
"""Output debug information"""
if -1 < self.number < 10:
return str(self.number)
else:
return self.DEBUG_CHR
def drop_bomb(self):
"""Drop a bomb on the current coords"""
if self.state.arena.coords_have_class(self.coords, Bomb):
return None
if len(self._bombs_live) >= self.bomb:
return None
bomb = Bomb(self)
return bomb
def flamed(self, flame):
"""What happens when a player catches fire? Depends whose fault it is..."""
self.deaths += 1
if flame.bomb.player == self:
self.suicides += 1
else:
flame.bomb.player.kills += 1
self.remove()
self.coords = None
def move(self, new_coords):
"""Move a player"""
objs = []
for o in self.state.arena.coords_get(new_coords):
if isinstance(o, (Block, DestructibleBlock, Bomb)):
raise IndexError("Can't move %r to %r" % (self, new_coords))
objs.append(o)
self.remove()
self.state.arena.coords_add(new_coords, self)
self.coords = new_coords
for o in objs:
o.picked_up(self)
def picked_up(self, player):
"""Picked up by another player? Nah"""
pass
class Bomb(GameObject):
"""Boom!"""
DEBUG_CHR = 'x'
ZINDEX = 2
def __init__(self, player):
"""Set up some defaults and references"""
player._bombs_live.append(self)
self.player = player
self.original_owner = player # exists for cases where the bomb changes owner, e.g. when flamed by another player
self.flame = player.flame
self.ticks_left = 4
super(Bomb, self).__init__(player.state, player.coords)
def _more_repr(self):
return "op:%r, p:%r, f:%r, t:%r" % (self.original_owner, self.player, self.flame, self.ticks_left)
def tick(self):
"""What to do when the game ticks; count down and explode"""
self.ticks_left -= 1
if self.ticks_left > 0:
return
self.explode()
def explode(self):
"""Probably the most important method in the game"""
self.remove()
FlameCross(self, self.coords)
self.incinerate(self.coords, (0, -1), self.flame)
self.incinerate(self.coords, (0, +1), self.flame)
self.incinerate(self.coords, (-1, 0), self.flame)
self.incinerate(self.coords, (+1, 0), self.flame)
def incinerate(self, coords, coord_mod, flame):
"""Recursive function to spread the flames"""
coords = coords[0] + coord_mod[0], coords[1] + coord_mod[1]
try:
self.state.arena.sanity(coords)
except (IndexError):
return
if self.state.arena.coords_have_class(coords, Block):
return
# keep note if we have a DestructibleBlock, as it'll removed itself before we check on it
destructible = self.state.arena.coords_have_class(coords, DestructibleBlock)
if flame > 1 and not destructible:
if coord_mod == (0, -1) or coord_mod == (0, +1):
FlameVt(self, coords)
if coord_mod == (-1, 0) or coord_mod == (+1, 0):
FlameHz(self, coords)
else:
if coord_mod == (0, -1):
FlameEndUp(self, coords)
if coord_mod == (0, +1):
FlameEndDown(self, coords)
if coord_mod == (-1, 0):
FlameEndLeft(self, coords)
if coord_mod == (+1, 0):
FlameEndRight(self, coords)
if destructible:
return
if flame == 1:
return
self.incinerate(coords,
coord_mod,
flame-1)
def flamed(self, flame):
"""What to do when I get flamed; become property of flamer and explode"""
self.player = flame.bomb.player
self.explode()
def remove(self):
self.original_owner._bombs_live.remove(self)
super(Bomb, self).remove()
class Flame(GameObject):
"""Crackle"""
DEBUG_CHR = "~"
ZINDEX = 4
def __init__(self, bomb, coords):
"""Set up some defaults and references"""
self.bomb = bomb
super(Flame, self).__init__(bomb.state, coords)
self.state._flames.append(self)
for o in self.state.arena.coords_get(coords):
if o != self:
o.flamed(self)
def _more_repr(self):
return "b:%r" % (self.bomb)
def tick(self):
"""What to do when the game ticks; remove self"""
self.remove()
def flamed(self, flame):
"""Turn into other type of flame"""
flame.remove()
if self.__class__ is flame.__class__ or self.__class__ is FlameCross:
return
self.remove()
self.combine(flame.__class__)(self.bomb, self.coords)
@classmethod
def combine(cls, _):
return Flame
def picked_up(self, player):
"""What to do when a player picks us up?; flame 'em"""
player.flamed(self)
def remove(self):
self.state._flames.remove(self)
super(Flame, self).remove()
class FlameCross(Flame):
"""Horizonal/Vertical flame"""
DEBUG_CHR = "+"
@classmethod
def combine(cls, _):
return FlameCross
class FlameHz(Flame):
"""Horizonal flame"""
DEBUG_CHR = "-"
@classmethod
def combine(cls, flamecls):
if flamecls in (FlameEndRight, FlameEndLeft):
return FlameHz
else:
return FlameCross
class FlameVt(Flame):
"""Vertical flame"""
DEBUG_CHR = "|"
@classmethod
def combine(cls, flamecls):
if flamecls in (FlameEndUp, FlameEndDown):
return FlameVt
else:
return FlameCross
class FlameEndUp(Flame):
"""Flame endpoint"""
DEBUG_CHR = "^"
@classmethod
def combine(cls, flamecls):
if flamecls in (FlameVt, FlameEndDown):
return FlameVt
else:
return FlameCross
class FlameEndDown(Flame):
"""Flame endpoint"""
DEBUG_CHR = "v"
@classmethod
def combine(cls, flamecls):
if flamecls in (FlameVt, FlameEndUp):
return FlameVt
else:
return FlameCross
class FlameEndLeft(Flame):
"""Flame endpoint"""
DEBUG_CHR = "<"
@classmethod
def combine(cls, flamecls):
if flamecls in (FlameHz, FlameEndRight):
return FlameHz
else:
return FlameCross
class FlameEndRight(Flame):
"""Flame endpoint"""
DEBUG_CHR = ">"
@classmethod
def combine(cls, flamecls):
if flamecls in (FlameHz, FlameEndLeft):
return FlameHz
else:
return FlameCross
class GameState(object):
"""Represents the game state"""
def __init__(self):
"""Simple init of variables"""
self.arena = None
self._player_queue = udeque()
self._sticky_actions = {}
self._action_queue = deque()
self._lookup = {
'B': Block,
'.': DestructibleBlock,
'S': SpawnPoint,
}
self._flames = []
self.arena_load(["arenas", "default.bmm"])
def arena_load(self, filename_list):
"""Load an arena from a file"""
lines = []
with codecs.open(os.sep.join(filename_list), 'r', 'UTF-8') as fp:
for line in fp:
lines.append(line.rstrip())
self.arena = Arena(max((len(line) for line in lines)), len(lines))
for row, line in enumerate(lines):
for col, char in enumerate(line):
if char == ' ':
continue
self._lookup[char](state=self, coords=(col, row))
def __str__(self):
"""Produce a string representation of the arena in the same format as the map files"""
chars = []
old_y = 0
for _, y, l in self.arena:
if y != old_y:
chars.append('\n')
old_y = y
chars.append(str(max(l + [GameObject(state=None, coords=None)],
key=lambda o: o.ZINDEX)))
chars.append('\n')
return ''.join(chars)
def __repr__(self):
return str(self)
def player_add(self, player):
"""Add a player to the game state"""
self._player_queue.appendleft(player)
def player_remove(self, player):
"""Remove a player from the game state"""
player.remove()
def spawn(self):
"""Spawn the players into the arena"""
p_no = 0
for x, y, _ in self.arena:
if self.arena.coords_have_class((x, y), SpawnPoint):
try:
player = self._player_queue.pop()
except (IndexError):
break
p_no += 1
player.spawn(p_no, state=self, coords=(x, y))
self._sticky_actions[player] = None
def tick(self, count=1):
"""Step to the next game state: this is an example and is used for testing"""
for _ in xrange(count):
self._flames_process()
self._actions_process()
self._bombs_process()
def action_add(self, player, action):
"""Add player actions to a queue for processing"""
self._action_queue.appendleft((player, action))
def _actions_process(self):
"""Process queued actions or fall back to sticky actions"""
unexecuted = deque()
had_turn = []
while self._action_queue:
player, action = self._action_queue.pop()
if player in had_turn:
unexecuted.appendleft((player, action))
else:
self._player_action(player, action)
self._player_sticky(player, action)
had_turn.append(player)
for player in self._sticky_actions:
if player not in had_turn:
self._player_action(player, self._sticky_actions[player])
self._action_queue = unexecuted
def _player_action(self, player, action):
"""Perform player action"""
try:
px, py = player.coords
except TypeError:
# coords are invalid, player is not in the arena: noop
return
try:
if action == Player.BOMB:
player.drop_bomb()
elif action == Player.UP:
player.move((px, py-1))
elif action == Player.DOWN:
player.move((px, py+1))
elif action == Player.LEFT:
player.move((px-1, py))
elif action == Player.RIGHT:
player.move((px+1, py))
except IndexError:
self._sticky_actions[player] = None
def _player_sticky(self, player, action):
"""Add actions to "sticky" lookup, if applicable"""
if action == Player.BOMB:
self._sticky_actions[player] = None
else:
self._sticky_actions[player] = action
def _bombs_process(self):
"""Tick bombs"""
for p in self._sticky_actions:
for b in p._bombs_live[:]: # copy the list so we can safely iterate
if b in p._bombs_live:
b.tick()
def _flames_process(self):
"""Tick the flames"""
for f in self._flames[:]: # copy the list so we can safely iterate
f.tick()