boris-vlasenko

змейка2

Mar 1st, 2024 (edited)
877
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.65 KB | None | 0 0
  1. from random import randint
  2.  
  3. import pygame
  4.  
  5.  
  6. pygame.init()
  7.  
  8. # Константы для размеров поля и сетки:
  9. SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
  10. GRID_SIZE = 20
  11. GRID_WIDTH = SCREEN_WIDTH // GRID_SIZE
  12. GRID_HEIGHT = SCREEN_HEIGHT // GRID_SIZE
  13.  
  14. # Направления движения:
  15. UP = (0, -1)
  16. DOWN = (0, 1)
  17. LEFT = (-1, 0)
  18. RIGHT = (1, 0)
  19.  
  20. # Цвет фона - черный:
  21. BOARD_BACKGROUND_COLOR = (0, 0, 0)
  22.  
  23. # Цвет границы ячейки
  24. BORDER_COLOR = (93, 216, 228)
  25.  
  26. # Цвет яблока
  27. APPLE_COLOR = (255, 0, 2)
  28.  
  29. # Цвет змейки
  30. SNAKE_COLOR = (111, 111, 111)
  31.  
  32. # Скорость движения змейки:
  33. SPEED = 20
  34.  
  35. # Настройка игрового окна:
  36. screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
  37.  
  38. # Заголовок окна игрового поля:
  39. pygame.display.set_caption('Змейка')
  40.  
  41. # Настройка времени:
  42. clock = pygame.time.Clock()
  43.  
  44.  
  45. class GameObject:
  46.     """Базовый класс."""
  47.  
  48.     def __init__(self):
  49.         """Метод инициализации."""
  50.         self.body_color = None
  51.         self.position = [SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2]
  52.  
  53.     def draw(self):
  54.         """Метод отрисовки."""
  55.         raise NotImplementedError
  56.  
  57.  
  58. class Snake(GameObject):
  59.     """Класс змейки."""
  60.  
  61.     def __init__(self):
  62.         """Метод инициализации."""
  63.         super().__init__()
  64.         self.positions = [self.position]
  65.         self.reset()
  66.  
  67.     def update_direction(self):
  68.         """Метод обновления метонахождения змейки."""
  69.         if self.next_direction is not None:
  70.             if self.next_direction == UP and self.direction != DOWN:
  71.                 self.direction = UP
  72.             if self.next_direction == DOWN and self.direction != UP:
  73.                 self.direction = DOWN
  74.             if self.next_direction == LEFT and self.direction != RIGHT:
  75.                 self.direction = LEFT
  76.             if self.next_direction == RIGHT and self.direction != LEFT:
  77.                 self.direction = RIGHT
  78.             self.next_direction = None
  79.  
  80.     def move(self):
  81.         """Метод движения."""
  82.         head_position = list(self.get_head_position())
  83.         head_position[0] += self.direction[0] * GRID_SIZE
  84.         head_position[1] += self.direction[1] * GRID_SIZE
  85.  
  86.         head_position[0] = head_position[0] % SCREEN_WIDTH
  87.         head_position[1] = head_position[1] % SCREEN_HEIGHT
  88.  
  89.         self.positions.insert(0, head_position)
  90.         if len(self.positions) > self.length:
  91.             self.positions.pop()
  92.  
  93.     def draw(self):
  94.         """Метод отрисовки."""
  95.         for pos in self.positions:
  96.             pygame.draw.rect(screen, self.body_color, pygame.Rect(pos[0],
  97.                                                                   pos[1],
  98.                                                                   GRID_SIZE,
  99.                                                                   GRID_SIZE))
  100.  
  101.     def get_head_position(self):
  102.         """Метод расположения головы."""
  103.         return self.positions[0]
  104.  
  105.     def reset(self):
  106.         """Метод сброса."""
  107.         self.length = 1
  108.         self.positions = [self.position]
  109.         self.direction = RIGHT
  110.         self.next_direction = None
  111.         self.body_color = SNAKE_COLOR
  112.  
  113.  
  114. class Apple(GameObject):
  115.     """Класс яблока."""
  116.  
  117.     def __init__(self, snake=None):
  118.         """Метод инициализации."""
  119.         super().__init__()
  120.         self.body_color = APPLE_COLOR
  121.         self.randomize_position(snake)
  122.  
  123.     def randomize_position(self, snake=None):
  124.         """Метод случайного появления яблока."""
  125.         self.position = [randint(1, GRID_WIDTH - 1) * GRID_SIZE,
  126.                             randint(1, GRID_HEIGHT - 1) * GRID_SIZE]
  127.         if snake and self.position not in snake.positions:
  128.             return
  129.  
  130.     def draw(self):
  131.         """Метод отрисовки."""
  132.         pygame.draw.rect(screen, self.body_color, pygame.Rect(self.position[0],
  133.                                                               self.position[1],
  134.                                                               GRID_SIZE,
  135.                                                               GRID_SIZE))
  136.  
  137.  
  138. def handle_keys(snake):
  139.     """Метод привязки движения."""
  140.     for event in pygame.event.get():
  141.         if event.type == pygame.QUIT:
  142.             pygame.quit()
  143.         elif event.type == pygame.KEYDOWN:
  144.             if event.key == pygame.K_UP:
  145.                 snake.next_direction = UP
  146.             elif event.key == pygame.K_DOWN:
  147.                 snake.next_direction = DOWN
  148.             elif event.key == pygame.K_LEFT:
  149.                 snake.next_direction = LEFT
  150.             elif event.key == pygame.K_RIGHT:
  151.                 snake.next_direction = RIGHT
  152.  
  153.  
  154. def main():
  155.     """Основная функция игры."""
  156.     snake = Snake()
  157.     apple = Apple(snake)
  158.  
  159.     while True:
  160.         handle_keys(snake)
  161.         snake.update_direction()
  162.         snake.move()
  163.  
  164.         if snake.get_head_position() == apple.position:
  165.             apple.randomize_position(snake)
  166.             snake.length += 1
  167.  
  168.         for position in snake.positions[1:]:
  169.             if snake.get_head_position() == position:
  170.                 snake.reset()
  171.  
  172.         screen.fill(BOARD_BACKGROUND_COLOR)
  173.         snake.draw()
  174.         apple.draw()
  175.         pygame.display.update()
  176.         clock.tick(SPEED)
  177.  
  178.  
  179. if __name__ == '__main__':
  180.     main()
  181.  
Tags: змейка
Advertisement
Add Comment
Please, Sign In to add comment