Загрузка данных
import pygame
import random
import sys
# Инициализация pygame
pygame.init()
# Константы игры
WIDTH, HEIGHT = 800, 600
BLOCK_SIZE = 20
SPEED = 10
# Цвета
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Создание экрана
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Змейка")
clock = pygame.time.Clock()
class SnakeGame:
def __init__(self):
self.snake = [(200, 200), (180, 200), (160, 200)] # Начальная позиция змеи
self.direction = 'RIGHT'
self.food = self.generate_food()
self.score = 0
self.font = pygame.font.Font(None, 36)
def generate_food(self):
"""Генерация новой еды в случайном месте"""
while True:
x = random.randrange(0, WIDTH - BLOCK_SIZE, BLOCK_SIZE)
y = random.randrange(0, HEIGHT - BLOCK_SIZE, BLOCK_SIZE)
food_pos = (x, y)
if food_pos not in self.snake: # Еда не должна появляться на змее
return food_pos
def move_snake(self):
"""Движение змеи в текущем направлении"""
head_x, head_y = self.snake[0]
if self.direction == 'RIGHT':
new_head = (head_x + BLOCK_SIZE, head_y)
elif self.direction == 'LEFT':
new_head = (head_x - BLOCK_SIZE, head_y)
elif self.direction == 'UP':
new_head = (head_x, head_y - BLOCK_SIZE)
else: # DOWN
new_head = (head_x, head_y + BLOCK_SIZE)
# Проверка на столкновение с границами
if (new_head[0] < 0 or new_head[0] >= WIDTH or
new_head[1] < 0 or new_head[1] >= HEIGHT):
return False # Конец игры
# Проверка на столкновение с собой
if new_head in self.snake:
return False # Конец игры
self.snake.insert(0, new_head)
# Если змея съела еду
if new_head == self.food:
self.score += 1
self.food = self.generate_food()
else:
self.snake.pop() # Удаляем хвост, если еды не было
return True # Игра продолжается
def draw(self):
"""Отрисовка всех элементов игры"""
screen.fill(BLACK)
# Отрисовка змеи
for segment in self.snake:
pygame.draw.rect(screen, GREEN, (segment[0], segment[1], BLOCK_SIZE, BLOCK_SIZE))
# Отрисовка еды
pygame.draw.rect(screen, RED, (self.food[0], self.food[1], BLOCK_SIZE, BLOCK_SIZE))
# Отрисовка счёта
score_text = self.font.render(f"Счёт: {self.score}", True, WHITE)
screen.blit(score_text, (10, 10))
def handle_events(self):
"""Обработка событий клавиатуры"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and self.direction != 'DOWN':
self.direction = 'UP'
elif event.key == pygame.K_DOWN and self.direction != 'UP':
self.direction = 'DOWN'
elif event.key == pygame.K_LEFT and self.direction != 'RIGHT':
self.direction = 'LEFT'
elif event.key == pygame.K_RIGHT and self.direction != 'LEFT':
self.direction = 'RIGHT'
def game_over_screen():
"""Экран окончания игры"""
font = pygame.font.Font(None, 72)
game_over_text = font.render("Игра окончена!", True, RED)
screen.blit(game_over_text, (WIDTH // 2 - 180, HEIGHT // 2 - 36))
pygame.display.flip()
pygame.time.wait(2000) # Ждём 2 секунды перед выходом
# Основной игровой цикл
def main():
game = SnakeGame()
while True:
game.handle_events()
if not game.move_snake():
game_over_screen()
break
game.draw()
pygame.display.flip()
clock.tick(SPEED)
if __name__ == "__main__":
main()