Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import randint
- import pygame
- pygame.init()
- # Константы для размеров поля и сетки:
- SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
- GRID_SIZE = 20
- GRID_WIDTH = SCREEN_WIDTH // GRID_SIZE
- GRID_HEIGHT = SCREEN_HEIGHT // GRID_SIZE
- # Направления движения:
- UP = (0, -1)
- DOWN = (0, 1)
- LEFT = (-1, 0)
- RIGHT = (1, 0)
- # Цвет фона - черный:
- BOARD_BACKGROUND_COLOR = (0, 0, 0)
- # Цвет границы ячейки
- BORDER_COLOR = (93, 216, 228)
- # Цвет яблока
- APPLE_COLOR = (255, 0, 2)
- # Цвет змейки
- SNAKE_COLOR = (111, 111, 111)
- # Скорость движения змейки:
- SPEED = 20
- # Настройка игрового окна:
- screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
- # Заголовок окна игрового поля:
- pygame.display.set_caption('Змейка')
- # Настройка времени:
- clock = pygame.time.Clock()
- class GameObject:
- """Базовый класс."""
- def __init__(self):
- """Метод инициализации."""
- self.body_color = None
- self.position = [SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2]
- def draw(self):
- """Метод отрисовки."""
- raise NotImplementedError
- class Snake(GameObject):
- """Класс змейки."""
- def __init__(self):
- """Метод инициализации."""
- super().__init__()
- self.positions = [self.position]
- self.reset()
- def update_direction(self):
- """Метод обновления метонахождения змейки."""
- if self.next_direction is not None:
- if self.next_direction == UP and self.direction != DOWN:
- self.direction = UP
- if self.next_direction == DOWN and self.direction != UP:
- self.direction = DOWN
- if self.next_direction == LEFT and self.direction != RIGHT:
- self.direction = LEFT
- if self.next_direction == RIGHT and self.direction != LEFT:
- self.direction = RIGHT
- self.next_direction = None
- def move(self):
- """Метод движения."""
- head_position = list(self.get_head_position())
- head_position[0] += self.direction[0] * GRID_SIZE
- head_position[1] += self.direction[1] * GRID_SIZE
- head_position[0] = head_position[0] % SCREEN_WIDTH
- head_position[1] = head_position[1] % SCREEN_HEIGHT
- self.positions.insert(0, head_position)
- if len(self.positions) > self.length:
- self.positions.pop()
- def draw(self):
- """Метод отрисовки."""
- for pos in self.positions:
- pygame.draw.rect(screen, self.body_color, pygame.Rect(pos[0],
- pos[1],
- GRID_SIZE,
- GRID_SIZE))
- def get_head_position(self):
- """Метод расположения головы."""
- return self.positions[0]
- def reset(self):
- """Метод сброса."""
- self.length = 1
- self.positions = [self.position]
- self.direction = RIGHT
- self.next_direction = None
- self.body_color = SNAKE_COLOR
- class Apple(GameObject):
- """Класс яблока."""
- def __init__(self, snake=None):
- """Метод инициализации."""
- super().__init__()
- self.body_color = APPLE_COLOR
- self.randomize_position(snake)
- def randomize_position(self, snake=None):
- """Метод случайного появления яблока."""
- self.position = [randint(1, GRID_WIDTH - 1) * GRID_SIZE,
- randint(1, GRID_HEIGHT - 1) * GRID_SIZE]
- if snake and self.position not in snake.positions:
- return
- def draw(self):
- """Метод отрисовки."""
- pygame.draw.rect(screen, self.body_color, pygame.Rect(self.position[0],
- self.position[1],
- GRID_SIZE,
- GRID_SIZE))
- def handle_keys(snake):
- """Метод привязки движения."""
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- pygame.quit()
- elif event.type == pygame.KEYDOWN:
- if event.key == pygame.K_UP:
- snake.next_direction = UP
- elif event.key == pygame.K_DOWN:
- snake.next_direction = DOWN
- elif event.key == pygame.K_LEFT:
- snake.next_direction = LEFT
- elif event.key == pygame.K_RIGHT:
- snake.next_direction = RIGHT
- def main():
- """Основная функция игры."""
- snake = Snake()
- apple = Apple(snake)
- while True:
- handle_keys(snake)
- snake.update_direction()
- snake.move()
- if snake.get_head_position() == apple.position:
- apple.randomize_position(snake)
- snake.length += 1
- for position in snake.positions[1:]:
- if snake.get_head_position() == position:
- snake.reset()
- screen.fill(BOARD_BACKGROUND_COLOR)
- snake.draw()
- apple.draw()
- pygame.display.update()
- clock.tick(SPEED)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment