Manages the gameplay logic and its user interactions.
| 7 | |
| 8 | |
| 9 | class Game: |
| 10 | """Manages the gameplay logic and its user interactions.""" |
| 11 | |
| 12 | def __init__(self): |
| 13 | self.display = Display() |
| 14 | self.snake = Snake() |
| 15 | self.score = 0 |
| 16 | self.food = None |
| 17 | self.place_food() |
| 18 | self.high_score = self.load_high_score() |
| 19 | |
| 20 | def game_loop(self): |
| 21 | while True: |
| 22 | self.play_step() |
| 23 | game_over, score = self.play_step() |
| 24 | self.update_high_score(self.high_score) |
| 25 | if game_over: |
| 26 | self.display.render_game_over() |
| 27 | if score > self.high_score: |
| 28 | self.display.render_new_high_score(score) |
| 29 | self.update_high_score(score) |
| 30 | self.high_score = self.load_high_score() |
| 31 | self.display.render_play_again() |
| 32 | if not self.play_again(): |
| 33 | break |
| 34 | self.restart_game() |
| 35 | pygame.quit() |
| 36 | |
| 37 | def is_collision(self): |
| 38 | """Checks if the snake has collided with the boundary or with itself. |
| 39 | |
| 40 | Returns: |
| 41 | bool: True if a collision is detected, False otherwise. |
| 42 | """ |
| 43 | # Snake hits boundary |
| 44 | if ( |
| 45 | self.snake.head.x > self.display.width - self.snake.block_size |
| 46 | or self.snake.head.x < 0 |
| 47 | or self.snake.head.y > self.display.height - self.snake.block_size |
| 48 | or self.snake.head.y < 0 |
| 49 | ): |
| 50 | return True |
| 51 | # Snake hits itself |
| 52 | if self.snake.self_collision(): |
| 53 | return True |
| 54 | return False |
| 55 | |
| 56 | def game_over(self): |
| 57 | return self.is_collision() |
| 58 | |
| 59 | def get_user_input(self): |
| 60 | for event in pygame.event.get(): |
| 61 | if event.type == pygame.QUIT: |
| 62 | pygame.quit() |
| 63 | quit() |
| 64 | if event.type == pygame.KEYDOWN: |
| 65 | if event.key == pygame.K_LEFT: |
| 66 | self.snake.direction = Direction.LEFT |