-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.py
More file actions
668 lines (551 loc) · 20.8 KB
/
engine.py
File metadata and controls
668 lines (551 loc) · 20.8 KB
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
import re
import random
import pygameui as ui
from itertools import chain
import asyncio
TILE_WIDTH = 10
TILE_HEIGHT = 10
directions = {
# direction: (left, top)
"w": (0, -1),
"a": (-1, 0),
"s": (0, 1),
"d": (1, 0),
}
def feedblock(line):
while line:
attr, block, line = line[0], line[1], line[2:]
yield attr, block
def first(iterator):
for elem in iterator:
return elem
class MapObject:
char = "Q"
hidden = False
color = (100, 100, 100)
def __init__(self, frame):
self.frame = frame
@property
def position_int(self):
return (round(self.frame.left / TILE_WIDTH), round(self.frame.top / TILE_HEIGHT))
@property
def position_float(self):
return (round(self.frame.left / TILE_WIDTH, 1), round(self.frame.top / TILE_HEIGHT, 1))
def update(self, dt):
pass
def hide(self):
self.hidden = True
self.char = self.char.lower()
class FireTrail(MapObject):
def __init__(self, bomb, start, end):
self.start = start
self.end = end
x, y = start
_x, _y = end
frame = ui.Rect(
min(x, _x) * TILE_WIDTH,
min(y, _y) * TILE_HEIGHT,
(abs(x - _x) + 1) * TILE_WIDTH,
(abs(y - _y) + 1) * TILE_HEIGHT
)
super().__init__(frame)
self.color = bomb.color
self.bomb = bomb
class Bomb(MapObject):
def __init__(self, player, fuse_time, position):
x, y = position
frame = ui.Rect(
x * TILE_WIDTH,
y * TILE_HEIGHT,
TILE_WIDTH,
TILE_HEIGHT
)
super().__init__(frame)
self.player = player
self.fuse_time = fuse_time
self.burn_time = 1.5
self.exploding_time = 0.2
self.ignite_time = 0.1
self.update_timer = fuse_time
self._state = "ticking"
self.color = (10, 10, 10)
self.explosion_radius = player.explosion_radius
self.hidden = False
self.destroyed_walls = []
self.fire_trails = []
@property
def state(self):
return self._state
@state.setter
def state(self, value):
state_transitions = {
"ticking": ["exploding", "burning"],
"exploding": ["burning"],
"burning": ["hiding"],
"hiding": []
}
assert value in state_transitions[self._state]
if self._state != value:
self._state = value
self.on_new_state(value)
def bomb_info(self):
# for clients it is not a difference if the bomb is exploding or burning
# since the exploding state is just present for 0.2 seconds it will probably produce bugs
# if the client doesn't know or care about it.
default_info = (self.position_int, self.update_timer, self.state,)
if self.state == "exploding":
return (self.position_int, self.update_timer + 1.5, "burning",) + ([f.end for f in self.fire_trails],)
elif self.state == "burning":
return default_info + ([f.end for f in self.fire_trails],)
elif self.state == "hiding":
return default_info + ([w.position_int for w in self.destroyed_walls],)
return default_info + (None,)
def on_new_state(self, state):
if state == "exploding":
self.color = (255, 255, 230)
self.update_timer = self.exploding_time
self.deploy_fire_trails()
self.player.map.inform_all("BOMB", self.bomb_info())
elif state == "burning":
self.color = (255, 55, 10)
self.update_timer = self.burn_time
elif state == "hiding":
self.hide()
for fire_trail in self.fire_trails:
fire_trail.hide()
self.player.points += len([w for w in self.destroyed_walls if not w.hidden])
for wall in self.destroyed_walls:
wall.hide()
self.player.map.inform_all("BOMB", self.bomb_info())
def deploy_fire_trails(self):
for direction in "wasd":
left, top = directions[direction]
x, y = self.position_int
for i in range(self.explosion_radius + 1):
_x = x + i * left
_y = y + i * top
if _x < 0 or _y < 0:
break
try:
tile = self.player.map._map[_y][_x]
if isinstance(tile, Wall) and not tile.hidden:
if tile.destructable:
self.destroyed_walls.append(tile)
break
except IndexError:
pass
fire_trail = FireTrail(self, (x, y), (_x, _y))
self.player.map.items.append(fire_trail)
self.fire_trails.append(fire_trail)
def ignite(self):
if self.state == "ticking":
self.state = "exploding"
def update(self, dt):
loop = asyncio.get_event_loop()
if self.state in ("exploding", "burning"):
for fire_trail in self.fire_trails:
for player in self.player.map.players:
if not player.alive:
continue
if fire_trail.frame.colliderect(player.frame):
player.die()
for bomb in self.player.map.items:
if not isinstance(bomb, Bomb) or bomb.state != "ticking":
continue
if fire_trail.frame.colliderect(bomb.frame):
loop.call_later(self.ignite_time, lambda x: x.ignite(), bomb)
time_to_tick = min(dt, self.update_timer)
dt -= time_to_tick
self.update_timer -= time_to_tick
if self.update_timer <= 0:
if self.state == "ticking":
self.state = "exploding"
elif self.state == "exploding":
self.state = "burning"
elif self.state == "burning":
self.state = "hiding"
class GroundBlock(MapObject):
char = "g"
color = (0, 200, 0)
class Wall(MapObject):
pass
class DestructableWall(Wall):
char = "W"
color = (200, 100, 100)
destructable = True
class IndestructableWall(Wall):
char = "M"
color = (100, 100, 100)
destructable = False
COLLIDING_OBJECTS = (IndestructableWall, DestructableWall, Bomb)
def rest_call(fn):
def foo(self, *args, **kw):
ret = fn(self, *args, **kw)
if ret:
self.client.inform(*ret)
else:
self.client.inform(("ACK", None))
return foo
class Player:
def __init__(self, position, client, name="Hans", color=None, password="", id=None, map=None, async=False):
x, y = position
self.__x = x
self.__y = y
self.resurrect()
# TODO use a real hash
hashpassword = lambda x: x
self.name = name
self.client = client
self.async = async
self.color = {
"1": (255, 0, 0), # red
"2": (0, 0, 255), # blue
"3": (0, 0, 0), # white
"4": (0xFF, 0x66, 0), # orange
"5": (0, 0x80, 0), # green
"6": (0x55, 0x22, 0), # brown
"7": (0x80, 0, 0x80), # purple
"8": (255, 255, 0), # yellow
}[color]
self.password = password
self.speed = 100.
self.bombamount = 10
self.explosion_radius = 10
self.moving = 0 # unit pixel
self.direction = "w" # North
self.id = id
self.map = map
self.points = 0
self.alive = True
self.hidden = False
client.on_message.connect(self.handle_msg)
self.client.inform("OK", self.whoami_data)
self._setup_async_inform_function()
@property
def position_int(self):
return (round(self.frame.left / TILE_WIDTH), round(self.frame.top / TILE_HEIGHT))
@property
def next_position_int(self):
left, top = directions[self.direction]
x, y = self.position_int
return x + left, y + top
@property
def position_float(self):
return (round(self.frame.left / TILE_WIDTH, 1), round(self.frame.top / TILE_HEIGHT, 1))
@property
def delta_position_distance(self):
x, y = self.position_int
x *= TILE_WIDTH
y *= TILE_HEIGHT
return abs(x - self._left) + abs(y - self._top)
@property
def whoami_data(self):
return [self.color, self.id, self._top, self._left]
def get_direction_to_int_position(self):
xi, yi = self.position_int
xf, yf = self.position_float
if xf > xi:
return "a"
elif xf < xi:
return "d"
elif yf > yi:
return "w"
elif yf < yi:
return "s"
def inform_async(self, msg_type, data):
self.client.inform(msg_type, data)
def rest_inform(self, msg_type, data):
accepted_msgtypes = {
"BOMB", "MOVE"
}
if data[0] == self.id and msg_type in accepted_msgtypes:
self.client.inform(msg_type, data)
def _setup_async_inform_function(self):
if not self.async:
self.inform_async = self.rest_inform
def die(self, hard=False):
print("die {}, tonight you dine in hell".format(self.name))
loop = asyncio.get_event_loop()
self.alive = False
self.hidden = True
if not hard:
loop.call_later(5, self.resurrect)
self.points -= 10
def resurrect(self):
self.alive = True
self.hidden = False
self.frame = ui.Rect(self.__x * TILE_WIDTH, self.__y * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT)
self._top = float(self.frame.top)
self._left = float(self.frame.left)
def handle_msg(self, msg):
if not self.alive:
self.client.inform("ERR", "you are dead")
return
msg_type = msg.pop("type")
try:
handler = getattr(self, "do_{}".format(msg_type))
except AttributeError:
self.client.inform("ERR",
"The function ({}) you are calling is not available".format(msg_type))
ret = handler(**msg)
if ret:
msg_type, *rest = ret
self.map.inform_all(msg_type, rest, from_id=self.id)
# self.client.inform(* ret)
def do_move(self, direction, distance=1., **kwargs):
assert direction in "wasd"
assert isinstance(distance, (int, float))
self.direction = direction
self.moving = distance * 10 # TODO, don't use constant
return ("MOVE", self.position_int, direction, distance)
def do_bomb(self, **kwargs):
fuse_time = kwargs.get("fuse_time", 5)
bomb = self.map.plant_bomb(self, fuse_time=fuse_time)
if bomb:
return ("BOMB", ) + bomb.bomb_info()
# REST packets, answer should only go to sender
@rest_call
def do_whoami(self, **kwargs):
return ("WHOAMI", self.whoami_data)
@rest_call
def do_map(self, **kwargs):
return("MAP", "\n".join(
"".join(e.char for e in line) for line in self.map._map),)
@rest_call
def do_what_bombs(self, **kwargs):
return ("WHAT_BOMBS", [
b.bomb_info() for b in self.map.items if isinstance(b, Bomb)
])
@rest_call
def do_what_foes(self, **kwargs):
return ("WHAT_FOES", [
(p.position_int, p.direction, p.id, p.name) for p in self.map.players
])
@rest_call
def do_points(self, **kwargs):
return ("POINTS", [(p.id, p.name, p.points) for p in self.map.players])
def update(self, dt):
if not self.moving > 0 or not self.alive:
return
distance = min(dt * self.speed, self.moving)
self.moving -= distance
left, top = directions[self.direction]
_top = self._top + (top * distance)
_left = self._left + (left * distance)
# collision detection with map border
if _top < 0:
_top = 0
self.moving = 0
if _left < 0:
_left = 0
self.moving = 0
if _top > (self.map.frame.height - TILE_HEIGHT):
_top = (self.map.frame.height - TILE_HEIGHT)
self.moving = 0
if _left > (self.map.frame.width - TILE_WIDTH):
_left = (self.map.frame.width - TILE_WIDTH)
self.moving = 0
# collision detection with walls
frame = ui.Rect(_left, _top, TILE_WIDTH, TILE_HEIGHT) # possible new position
collision_frame = ui.Rect(
min(self.frame.left, frame.left),
min(self.frame.top, frame.top),
abs(self.frame.left - frame.left) + TILE_WIDTH,
abs(self.frame.top - frame.top) + TILE_HEIGHT,
)
# TODO it is the jurisdiction of Map to tell the Player about colliding walls
# Now it is even more complicated to move this to the Map object
# because it cannot inlcude objects that are placed on
collisions = [wall for wall in chain(self.map.walls, self.map.items)
if isinstance(wall, COLLIDING_OBJECTS) and collision_frame.colliderect(wall.frame)
and not self.frame.colliderect(wall.frame)]
if collisions:
collision = True
if self.direction == "w":
# get the lowest box
collisions = sorted(collisions, key=lambda x: x.frame.top, reverse=True)
collider = [c for c in collisions if c.position_int == self.next_position_int]
if collider:
frame.top = collisions[0].frame.bottom
_top = frame.top
else:
# no valid collision
collision = False
elif self.direction == "a":
# get the box farest right
collisions = sorted(collisions, key=lambda x: x.frame.left, reverse=True)
collider = [c for c in collisions if c.position_int == self.next_position_int]
if collider:
frame.left = collisions[0].frame.right
_left = frame.left
else:
# no valid collision
collision = False
elif self.direction == "s":
# get the highest box
collisions = sorted(collisions, key=lambda x: x.frame.top)
collider = [c for c in collisions if c.position_int == self.next_position_int]
if collider:
frame.bottom = collisions[0].frame.top
_top = frame.top
else:
# no valid collision
collision = False
elif self.direction == "d":
# get the box farest left
collisions = sorted(collisions, key=lambda x: x.frame.left)
collider = [c for c in collisions if c.position_int == self.next_position_int]
if collider:
frame.right = collisions[0].frame.left
_left = frame.left
else:
# no valid collision
collision = False
if collision:
self.moving = 0
# TODO send info to client
else:
offset_distance = min(self.delta_position_distance, distance)
distance -= offset_distance
new_direction = self.get_direction_to_int_position()
if new_direction:
left_offset, top_offset = directions[new_direction]
_top = self._top + (top_offset * offset_distance)
_left = self._left + (left_offset * offset_distance)
if distance > 0:
_top += top * distance
_left += left * distance
self.frame.top = self._top = _top
self.frame.left = self._left = _left
if self.moving == 0:
self.map.inform_all("PLAYER_STOPPED", (self.position_int,), from_id=self.id)
class Map(ui.View):
def __init__(self, frame):
super().__init__(frame)
with open("simple.map") as fh:
mapdata = fh.read()
def rand_wall(match):
if random.random() < 0.6:
return " W"
return " g"
mapdata = re.sub(r" ( )", rand_wall, mapdata)
lines = mapdata.splitlines()
spawnpoints = []
freespawnpoints = []
self.walls = []
self.items = []
self.players = []
self.spawnpoints = {}
self.users = {}
self._map = []
for y, mapline in enumerate(lines):
line = []
for x, (attr, block) in enumerate(feedblock(mapline)):
frame = ui.Rect(x * TILE_WIDTH, y * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT)
item = GroundBlock(frame)
if block == "W":
item = DestructableWall(frame)
self.walls.append(item)
elif block == "M":
item = IndestructableWall(frame)
self.walls.append(item)
elif block == "S":
# this is a spawn point
# attr is the start position
self.spawnpoints[attr] = (x, y)
freespawnpoints.append(attr)
line.append(item)
self._map.append(line)
self.freespawnpoints = sorted(freespawnpoints, reverse=True)
self.on_player_join = ui.callback.Signal()
self.on_player_leave = ui.callback.Signal()
self.on_update_player = ui.callback.Signal()
# self.on_keydown.register(self.keydown)
def key_down(self, key, code):
if not self.players:
return
key_code = code.lower()
if key_code in ["w", "a", "s", "d"]:
self.players[0].do_move(key_code, 2.5)
elif code.lower() == "b":
self.players[0].do_bomb()
def player_register(self, client, username, password="", async=False, **kw):
try:
if username in self.users:
position = self.users[username]
else:
position = self.freespawnpoints.pop()
self.users[username] = position
except StopIteration as e:
return False
old_player = self.player_unregister(position, password)
player = Player(
position=self.spawnpoints[position],
client=client,
color=position,
id=position,
map=self,
name=username,
password=password,
async=async,
)
if old_player:
player.points = old_player.points
self.players.append(player)
self.on_update_player(player)
return position
def player_unregister(self, position, password):
old_player = None
for player in self.players:
if player.id == position:
old_player = player
break
if old_player:
assert old_player.password == password
np = [p for p in self.players if p.id != position]
if len(self.players) > len(np):
self.players = np
# self.freespawnpoints.append(position)
return old_player
def inform_all(self, msg_type, msg, from_id="0"):
msg = list(msg)
msg.insert(0, from_id)
for player in self.players:
player.inform_async(msg_type, msg)
def plant_bomb(self, player, fuse_time):
bombs = [b for b in self.items if isinstance(b, Bomb) and b.player is player and b.state == "ticking"]
if len(bombs) >= player.bombamount:
return False
bomb = Bomb(
player=player,
fuse_time=fuse_time,
position=player.position_int,
)
self.items.append(bomb)
return bomb
def draw(self):
if not super().draw():
return False
ui.render.fillrect(self.surface,
[(173, 222, 78), (153, 202, 58)],
ui.Rect(0, 0, self.frame.w, self.frame.h)
)
# draw walls
for wall in self.walls:
ui.render.fillrect(self.surface, wall.color, wall.frame)
# draw items
for item in self.items:
ui.render.fillrect(self.surface, item.color, item.frame)
# draw player
for player in self.players:
if player.hidden:
continue
ui.render.fillrect(self.surface, player.color, player.frame)
return True
def update(self, dt):
for player in self.players:
player.update(dt)
for item in self.items:
item.update(dt)
self.items = [i for i in self.items if not i.hidden]
self.walls = [w for w in self.walls if not w.hidden]