import pygame
import random
import os
pygame.init()
# окно
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
clock = pygame.time.Clock()
# цвета
WHITE = (255, 255, 255)
GREEN = (0, 200, 0)
RED = (200, 0, 0)
BLACK = (0, 0, 0)
BLOCK = 20
SPEED = 10
font = pygame.font.SysFont("Arial", 24)
# рекорд
HIGHSCORE_FILE = "highscore.txt"
def load_score():
if os.path.exists(HIGHSCORE_FILE):
return int(open(HIGHSCORE_FILE).read())
return 0
def save_score(score):
with open(HIGHSCORE_FILE, "w") as f:
f.write(str(score))
def draw_snake(snake):
for i, s in enumerate(snake):
color = (0, 255, 0) if i == 0 else GREEN
pygame.draw.rect(screen, color, (s[0], s[1], BLOCK, BLOCK))
def message(text, x, y):
screen.blit(font.render(text, True, WHITE), (x, y))
def game():
snake = [[100, 100]]
direction = "RIGHT"
food = [random.randrange(0, WIDTH, BLOCK), random.randrange(0, HEIGHT, BLOCK)]
score = 0
highscore = load_score()
running = True
while running:
screen.fill(BLACK)
# события
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != "DOWN":
direction = "UP"
if event.key == pygame.K_DOWN and direction != "UP":
direction = "DOWN"
if event.key == pygame.K_LEFT and direction != "RIGHT":
direction = "LEFT"
if event.key == pygame.K_RIGHT and direction != "LEFT":
direction = "RIGHT"
# движение
head = snake[0].copy()
if direction == "UP":
head[1] -= BLOCK
if direction == "DOWN":
head[1] += BLOCK
if direction == "LEFT":
head[0] -= BLOCK
if direction == "RIGHT":
head[0] += BLOCK
snake.insert(0, head)
# еда
if head == food:
score += 1
food = [random.randrange(0, WIDTH, BLOCK), random.randrange(0, HEIGHT, BLOCK)]
else:
snake.pop()
# стены
if head[0] < 0 or head[0] >= WIDTH or head[1] < 0 or head[1] >= HEIGHT:
running = False
# сам себя
if head in snake[1:]:
running = False
# рисуем
draw_snake(snake)
pygame.draw.rect(screen, RED, (food[0], food[1], BLOCK, BLOCK))
message(f"Score: {score}", 10, 10)
message(f"Best: {max(score, highscore)}", 10, 35)
pygame.display.update()
clock.tick(SPEED)
# конец игры
if score > highscore:
save_score(score)
game()
pygame.quit()