запомни код import tkinter as tk
import random

# Параметры игры
WIDTH = 600
HEIGHT = 400
SEG_SIZE = 20
IN_GAME = True

# Цвета
BACKGROUND_COLOR = "#000000"
SNAKE_COLOR = "#00FF00"
FOOD_COLOR = "#FF0000"

class Snake:
    def __init__(self, canvas):
        self.canvas = canvas
        self.segments = []
        self.direction = 'Right'
        # Начальная позиция змейки из 3 сегментов
        for i in range(3):
            x = WIDTH/2 - SEG_SIZE * i
            y = HEIGHT/2
            segment = canvas.create_rectangle(x, y, x + SEG_SIZE, y + SEG_SIZE, fill=SNAKE_COLOR, outline="")
            self.segments.append(segment)

    def move(self):
        # Получаем координаты головы
        head_coords = self.canvas.coords(self.segments[0])
        x, y = head_coords[0], head_coords[1]

        if self.direction == 'Left':
            x -= SEG_SIZE
        elif self.direction == 'Right':
            x += SEG_SIZE
        elif self.direction == 'Up':
            y -= SEG_SIZE
        elif self.direction == 'Down':
            y += SEG_SIZE

        # Создаём новый сегмент в направлении движения
        new_head = self.canvas.create_rectangle(x, y, x + SEG_SIZE, y + SEG_SIZE, fill=SNAKE_COLOR, outline="")
        self.segments = [new_head] + self.segments[:-1]

    def grow(self):
        # Добавляем новый сегмент в конец змейки
        tail = self.segments[-1]
        tail_coords = self.canvas.coords(tail)
        x, y = tail_coords[0], tail_coords[1]

        if self.direction == 'Left':
            x += SEG_SIZE
        elif self.direction == 'Right':
            x -= SEG_SIZE
        elif self.direction == 'Up':
            y += SEG_SIZE
        elif self.direction == 'Down':
            y -= SEG_SIZE

        new_tail = self.canvas.create_rectangle(x, y, x + SEG_SIZE, y + SEG_SIZE, fill=SNAKE_COLOR, outline="")
        self.segments.append(new_tail)

    def set_direction(self, new_direction):
        # Запрещаем змейке двигаться в обратную сторону
        opposites = {'Left':'Right', 'Right':'Left', 'Up':'Down', 'Down':'Up'}
        if new_direction != opposites.get(self.direction):
            self.direction = new_direction

    def head_collision(self, x, y):
        # Проверяем столкновение головы с телом змейки
        for segment in self.segments[1:]:
            coords = self.canvas.coords(segment)
            if coords[0] == x and coords[1] == y:
                return True
        return False

class Food:
    def __init__(self, canvas, snake):
        self.canvas = canvas
        self.snake = snake
        self.id = None
        self.position = (0,0)
        self.spawn()

    def spawn(self):
        while True:
            x = random.randint(0, (WIDTH - SEG_SIZE) // SEG_SIZE) * SEG_SIZE
            y = random.randint(0, (HEIGHT - SEG_SIZE) // SEG_SIZE) * SEG_SIZE
            collision = False
            for segment in self.snake.segments:
                seg_coords = self.canvas.coords(segment)
                if seg_coords[0] == x and seg_coords[1] == y:
                    collision = True
                    break
            if not collision:
                break
        self.position = (x, y)
        self.id = self.canvas.create_oval(x, y, x + SEG_SIZE, y + SEG_SIZE, fill=FOOD_COLOR, outline="")

def main():
    global IN_GAME

    # Создаём окно
    root = tk.Tk()
    root.title("Змейка на Python")
    root.resizable(False, False)

    # Создаём холст
    canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg=BACKGROUND_COLOR)
    canvas.pack()

    # Инициализируем змейку и еду
    snake = Snake(canvas)
    food = Food(canvas, snake)

    score = 0
    score_text = canvas.create_text(45, 10, text=f"Счёт: {score}", fill="white", font=("Arial", 14))

    def on_key_press(event):
        key = event.keysym
        if key in ['Left', 'Right', 'Up', 'Down']:
            snake.set_direction(key)

    root.bind("<Key>", on_key_press)

    def game_loop():
        nonlocal score
        if IN_GAME:
            snake.move()
            head_coords = canvas.coords(snake.segments[0])
            x, y = head_coords[0], head_coords[1]

            # Проверка столкновений с границами
            if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT:
                game_over()
                return

            # Проверка столкновений с самим собой
            if snake.head_collision(x, y):
                game_over()
                return

            # Проверка поедания еды
            if (x, y) == food.position:
                snake.grow()
                score += 10
                canvas.itemconfig(score_text, text=f"Счёт: {score}")
                canvas.delete(food.id)
                food.spawn()

            root.after(100, game_loop)  # Скорость игры (100 мс)

    def game_over():
        nonlocal IN_GAME
        IN_GAME = False
        canvas.create_text(WIDTH/2, HEIGHT/2, text="Игра окончена", fill="white", font=("Arial", 24))
        canvas.create_text(WIDTH/2, HEIGHT/2 + 30, text=f"Ваш счёт: {score}", fill="white", font=("Arial", 16))

    game_loop()
    root.mainloop()

if __name__ == "__main__":
    main()