forked from janjilecek/pacman_python_pygame
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacman.py
411 lines (338 loc) · 14.6 KB
/
pacman.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
import pygame
import numpy as np
import tcod
import random
from enum import Enum
class Direction(Enum):
LEFT = 0
UP = 1
RIGHT = 2
DOWN = 3,
NONE = 4
def translate_screen_to_maze(in_coords, in_size=32):
return int(in_coords[0] / in_size), int(in_coords[1] / in_size)
def translate_maze_to_screen(in_coords, in_size=32):
return in_coords[0] * in_size, in_coords[1] * in_size
class GameObject:
def __init__(self, in_surface, x, y,
in_size: int, in_color=(255, 0, 0),
is_circle: bool = False):
self._size = in_size
self._renderer: GameRenderer = in_surface
self._surface = in_surface._screen
self.y = y
self.x = x
self._color = in_color
self._circle = is_circle
self._shape = pygame.Rect(self.x, self.y, in_size, in_size)
def draw(self):
if self._circle:
pygame.draw.circle(self._surface,
self._color,
(self.x, self.y),
self._size)
else:
rect_object = pygame.Rect(self.x, self.y, self._size, self._size)
pygame.draw.rect(self._surface,
self._color,
rect_object,
border_radius=4)
def tick(self):
pass
def get_shape(self):
return self._shape
def set_position(self, in_x, in_y):
self.x = in_x
self.y = in_y
def get_position(self):
return (self.x, self.y)
class Wall(GameObject):
def __init__(self, in_surface, x, y, in_size: int, in_color=(0, 0, 255)):
super().__init__(in_surface, x * in_size, y * in_size, in_size, in_color)
class GameRenderer:
def __init__(self, in_width: int, in_height: int):
pygame.init()
self._width = in_width
self._height = in_height
self._screen = pygame.display.set_mode((in_width, in_height))
pygame.display.set_caption('Pacman')
self._clock = pygame.time.Clock()
self._done = False
self._game_objects = []
self._walls = []
self._cookies = []
self._hero: Hero = None
def tick(self, in_fps: int):
black = (0, 0, 0)
while not self._done:
for game_object in self._game_objects:
game_object.tick()
game_object.draw()
pygame.display.flip()
self._clock.tick(in_fps)
self._screen.fill(black)
self._handle_events()
print("Game over")
def add_game_object(self, obj: GameObject):
self._game_objects.append(obj)
def add_cookie(self, obj: GameObject):
self._game_objects.append(obj)
self._cookies.append(obj)
def add_wall(self, obj: Wall):
self.add_game_object(obj)
self._walls.append(obj)
def get_walls(self):
return self._walls
def get_cookies(self):
return self._cookies
def get_game_objects(self):
return self._game_objects
def add_hero(self, in_hero):
self.add_game_object(in_hero)
self._hero = in_hero
def _handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self._done = True
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
self._hero.set_direction(Direction.UP)
elif pressed[pygame.K_LEFT]:
self._hero.set_direction(Direction.LEFT)
elif pressed[pygame.K_DOWN]:
self._hero.set_direction(Direction.DOWN)
elif pressed[pygame.K_RIGHT]:
self._hero.set_direction(Direction.RIGHT)
class MovableObject(GameObject):
def __init__(self, in_surface, x, y, in_size: int, in_color=(255, 0, 0), is_circle: bool = False):
super().__init__(in_surface, x, y, in_size, in_color, is_circle)
self.current_direction = Direction.NONE
self.direction_buffer = Direction.NONE
self.last_working_direction = Direction.NONE
self.location_queue = []
self.next_target = None
def get_next_location(self):
return None if len(self.location_queue) == 0 else self.location_queue.pop(0)
def set_direction(self, in_direction):
self.current_direction = in_direction
self.direction_buffer = in_direction
def collides_with_wall(self, in_position):
collision_rect = pygame.Rect(in_position[0], in_position[1], self._size, self._size)
collides = False
walls = self._renderer.get_walls()
for wall in walls:
collides = collision_rect.colliderect(wall.get_shape())
if collides: break
return collides
def check_collision_in_direction(self, in_direction: Direction):
desired_position = (0, 0)
if in_direction == Direction.NONE: return False, desired_position
if in_direction == Direction.UP:
desired_position = (self.x, self.y - 1)
elif in_direction == Direction.DOWN:
desired_position = (self.x, self.y + 1)
elif in_direction == Direction.LEFT:
desired_position = (self.x - 1, self.y)
elif in_direction == Direction.RIGHT:
desired_position = (self.x + 1, self.y)
return self.collides_with_wall(desired_position), desired_position
def automatic_move(self, in_direction: Direction):
pass
def tick(self):
self.reached_target()
self.automatic_move(self.current_direction)
def reached_target(self):
pass
class Hero(MovableObject):
def __init__(self, in_surface, x, y, in_size: int):
super().__init__(in_surface, x, y, in_size, (255, 255, 0), False)
self.last_non_colliding_position = (0, 0)
def tick(self):
# TELEPORT
if self.x < 0:
self.x = self._renderer._width
if self.x > self._renderer._width:
self.x = 0
self.last_non_colliding_position = self.get_position()
if self.check_collision_in_direction(self.direction_buffer)[0]:
self.automatic_move(self.current_direction)
else:
self.automatic_move(self.direction_buffer)
self.current_direction = self.direction_buffer
if self.collides_with_wall((self.x, self.y)):
self.set_position(self.last_non_colliding_position[0], self.last_non_colliding_position[1])
self.handle_cookie_pickup()
def automatic_move(self, in_direction: Direction):
collision_result = self.check_collision_in_direction(in_direction)
desired_position_collides = collision_result[0]
if not desired_position_collides:
self.last_working_direction = self.current_direction
desired_position = collision_result[1]
self.set_position(desired_position[0], desired_position[1])
else:
self.current_direction = self.last_working_direction
def handle_cookie_pickup(self):
collision_rect = pygame.Rect(self.x, self.y, self._size, self._size)
cookies = self._renderer.get_cookies()
game_objects = self._renderer.get_game_objects()
for cookie in cookies:
collides = collision_rect.colliderect(cookie.get_shape())
if collides and cookie in game_objects:
game_objects.remove(cookie)
def draw(self):
half_size = self._size / 2
pygame.draw.circle(self._surface, self._color, (self.x + half_size, self.y + half_size), half_size)
class Ghost(MovableObject):
def __init__(self, in_surface, x, y, in_size: int, in_game_controller, in_color=(255, 0, 0)):
super().__init__(in_surface, x, y, in_size, in_color, False)
self.game_controller = in_game_controller
def reached_target(self):
if (self.x, self.y) == self.next_target:
self.next_target = self.get_next_location()
self.current_direction = self.calculate_direction_to_next_target()
def set_new_path(self, in_path):
for item in in_path:
self.location_queue.append(item)
self.next_target = self.get_next_location()
def calculate_direction_to_next_target(self) -> Direction:
if self.next_target is None:
self.game_controller.request_new_random_path(self)
return Direction.NONE
diff_x = self.next_target[0] - self.x
diff_y = self.next_target[1] - self.y
if diff_x == 0:
return Direction.DOWN if diff_y > 0 else Direction.UP
if diff_y == 0:
return Direction.LEFT if diff_x < 0 else Direction.RIGHT
self.game_controller.request_new_random_path(self)
return Direction.NONE
def automatic_move(self, in_direction: Direction):
if in_direction == Direction.UP:
self.set_position(self.x, self.y - 1)
elif in_direction == Direction.DOWN:
self.set_position(self.x, self.y + 1)
elif in_direction == Direction.LEFT:
self.set_position(self.x - 1, self.y)
elif in_direction == Direction.RIGHT:
self.set_position(self.x + 1, self.y)
class Cookie(GameObject):
def __init__(self, in_surface, x, y):
super().__init__(in_surface, x, y, 4, (255, 255, 0), True)
class Pathfinder:
def __init__(self, in_arr):
cost = np.array(in_arr, dtype=np.bool_).tolist()
self.pf = tcod.path.AStar(cost=cost, diagonal=0)
def get_path(self, from_x, from_y, to_x, to_y) -> object:
res = self.pf.get_path(from_x, from_y, to_x, to_y)
return [(sub[1], sub[0]) for sub in res]
class PacmanGameController:
def __init__(self):
self.ascii_maze = [
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"XP XX X",
"X XXXX XXXXX XX XXXXX XXXX X",
"X XXXX XXXXX XX XXXXX XXXX X",
"X XXXX XXXXX XX XXXXX XXXX X",
"X X",
"X XXXX XX XXXXXXXX XX XXXX X",
"X XXXX XX XXXXXXXX XX XXXX X",
"X XX XX XX X",
"XXXXXX XXXXX XX XXXXX XXXXXX",
"XXXXXX XXXXX XX XXXXX XXXXXX",
"XXXXXX XX XX XXXXXX",
"XXXXXX XX XXXXXXXX XX XXXXXX",
"XXXXXX XX X G X XX XXXXXX",
" X G X ",
"XXXXXX XX X G X XX XXXXXX",
"XXXXXX XX XXXXXXXX XX XXXXXX",
"XXXXXX XX XX XXXXXX",
"XXXXXX XX XXXXXXXX XX XXXXXX",
"XXXXXX XX XXXXXXXX XX XXXXXX",
"X XX X",
"X XXXX XXXXX XX XXXXX XXXX X",
"X XXXX XXXXX XX XXXXX XXXX X",
"X XX G XX X",
"XXX XX XX XXXXXXXX XX XX XXX",
"XXX XX XX XXXXXXXX XX XX XXX",
"X XX XX XX X",
"X XXXXXXXXXX XX XXXXXXXXXX X",
"X XXXXXXXXXX XX XXXXXXXXXX X",
"X X",
"XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
]
self.numpy_maze = []
self.cookie_spaces = []
self.reachable_spaces = []
self.ghost_spawns = []
self.ghost_colors = [
(255, 184, 255),
(255, 0, 20),
(0, 255, 255),
(255, 184, 82)
]
self.size = (0, 0)
self.convert_maze_to_numpy()
self.p = Pathfinder(self.numpy_maze)
def request_new_random_path(self, in_ghost: Ghost):
random_space = random.choice(self.reachable_spaces)
current_maze_coord = translate_screen_to_maze(in_ghost.get_position())
path = self.p.get_path(current_maze_coord[1], current_maze_coord[0], random_space[1],
random_space[0])
test_path = [translate_maze_to_screen(item) for item in path]
in_ghost.set_new_path(test_path)
def convert_maze_to_numpy(self):
for x, row in enumerate(self.ascii_maze):
self.size = (len(row), x + 1)
binary_row = []
for y, column in enumerate(row):
if column == "G":
self.ghost_spawns.append((y, x))
if column == "X":
binary_row.append(0)
else:
binary_row.append(1)
self.cookie_spaces.append((y, x))
self.reachable_spaces.append((y, x))
self.numpy_maze.append(binary_row)
if __name__ == "__main__":
unified_size = 32
pacman_game = PacmanGameController()
size = pacman_game.size
game_renderer = GameRenderer(size[0] * unified_size, size[1] * unified_size)
for y, row in enumerate(pacman_game.numpy_maze):
for x, column in enumerate(row):
if column == 0:
game_renderer.add_wall(Wall(game_renderer, x, y, unified_size))
# Vykresleni cesty
# red = (255, 0, 0)
# green = (0, 255, 0)
# _from = (1, 1)
# _to = (24, 24)
# path_array = pacman_game.p.get_path(_from[1], _from[0], _to[1], _to[0])
#
# print(path_array)
# # [(1, 2), (1, 3), (1, 4), (1, 5), (2, 5), (3, 5), (4, 5), (5, 5), (6, 5), (6, 6), (6, 7) ...
#
# white = (255, 255, 255)
# for path in path_array:
# game_renderer.add_game_object(Wall(game_renderer, path[0], path[1], unified_size, white))
#
# from_translated = translate_maze_to_screen(_from)
# game_renderer.add_game_object(
# GameObject(game_renderer, from_translated[0], from_translated[1], unified_size, red))
#
# to_translated = translate_maze_to_screen(_to)
# game_renderer.add_game_object(
# GameObject(game_renderer, to_translated[0], to_translated[1], unified_size, green))
for cookie_space in pacman_game.cookie_spaces:
translated = translate_maze_to_screen(cookie_space)
cookie = Cookie(game_renderer, translated[0] + unified_size / 2, translated[1] + unified_size / 2)
game_renderer.add_cookie(cookie)
for i, ghost_spawn in enumerate(pacman_game.ghost_spawns):
translated = translate_maze_to_screen(ghost_spawn)
ghost = Ghost(game_renderer, translated[0], translated[1], unified_size, pacman_game,
pacman_game.ghost_colors[i % 4])
game_renderer.add_game_object(ghost)
pacman = Hero(game_renderer, unified_size, unified_size, unified_size)
game_renderer.add_hero(pacman)
game_renderer.tick(120)