import tkinter as tk
import math
import random

WIDTH, HEIGHT = 600, 600
CAR_SIZE = 20
FPS = 30

class RacingGame:
    def __init__(self, root):
        self.root = root
        self.root.title("008. 2D 赛车")
        self.root.resizable(False, False)

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

        # 赛车状态
        self.x = WIDTH // 2
        self.y = HEIGHT // 2 + 100
        self.angle = -90  # 朝上
        self.speed = 0
        self.max_speed = 8
        self.acc = 0.3
        self.friction = 0.05
        self.steer = 4

        self.lap = 0
        self.last_cross = False

        self.car = None
        self.info = None

        self.build_track()
        self.draw_car()
        self.bind_keys()
        self.game_loop()

    # ===== 赛道（简易椭圆）=====
    def build_track(self):
        self.canvas.create_oval(
            80, 80, WIDTH - 80, HEIGHT - 80,
            outline="white", width=10
        )
        self.canvas.create_oval(
            140, 140, WIDTH - 140, HEIGHT - 140,
            outline="white", width=10
        )
        # 起跑线
        self.canvas.create_line(
            WIDTH // 2, HEIGHT // 2 + 80,
            WIDTH // 2, HEIGHT // 2 + 120,
            fill="yellow", width=4
        )

    # ===== 赛车绘制 =====
    def draw_car(self):
        if self.car:
            self.canvas.delete(self.car)

        rad = math.radians(self.angle)
        x1 = self.x + CAR_SIZE * math.cos(rad)
        y1 = self.y + CAR_SIZE * math.sin(rad)
        x2 = self.x + CAR_SIZE * math.cos(rad + math.pi * 0.8)
        y2 = self.y + CAR_SIZE * math.sin(rad + math.pi * 0.8)
        x3 = self.x + CAR_SIZE * math.cos(rad - math.pi * 0.8)
        y3 = self.y + CAR_SIZE * math.sin(rad - math.pi * 0.8)

        self.car = self.canvas.create_polygon(
            x1, y1, x2, y2, x3, y3,
            fill="red", outline="darkred", width=2
        )

        if self.info:
            self.canvas.delete(self.info)

        self.info = self.canvas.create_text(
            70, 30,
            text=f"速度: {abs(self.speed):.1f}\n圈数: {self.lap}",
            fill="white", font=("Arial", 12, "bold"),
            anchor="w"
        )

    # ===== 键盘控制 =====
    def bind_keys(self):
        self.root.bind("<Up>", lambda e: self.accelerate(1))
        self.root.bind("<Down>", lambda e: self.accelerate(-1))
        self.root.bind("<Left>", lambda e: self.turn(-1))
        self.root.bind("<Right>", lambda e: self.turn(1))

    def accelerate(self, d):
        self.speed += self.acc * d
        self.speed = max(-self.max_speed / 2, min(self.max_speed, self.speed))

    def turn(self, d):
        if abs(self.speed) > 0.5:
            self.angle += self.steer * d * (self.speed / self.max_speed)

    # ===== 碰撞检测（草地减速）=====
    def check_surface(self):
        # 简单判断：靠近中心或边缘 = 草地
        dx = self.x - WIDTH // 2
        dy = self.y - HEIGHT // 2
        dist = math.sqrt(dx * dx + dy * dy)

        # 赛道范围
        if 130 < dist < 220:
            return "track"
        return "grass"

    # ===== 圈数检测 =====
    def check_lap(self):
        # 起跑线附近
        if abs(self.x - WIDTH // 2) < 10 and 250 < self.y < 270:
            if not self.last_cross:
                self.lap += 1
                self.last_cross = True
        else:
            self.last_cross = False

    # ===== 游戏循环 =====
    def game_loop(self):
        surface = self.check_surface()

        # 草地阻力
        if surface == "grass":
            self.speed *= 0.96
        else:
            self.speed *= 0.99

        # 摩擦力
        if abs(self.speed) < self.friction:
            self.speed = 0

        rad = math.radians(self.angle)
        self.x += self.speed * math.cos(rad)
        self.y += self.speed * math.sin(rad)

        # 边界限制
        self.x = max(CAR_SIZE, min(WIDTH - CAR_SIZE, self.x))
        self.y = max(CAR_SIZE, min(HEIGHT - CAR_SIZE, self.y))

        self.check_lap()
        self.draw_car()

        self.root.after(1000 // FPS, self.game_loop)

# ===== 启动 =====
root = tk.Tk()
RacingGame(root)
root.mainloop()