karen_constantine

Untitled

Oct 28th, 2023
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.04 KB | None | 0 0
  1. import pygame # import packages (install with "pip install pygame" in cmd)
  2. import numpy as np
  3. import tcod
  4.  
  5. class GameRenderer:
  6. def __init__(self, in_width: int, in_height: int):
  7. pygame.init()
  8. self._width = in_width
  9. self._height = in_height
  10. self._screen = pygame.display.set_mode((in_width, in_height))
  11. pygame.display.set_caption('Pacman')
  12. self._clock = pygame.time.Clock()
  13. self._done = False
  14. self._game_objects = []
  15. self._walls = []
  16. self._cookies = []
  17. self._hero: Hero = None
  18.  
  19. def tick(self, in_fps: int):
  20. black = (0, 0, 0)
  21. while not self._done:
  22. for game_object in self._game_objects:
  23. game_object.tick()
  24. game_object.draw()
  25.  
  26. pygame.display.flip()
  27. self._clock.tick(in_fps)
  28. self._screen.fill(black)
  29. self._handle_events()
  30. print("Game over")
  31.  
  32. def add_game_object(self, obj: GameObject):
  33. self._game_objects.append(obj)
  34.  
  35.  
  36. def add_wall(self, obj: Wall):
  37. self.add_game_object(obj)
  38. self._walls.append(obj)
  39.  
  40. def _handle_events(self):
  41. pass # we'll implement this later
  42. class GameObject:
  43. def __init__(self, in_surface, x, y,
  44. in_size: int, in_color=(255, 0, 0),
  45. is_circle: bool = False):
  46. self._size = in_size
  47. self._renderer: GameRenderer = in_surface
  48. self._surface = in_surface._screen
  49. self.y = y
  50. self.x = x
  51. self._color = in_color
  52. self._circle = is_circle
  53. self._shape = pygame.Rect(self.x, self.y, in_size, in_size)
  54.  
  55. def draw(self):
  56. if self._circle:
  57. pygame.draw.circle(self._surface,
  58. self._color,
  59. (self.x, self.y),
  60. self._size)
  61. else:
  62. rect_object = pygame.Rect(self.x, self.y, self._size, self._size)
  63. pygame.draw.rect(self._surface,
  64. self._color,
  65. rect_object,
  66. border_radius=4)
  67.  
  68. def tick(self):
  69. pass
  70. class Wall(GameObject):
  71. def __init__(self, in_surface, x, y, in_size: int, in_color=(0, 0, 255)):
  72. super().__init__(in_surface, x * in_size, y * in_size, in_size, in_color)
  73. class PacmanGameController:
  74. def __init__(self):
  75. self.ascii_maze = [
  76. "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  77. "XP XX X",
  78. "X XXXX XXXXX XX XXXXX XXXX X",
  79. "X XXXX XXXXX XX XXXXX XXXX X",
  80. "X XXXX XXXXX XX XXXXX XXXX X",
  81. "X X",
  82. "X XXXX XX XXXXXXXX XX XXXX X",
  83. "X XXXX XX XXXXXXXX XX XXXX X",
  84. "X XX XX XX X",
  85. "XXXXXX XXXXX XX XXXXX XXXXXX",
  86. "XXXXXX XXXXX XX XXXXX XXXXXX",
  87. "XXXXXX XX XX XXXXXX",
  88. "XXXXXX XX XXXXXXXX XX XXXXXX",
  89. "XXXXXX XX X G X XX XXXXXX",
  90. " X G X ",
  91. "XXXXXX XX X G X XX XXXXXX",
  92. # shortened for article, full ascii on my github
  93. "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  94. ]
  95.  
  96. self.numpy_maze = []
  97. self.cookie_spaces = []
  98. self.reachable_spaces = []
  99. self.ghost_spawns = []
  100.  
  101. self.size = (0, 0)
  102. self.convert_maze_to_numpy()
  103. #self.p = Pathfinder(self.numpy_maze) # use later
  104.  
  105.  
  106. def convert_maze_to_numpy(self):
  107. for x, row in enumerate(self.ascii_maze):
  108. self.size = (len(row), x + 1)
  109. binary_row = []
  110. for y, column in enumerate(row):
  111. if column == "G":
  112. self.ghost_spawns.append((y, x))
  113.  
  114. if column == "X":
  115. binary_row.append(0)
  116. else:
  117. binary_row.append(1)
  118. self.cookie_spaces.append((y, x))
  119. self.reachable_spaces.append((y, x))
  120. self.numpy_maze.append(binary_row)
  121. if __name__ == "__main__":
  122. unified_size = 32
  123. pacman_game = PacmanGameController()
  124. size = pacman_game.size
  125. game_renderer = GameRenderer(size[0] * unified_size, size[1] * unified_size)
  126.  
  127. for y, row in enumerate(pacman_game.numpy_maze):
  128. for x, column in enumerate(row):
  129. if column == 0:
  130. game_renderer.add_wall(Wall(game_renderer, x, y, unified_size))
  131.  
  132. game_renderer.tick(120)
  133. class Ghost(MovableObject):
  134. def __init__(self, in_surface, x, y, in_size: int, in_game_controller, in_color=(255, 0, 0)):
  135. super().__init__(in_surface, x, y, in_size, in_color, False)
  136. self.game_controller = in_game_controller
  137. # inPacmanGameController
  138. self.ghost_colors = [
  139. (255, 184, 255),
  140. (255, 0, 20),
  141. (0, 255, 255),
  142. (255, 184, 82)
  143. ]
  144.  
  145. # in main
  146. for i, ghost_spawn in enumerate(pacman_game.ghost_spawns):
  147. translated = translate_maze_to_screen(ghost_spawn)
  148. ghost = Ghost(game_renderer, translated[0], translated[1], unified_size, pacman_game,
  149. pacman_game.ghost_colors[i % 4])
  150. game_renderer.add_game_object(ghost)
  151.  
  152. # General functions for coordinate conversion, place at the beginning of the code
  153. def translate_screen_to_maze(in_coords, in_size=32):
  154. return int(in_coords[0] / in_size), int(in_coords[1] / in_size)
  155.  
  156. def translate_maze_to_screen(in_coords, in_size=32):
  157. return in_coords[0] * in_size, in_coords[1] * in_size
  158. class Pathfinder:
  159. def __init__(self, in_arr):
  160. cost = np.array(in_arr, dtype=np.bool_).tolist()
  161. self.pf = tcod.path.AStar(cost=cost, diagonal=0)
  162.  
  163. def get_path(self, from_x, from_y, to_x, to_y) -> object:
  164. res = self.pf.get_path(from_x, from_y, to_x, to_y)
  165. return [(sub[1], sub[0]) for sub in res]
  166. # draw path - optional
  167. red = (255, 0, 0)
  168. green = (0, 255, 0)
  169. _from = (1, 1)
  170. _to = (24, 24)
  171. path_array = pacman_game.p.get_path(_from[1], _from[0], _to[1], _to[0])
  172.  
  173. print(path_array)
  174. # [(1, 2), (1, 3), (1, 4), (1, 5), (2, 5), (3, 5), (4, 5), (5, 5), (6, 5), (6, 6), (6, 7) ...
  175.  
  176. white = (255, 255, 255)
  177. for path in path_array:
  178. game_renderer.add_game_object(Wall(game_renderer, path[0], path[1], unified_size, white))
  179.  
  180. from_translated = translate_maze_to_screen(_from)
  181. game_renderer.add_game_object(
  182. GameObject(game_renderer, from_translated[0], from_translated[1], unified_size, red))
  183.  
  184. to_translated = translate_maze_to_screen(_to)
  185. game_renderer.add_game_object(
  186. GameObject(game_renderer, to_translated[0], to_translated[1], unified_size, green))
  187.  
  188. def request_new_random_path(self, in_ghost: Ghost):
  189. random_space = random.choice(self.reachable_spaces)
  190. current_maze_coord = translate_screen_to_maze(in_ghost.get_position())
  191.  
  192. path = self.p.get_path(current_maze_coord[1], current_maze_coord[0], random_space[1],
  193. random_space[0])
  194. test_path = [translate_maze_to_screen(item) for item in path]
  195. in_ghost.set_new_path(test_path)
  196. def reached_target(self):
  197. if (self.x, self.y) == self.next_target:
  198. self.next_target = self.get_next_location()
  199. self.current_direction = self.calculate_direction_to_next_target()
  200.  
  201. def set_new_path(self, in_path):
  202. for item in in_path:
  203. self.location_queue.append(item)
  204. self.next_target = self.get_next_location()
  205.  
  206. def calculate_direction_to_next_target(self) -> Direction:
  207. if self.next_target is None:
  208. self.game_controller.request_new_random_path(self)
  209. return Direction.NONE
  210. diff_x = self.next_target[0] - self.x
  211. diff_y = self.next_target[1] - self.y
  212. if diff_x == 0:
  213. return Direction.DOWN if diff_y > 0 else Direction.UP
  214. if diff_y == 0:
  215. return Direction.LEFT if diff_x < 0 else Direction.RIGHT
  216. self.game_controller.request_new_random_path(self)
  217. return Direction.NONE
  218.  
  219. def automatic_move(self, in_direction: Direction):
  220. if in_direction == Direction.UP:
  221. self.set_position(self.x, self.y - 1)
  222. elif in_direction == Direction.DOWN:
  223. self.set_position(self.x, self.y + 1)
  224. elif in_direction == Direction.LEFT:
  225. self.set_position(self.x - 1, self.y)
  226. elif in_direction == Direction.RIGHT:
  227. self.set_position(self.x + 1, self.y)
  228.  
  229. class Hero(MovableObject):
  230. def __init__(self, in_surface, x, y, in_size: int):
  231. super().__init__(in_surface, x, y, in_size, (255, 255, 0), False)
  232. self.last_non_colliding_position = (0, 0)
  233.  
  234. def tick(self):
  235. # TELEPORT
  236. if self.x < 0:
  237. self.x = self._renderer._width
  238.  
  239. if self.x > self._renderer._width:
  240. self.x = 0
  241.  
  242. self.last_non_colliding_position = self.get_position()
  243.  
  244. if self.check_collision_in_direction(self.direction_buffer)[0]:
  245. self.automatic_move(self.current_direction)
  246. else:
  247. self.automatic_move(self.direction_buffer)
  248. self.current_direction = self.direction_buffer
  249.  
  250. if self.collides_with_wall((self.x, self.y)):
  251. self.set_position(self.last_non_colliding_position[0], self.last_non_colliding_position[1])
  252.  
  253. self.handle_cookie_pickup()
  254.  
  255. def automatic_move(self, in_direction: Direction):
  256. collision_result = self.check_collision_in_direction(in_direction)
  257.  
  258. desired_position_collides = collision_result[0]
  259. if not desired_position_collides:
  260. self.last_working_direction = self.current_direction
  261. desired_position = collision_result[1]
  262. self.set_position(desired_position[0], desired_position[1])
  263. else:
  264. self.current_direction = self.last_working_direction
  265.  
  266. def handle_cookie_pickup(self):
  267. collision_rect = pygame.Rect(self.x, self.y, self._size, self._size)
  268. cookies = self._renderer.get_cookies()
  269. game_objects = self._renderer.get_game_objects()
  270. for cookie in cookies:
  271. collides = collision_rect.colliderect(cookie.get_shape())
  272. if collides and cookie in game_objects:
  273. game_objects.remove(cookie)
  274.  
  275. def draw(self):
  276. half_size = self._size / 2
  277. pygame.draw.circle(self._surface, self._color, (self.x + half_size, self.y + half_size), half_size)
  278. # in GameRenderer class
  279. def add_hero(self, in_hero):
  280. self.add_game_object(in_hero)
  281. self._hero = in_hero
  282.  
  283. def _handle_events(self):
  284. for event in pygame.event.get():
  285. if event.type == pygame.QUIT:
  286. self._done = True
  287.  
  288. pressed = pygame.key.get_pressed()
  289. if pressed[pygame.K_UP]:
  290. self._hero.set_direction(Direction.UP)
  291. elif pressed[pygame.K_LEFT]:
  292. self._hero.set_direction(Direction.LEFT)
  293. elif pressed[pygame.K_DOWN]:
  294. self._hero.set_direction(Direction.DOWN)
  295. elif pressed[pygame.K_RIGHT]:
  296. self._hero.set_direction(Direction.RIGHT)
  297.  
  298.  
  299. # at the end of main function
  300. pacman = Hero(game_renderer, unified_size, unified_size, unified_size)
  301. game_renderer.add_hero(pacman)
  302. game_renderer.tick(120)
  303. class Cookie(GameObject):
  304. def __init__(self, in_surface, x, y):
  305. super().__init__(in_surface, x, y, 4, (255, 255, 0), True)
  306.  
  307. # in GameRenderer class
  308. def add_cookie(self, obj: GameObject):
  309. self._game_objects.append(obj)
  310. self._cookies.append(obj)
  311.  
  312. # in Hero class
  313. def handle_cookie_pickup(self):
  314. collision_rect = pygame.Rect(self.x, self.y, self._size, self._size)
  315. cookies = self._renderer.get_cookies()
  316. game_objects = self._renderer.get_game_objects()
  317. for cookie in cookies:
  318. collides = collision_rect.colliderect(cookie.get_shape())
  319. if collides and cookie in game_objects:
  320. game_objects.remove(cookie)
  321.  
  322. # in main function:
  323. for cookie_space in pacman_game.cookie_spaces:
  324. translated = translate_maze_to_screen(cookie_space)
  325. cookie = Cookie(game_renderer, translated[0] + unified_size / 2, translated[1] + unified_size / 2)
  326. game_renderer.add_cookie(cookie)
  327.  
Advertisement
Add Comment
Please, Sign In to add comment