import tkinter as tk
import random

# 游戏设置
WIDTH = 400
HEIGHT = 400
SIZE = 20
SPEED = 150

class SnakeGame:
    def __init__(self, root):
        self.root = root
        self.root.title("贪吃蛇")

        self.canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="#111111")
        self.canvas.pack()

        self.score = 0
        self.direction = "Right"
        self.snake = [(100, 100), (80, 100), (60, 100)]
        self.food = None
        self.game_running = True

        self.root.bind("<KeyPress>", self.change_dir)
        self.create_food()
        self.game_loop()

    def create_food(self):
        while True:
            x = random.randint(0, (WIDTH - SIZE) // SIZE) * SIZE
            y = random.randint(0, (HEIGHT - SIZE) // SIZE) * SIZE
            if (x, y) not in self.snake:
                self.food = (x, y)
                break

    def change_dir(self, event):
        key = event.keysym
        if key == "Up" and self.direction != "Down":
            self.direction = "Up"
        elif key == "Down" and self.direction != "Up":
            self.direction = "Down"
        elif key == "Left" and self.direction != "Right":
            self.direction = "Left"
        elif key == "Right" and self.direction != "Left":
            self.direction = "Right"

    def game_loop(self):
        if not self.game_running:
            return

        head_x, head_y = self.snake[0]
        if self.direction == "Up":
            head_y -= SIZE
        elif self.direction == "Down":
            head_y += SIZE
        elif self.direction == "Left":
            head_x -= SIZE
        elif self.direction == "Right":
            head_x += SIZE

        # 撞墙判断
        if head_x < 0 or head_x >= WIDTH or head_y < 0 or head_y >= HEIGHT:
            self.game_over()
            return
        # 撞到自己
        if (head_x, head_y) in self.snake:
            self.game_over()
            return

        self.snake.insert(0, (head_x, head_y))

        # 吃到食物
        if (head_x, head_y) == self.food:
            self.score += 10
            self.create_food()
        else:
            self.snake.pop()

        self.draw()
        self.root.after(SPEED, self.game_loop)

    def draw(self):
        self.canvas.delete("all")
        # 画蛇
        for x, y in self.snake:
            self.canvas.create_rectangle(x, y, x + SIZE, y + SIZE, fill="#33cc33")
        # 画食物
        fx, fy = self.food
        self.canvas.create_oval(fx, fy, fx + SIZE, fy + SIZE, fill="#ff3333")
        # 分数
        self.canvas.create_text(30, 15, text=f"分数：{self.score}", fill="white", font=("Arial", 12))

    def game_over(self):
        self.game_running = False
        self.canvas.create_text(WIDTH//2, HEIGHT//2, text=f"游戏结束！得分：{self.score}", fill="white", font=("Arial", 16))

if __name__ == "__main__":
    win = tk.Tk()
    game = SnakeGame(win)
    win.mainloop()
