Untitled
unknown
plain_text
2 years ago
5.2 kB
16
Indexable
from random import choice, randint
import pygame
# Инициализация 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)
# Скорость движения змейки
SPEED = 10
# Настройка игрового окна
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
# Заголовок окна игрового поля
pygame.display.set_caption('Змейка')
# Настройка времени
clock = pygame.time.Clock()
class GameObject:
"""базовый класс объектов."""
def __init__(self, position, body_color):
self.body_color = body_color
self.position = position
def draw(self, surface):
"""метод отрисовки объекта."""
pass
class Apple(GameObject):
"""наследуемый класс, представления яблока."""
def __init__(self, body_color):
super().__init__((0, 0), body_color)
self.randomize_position()
def randomize_position(self):
"""инициализация яблока."""
self.position = (
randint(0, GRID_WIDTH - 1) * GRID_SIZE,
randint(0, GRID_HEIGHT - 1) * GRID_SIZE,
)
def draw(self, surface):
"""метод отрисовки объекта."""
rect = pygame.Rect((self.position[0], self.position[1]), (GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, self.body_color, rect)
pygame.draw.rect(surface, (93, 216, 228), rect, 1)
class Snake(GameObject):
"""наследуемый класс, представления змейки."""
def __init__(self, body_color):
super().__init__((SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2), body_color)
self.length = 1
self.positions = [(self.position[0], self.position[1])]
self.direction = RIGHT
self.next_direction = None
self.color = body_color
self.alive = True
def update_direction(self):
"""метод обновления направления после нажатия на кнопку."""
if self.next_direction:
self.direction = self.next_direction
self.next_direction = None
def move(self, apple_position, apple):
x, y = self.positions[0]
dx, dy = self.direction
new_position = (
(x + dx * GRID_SIZE) % SCREEN_WIDTH,
(y + dy * GRID_SIZE) % SCREEN_HEIGHT,
)
if new_position in self.positions[1:]:
self.alive = False
self.positions.insert(0, new_position)
if new_position != apple_position:
self.positions.pop(-1)
else:
self.length += 1
apple.randomize_position()
def draw(self, surface):
for position in self.positions:
rect = pygame.Rect((position[0], position[1]), (GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, self.color, rect)
pygame.draw.rect(surface, (93, 216, 228), rect, 1)
def reset(self):
"""метод проверки того, врезалась ли змейка в себя"""
self.position = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
self.length = 1
self.positions = [(self.position[0], self.position[1])]
self.direction = RIGHT
self.next_direction = None
self.color = BOARD_BACKGROUND_COLOR
self.alive = True
def handle_keys(game_object):
"""функция обработки действий пользователя."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and game_object.direction != DOWN:
game_object.next_direction = UP
elif event.key == pygame.K_DOWN and game_object.direction != UP:
game_object.next_direction = DOWN
elif event.key == pygame.K_LEFT and game_object.direction != RIGHT:
game_object.next_direction = LEFT
elif event.key == pygame.K_RIGHT and game_object.direction != LEFT:
game_object.next_direction = RIGHT
def main():
apple = Apple((255, 0, 0))
snake = Snake((0, 255, 0))
while True:
clock.tick(SPEED)
handle_keys(snake)
snake.update_direction()
snake.move(apple.position, apple)
if not snake.alive:
snake.reset()
apple.randomize_position()
snake = Snake((0, 255, 0))
screen.fill(BOARD_BACKGROUND_COLOR)
snake.draw(screen)
apple.draw(screen)
pygame.display.update()
if __name__ == "__main__":
main()Editor is loading...
Leave a Comment