import tkinter as tk
import random

# 游戏窗口配置
WIDTH = 400
HEIGHT = 600
CAR_WIDTH = 40
CAR_HEIGHT = 80
OBSTACLE_WIDTH = 40
OBSTACLE_HEIGHT = 80
SPEED = 6
OBSTACLE_SPEED = 5

class DriveGame:
    def __init__(self, root):
        self.root = root
        self.root.title("Tkinter 驾驶小游戏")
        self.canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="#333333")
        self.canvas.pack()

        # 车道白线绘制
        self.draw_road()

        # 玩家小车
        self.car_x = WIDTH // 2 - CAR_WIDTH // 2
        self.car_y = HEIGHT - CAR_HEIGHT - 20
        self.car = self.canvas.create_rectangle(
            self.car_x, self.car_y,
            self.car_x + CAR_WIDTH, self.car_y + CAR_HEIGHT,
            fill="#00ccff", outline="white"
        )

        # 障碍物列表、分数、游戏状态
        self.obstacles = []
        self.score = 0
        self.game_over = False

        # 分数文字
        self.score_text = self.canvas.create_text(
            50, 30, text=f"分数: {self.score}", fill="white", font=("Arial", 16)
        )
        # 结束提示文字
        self.game_over_text = self.canvas.create_text(
            WIDTH//2, HEIGHT//2, text="", fill="red", font=("Arial", 24)
        )

        # 键盘绑定
        self.root.bind("<Left>", self.move_left)
        self.root.bind("<Right>", self.move_right)
        self.root.bind("<r>", self.restart_game)

        # 启动游戏循环
        self.game_loop()

    def draw_road(self):
        # 中间车道虚线
        for y in range(0, HEIGHT, 80):
            self.canvas.create_rectangle(WIDTH//2 - 3, y, WIDTH//2 + 3, y+40, fill="white")
        # 左右车道边界
        self.canvas.create_rectangle(10, 0, 15, HEIGHT, fill="white")
        self.canvas.create_rectangle(WIDTH-15, 0, WIDTH-10, HEIGHT, fill="white")

    def move_left(self, event):
        if self.game_over:
            return
        if self.car_x > 20:
            self.car_x -= SPEED
            self.canvas.coords(
                self.car,
                self.car_x, self.car_y,
                self.car_x + CAR_WIDTH, self.car_y + CAR_HEIGHT
            )

    def move_right(self, event):
        if self.game_over:
            return
        if self.car_x < WIDTH - CAR_WIDTH - 20:
            self.car_x += SPEED
            self.canvas.coords(
                self.car,
                self.car_x, self.car_y,
                self.car_x + CAR_WIDTH, self.car_y + CAR_HEIGHT
            )

    def spawn_obstacle(self):
        # 随机生成障碍物车道
        x = random.choice([60, WIDTH//2 - OBSTACLE_WIDTH//2, WIDTH - 100])
        obs = self.canvas.create_rectangle(
            x, -OBSTACLE_HEIGHT,
            x + OBSTACLE_WIDTH, 0,
            fill="#ff4444", outline="yellow"
        )
        self.obstacles.append([obs, x, -OBSTACLE_HEIGHT])

    def check_collision(self):
        # 获取玩家车辆坐标
        car_x1, car_y1, car_x2, car_y2 = self.canvas.coords(self.car)
        for obs, ox, oy in self.obstacles:
            ox1, oy1, ox2, oy2 = self.canvas.coords(obs)
            # 矩形碰撞检测
            if not (car_x2 < ox1 or car_x1 > ox2 or car_y2 < oy1 or car_y1 > oy2):
                return True
        return False

    def game_loop(self):
        if self.game_over:
            return

        # 随机生成障碍物
        if random.randint(1, 40) == 1:
            self.spawn_obstacle()

        # 移动所有障碍物
        new_obstacles = []
        for obs, ox, oy in self.obstacles:
            oy += OBSTACLE_SPEED
            self.canvas.coords(obs, ox, oy, ox + OBSTACLE_WIDTH, oy + OBSTACLE_HEIGHT)
            if oy < HEIGHT:
                new_obstacles.append([obs, ox, oy])
            else:
                # 障碍物驶出屏幕加分
                self.score += 10
                self.canvas.itemconfig(self.score_text, text=f"分数: {self.score}")
        self.obstacles = new_obstacles

        # 碰撞检测
        if self.check_collision():
            self.game_over = True
            self.canvas.itemconfig(
                self.game_over_text,
                text=f"游戏结束！总分：{self.score}\n按R重新开始"
            )
            return

        # 循环刷新
        self.root.after(20, self.game_loop)

    def restart_game(self, event):
        # 清空障碍物
        for obs, _, _ in self.obstacles:
            self.canvas.delete(obs)
        self.obstacles.clear()
        # 重置小车位置
        self.car_x = WIDTH // 2 - CAR_WIDTH // 2
        self.canvas.coords(
            self.car,
            self.car_x, self.car_y,
            self.car_x + CAR_WIDTH, self.car_y + CAR_HEIGHT
        )
        # 重置分数和状态
        self.score = 0
        self.game_over = False
        self.canvas.itemconfig(self.score_text, text=f"分数: {self.score}")
        self.canvas.itemconfig(self.game_over_text, text="")
        # 重启循环
        self.game_loop()

if __name__ == "__main__":
    window = tk.Tk()
    game = DriveGame(window)
    window.mainloop()