import tkinter as tk
from tkinter import ttk, messagebox
import random
import math

# 科技风2D样式配置
TECH_STYLE = {
    "bg_main": "#0a0e17",       # 主背景（深黑蓝）
    "bg_panel": "#141b2d",      # 面板背景
    "bg_canvas": "#050710",     # 画布背景
    "text_primary": "#00e5ff",  # 科技蓝（主文字）
    "text_secondary": "#ffffff",# 白色（次文字）
    "accent": "#ff3a3a",        # 红色（强调色）
    "border": "#222d42",        # 边框色
    "grid": "#1a2338"           # 网格色
}

# 2D车模型配置（专属模型+技能）
CAR_MODELS = {
    "基础款 🚗": {
        "price": 0,
        "skill": "无技能 | 基础赛车模型",
        "speed": 6,
        "obstacle_rate": 0.06,
        "score_mult": 1,
        "color": "#ffffff",
        # 2D车模型坐标（相对中心点的偏移，构成赛车轮廓）
        "model": [
            (-20, 15), (20, 15),  # 车尾
            (15, 5), (10, -5),     # 车身右侧
            (10, -10), (-10, -10), # 车头
            (-10, -5), (-15, 5)    # 车身左侧
        ],
        # 车轮坐标（相对中心点）
        "wheels": [(-15, 15), (15, 15)]
    },
    "闪电款 ⚡": {
        "price": 500,
        "skill": "速度+3 | 积分×1.5 | 闪电赛车模型",
        "speed": 9,
        "obstacle_rate": 0.06,
        "score_mult": 1.5,
        "color": "#ffd600",
        "model": [
            (-25, 10), (25, 10),   # 车尾（更窄）
            (20, 0), (15, -10),    # 车身右侧（流线型）
            (10, -15), (-10, -15), # 车头（尖锐）
            (-15, -10), (-20, 0)   # 车身左侧
        ],
        "wheels": [(-20, 10), (20, 10)]
    },
    "幻影款 👻": {
        "price": 800,
        "skill": "障碍物-50% | 体积缩小 | 幻影赛车模型",
        "speed": 6,
        "obstacle_rate": 0.03,
        "score_mult": 1,
        "color": "#80e0ff",
        # 更小的模型
        "model": [
            (-15, 10), (15, 10),
            (10, 0), (8, -8),
            (5, -10), (-5, -10),
            (-8, -8), (-10, 0)
        ],
        "wheels": [(-12, 10), (12, 10)]
    },
    "黄金款 🥇": {
        "price": 1200,
        "skill": "积分×2 | 宽体模型 | 碰撞判定缩小",
        "speed": 7,
        "obstacle_rate": 0.06,
        "score_mult": 2,
        "color": "#ffc107",
        "model": [
            (-20, 20), (20, 20),   # 宽车尾
            (18, 5), (12, -8),     # 宽车身
            (10, -12), (-10, -12), # 车头
            (-12, -8), (-18, 5)    # 宽车身左侧
        ],
        "wheels": [(-18, 20), (18, 20)]
    },
    "科技款 🤖": {
        "price": 1800,
        "skill": "全属性：速+4 | 障-50% | 分×2 | 科技赛车模型",
        "speed": 10,
        "obstacle_rate": 0.03,
        "score_mult": 2,
        "color": "#00ff9d",
        "model": [
            (-30, 12), (30, 12),   # 加长车尾
            (25, 0), (20, -12),    # 流线型车身
            (15, -18), (-15, -18), # 尖锐车头
            (-20, -12), (-25, 0)   # 流线型左侧
        ],
        "wheels": [(-25, 12), (25, 12)]
    }
}

class Tech2DRacingWithModel:
    def __init__(self, root):
        self.root = root
        self.root.title("2D科技版 - 赛车转盘抽奖（带车模型）")
        self.root.geometry("900x680")
        self.root.resizable(False, False)
        self.root.configure(bg=TECH_STYLE["bg_main"])
        
        # 核心数据
        self.total_score = 0          # 总积分
        self.lottery_times = 0       # 抽奖次数（300积分/次）
        self.game_running = False    # 游戏状态
        self.unlocked_models = ["基础款 🚗"]  # 已解锁车模型
        self.equipped_model = "基础款 🚗"     # 当前装备车模型
        
        # 游戏变量（2D坐标）
        self.car_center_x = 450      # 赛车中心X
        self.car_center_y = 360      # 赛车中心Y
        self.obstacles = []          # 障碍物列表
        self.game_score = 0          # 本局积分
        
        # 加载当前车模型属性
        self.load_car_model_attr()
        
        # 创建界面
        self.create_ui()

    def load_car_model_attr(self):
        """加载当前车模型的属性和模型数据"""
        model = CAR_MODELS[self.equipped_model]
        self.car_speed = model["speed"]
        self.obstacle_rate = model["obstacle_rate"]
        self.score_mult = model["score_mult"]
        self.car_color = model["color"]
        self.car_model = model["model"]
        self.car_wheels = model["wheels"]

    def create_ui(self):
        """创建2D科技风界面"""
        # ========== 顶部信息面板 ==========
        top_panel = tk.Frame(self.root, bg=TECH_STYLE["bg_panel"], height=80)
        top_panel.pack(fill=tk.X, padx=20, pady=10)
        top_panel.pack_propagate(False)
        
        # 标题
        title = tk.Label(
            top_panel, text="2D TECH RACING | 车模型系统",
            font=("Consolas", 18, "bold"), bg=TECH_STYLE["bg_panel"],
            fg=TECH_STYLE["text_primary"]
        )
        title.pack(side=tk.LEFT, padx=20, pady=10)
        
        # 数据显示区
        data_frame = tk.Frame(top_panel, bg=TECH_STYLE["bg_panel"])
        data_frame.pack(side=tk.RIGHT, padx=20, pady=10)
        
        # 积分
        self.score_label = tk.Label(
            data_frame, text=f"总积分: {self.total_score}",
            font=("Consolas", 12), bg=TECH_STYLE["bg_panel"],
            fg=TECH_STYLE["text_secondary"]
        )
        self.score_label.grid(row=0, column=0, padx=15)
        
        # 抽奖次数
        self.lottery_label = tk.Label(
            data_frame, text=f"抽奖次数: {self.lottery_times}",
            font=("Consolas", 12), bg=TECH_STYLE["bg_panel"],
            fg=TECH_STYLE["accent"]
        )
        self.lottery_label.grid(row=0, column=1, padx=15)
        
        # 当前车模型
        self.model_label = tk.Label(
            data_frame, text=f"当前模型: {self.equipped_model}",
            font=("Consolas", 12), bg=TECH_STYLE["bg_panel"],
            fg=TECH_STYLE["text_primary"]
        )
        self.model_label.grid(row=0, column=2, padx=15)
        
        # ========== 功能按钮区 ==========
        btn_frame = tk.Frame(self.root, bg=TECH_STYLE["bg_main"])
        btn_frame.pack(pady=5)
        
        # 按钮样式（2D扁平化）
        btn_config = {
            "font": ("Consolas", 11, "bold"),
            "bg": TECH_STYLE["text_primary"],
            "fg": "black",
            "width": 16,
            "relief": tk.FLAT,
            "bd": 0,
            "activebackground": TECH_STYLE["accent"]
        }
        
        # 功能按钮
        tk.Button(btn_frame, text="启动2D赛车", command=self.start_racing, **btn_config).grid(row=0, column=0, padx=8)
        tk.Button(btn_frame, text="转盘抽奖", command=self.open_lottery, **btn_config).grid(row=0, column=1, padx=8)
        tk.Button(btn_frame, text="车模型商城", command=self.open_model_shop, **btn_config).grid(row=0, column=2, padx=8)
        tk.Button(btn_frame, text="重置数据", command=self.reset_data, **btn_config).grid(row=0, column=3, padx=8)
        
        # ========== 2D画布（游戏/抽奖区） ==========
        self.canvas = tk.Canvas(
            self.root, width=860, height=420,
            bg=TECH_STYLE["bg_canvas"], highlightthickness=1,
            highlightbackground=TECH_STYLE["border"]
        )
        self.canvas.pack(padx=20, pady=10)
        
        # 初始欢迎界面
        self.show_welcome()

    def show_welcome(self):
        """2D欢迎界面（显示车模型预览）"""
        self.canvas.delete("all")
        
        # 2D网格背景
        for x in range(0, 860, 40):
            self.canvas.create_line(x, 0, x, 420, fill=TECH_STYLE["grid"], width=1)
        for y in range(0, 420, 40):
            self.canvas.create_line(0, y, 860, y, fill=TECH_STYLE["grid"], width=1)
        
        # 标题
        self.canvas.create_text(
            430, 150, text="2D 科技赛车抽奖系统",
            font=("Consolas", 28, "bold"), fill=TECH_STYLE["text_primary"]
        )
        
        # 提示
        self.canvas.create_text(
            430, 220, text="→ 方向键控制 | 300积分抽奖 | 积分解锁专属车模型 ←",
            font=("Consolas", 12), fill=TECH_STYLE["text_secondary"]
        )
        
        # 预览当前车模型
        self.canvas.create_text(
            430, 270, text="当前车模型预览:",
            font=("Consolas", 11), fill=TECH_STYLE["accent"]
        )
        # 绘制预览模型
        self.draw_car_model(430, 320, self.equipped_model, scale=0.8)

    def draw_car_model(self, center_x, center_y, model_name, scale=1.0):
        """绘制2D车模型（核心函数）"""
        model_data = CAR_MODELS[model_name]
        # 计算模型绝对坐标
        model_coords = []
        for (dx, dy) in model_data["model"]:
            abs_x = center_x + dx * scale
            abs_y = center_y + dy * scale
            model_coords.append((abs_x, abs_y))
        
        # 绘制车身（2D模型）
        car_body = self.canvas.create_polygon(
            model_coords,
            fill=model_data["color"], outline=TECH_STYLE["text_primary"], width=1
        )
        
        # 绘制车轮
        wheels = []
        for (dx, dy) in model_data["wheels"]:
            abs_x = center_x + dx * scale
            abs_y = center_y + dy * scale
            # 2D圆形车轮
            wheel = self.canvas.create_oval(
                abs_x - 4, abs_y - 4,
                abs_x + 4, abs_y + 4,
                fill=TECH_STYLE["border"], outline=TECH_STYLE["text_secondary"], width=1
            )
            wheels.append(wheel)
        
        return car_body, wheels

    def update_display(self):
        """更新积分和抽奖次数显示"""
        self.lottery_times = self.total_score // 300
        self.score_label.config(text=f"总积分: {self.total_score}")
        self.lottery_label.config(text=f"抽奖次数: {self.lottery_times}")
        self.model_label.config(text=f"当前模型: {self.equipped_model}")

    # ========== 2D赛车游戏核心 ==========
    def start_racing(self):
        """启动2D赛车游戏（带专属模型）"""
        if self.game_running:
            return
        
        # 重新加载车模型属性
        self.load_car_model_attr()
        
        self.game_running = True
        self.game_score = 0
        self.canvas.delete("all")
        self.car_center_x = 450
        self.obstacles = []
        
        # 绘制2D赛道
        # 赛道边界
        self.canvas.create_rectangle(80, 50, 780, 400, 
                                    outline=TECH_STYLE["text_primary"], width=2)
        # 赛道网格
        for x in range(80, 780, 30):
            self.canvas.create_line(x, 50, x, 400, fill=TECH_STYLE["grid"], width=1)
        
        # 绘制当前2D车模型（游戏内）
        self.car_body, self.car_wheels = self.draw_car_model(
            self.car_center_x, self.car_center_y, self.equipped_model
        )
        
        # 绑定方向键
        self.root.bind("<Left>", self.move_left)
        self.root.bind("<Right>", self.move_right)
        
        # 启动游戏循环
        self.game_loop()

    def move_left(self, event):
        """2D赛车左移（边界限制）"""
        if self.car_center_x > 100:
            # 移动车身
            self.canvas.move(self.car_body, -self.car_speed, 0)
            # 移动车轮
            for wheel in self.car_wheels:
                self.canvas.move(wheel, -self.car_speed, 0)
            self.car_center_x -= self.car_speed

    def move_right(self, event):
        """2D赛车右移（边界限制）"""
        if self.car_center_x < 760:
            # 移动车身
            self.canvas.move(self.car_body, self.car_speed, 0)
            # 移动车轮
            for wheel in self.car_wheels:
                self.canvas.move(wheel, self.car_speed, 0)
            self.car_center_x += self.car_speed

    def generate_obstacle(self):
        """生成2D科技风障碍物"""
        if len(self.obstacles) < 6:
            x = random.randint(100, 740)
            # 2D多边形障碍物
            obstacle = self.canvas.create_polygon(
                x-15, 60, x+15, 60,
                x+10, 80, x-10, 80,
                fill=TECH_STYLE["accent"], outline=TECH_STYLE["text_primary"], width=1
            )
            self.obstacles.append(obstacle)

    def game_loop(self):
        """2D赛车游戏主循环"""
        if not self.game_running:
            return
        
        # 移动障碍物
        for obs in self.obstacles:
            self.canvas.move(obs, 0, 7)
            pos = self.canvas.coords(obs)
            
            # 障碍物出界 → 加分
            if pos[7] > 400:  # 多边形第8个坐标（底部）
                self.canvas.delete(obs)
                self.obstacles.remove(obs)
                add_score = int(10 * self.score_mult)
                self.total_score += add_score
                self.game_score += add_score
                
                # 2D加分提示
                self.canvas.create_text(
                    pos[0]+15, 400, text=f"+{add_score}",
                    font=("Consolas", 10), fill=TECH_STYLE["text_primary"],
                    tags="score_hint"
                )
                self.root.after(200, lambda: self.canvas.delete("score_hint"))
                
                # 更新显示
                self.update_display()
        
        # 2D碰撞检测（车模型边界框）
        car_bbox = self.canvas.bbox(self.car_body)  # 获取车模型边界框
        collision = False
        for obs in self.obstacles:
            obs_bbox = self.canvas.bbox(obs)
            # 边界框碰撞判定
            if (car_bbox[0] < obs_bbox[2] and car_bbox[2] > obs_bbox[0] and
                car_bbox[1] < obs_bbox[3] and car_bbox[3] > obs_bbox[1]):
                collision = True
                break
        
        if collision:
            # 游戏结束
            self.game_running = False
            self.root.unbind("<Left>")
            self.root.unbind("<Right>")
            
            messagebox.showinfo(
                "2D赛车游戏结束",
                f"🚨 碰撞！本局积分: {self.game_score}\n"
                f"🎨 车模型: {self.equipped_model} | 倍率: {self.score_mult}x"
            )
            self.show_welcome()
            return
        
        # 随机生成障碍物
        if random.random() < self.obstacle_rate:
            self.generate_obstacle()
        
        # 继续循环
        self.root.after(50, self.game_loop)

    # ========== 2D转盘抽奖 ==========
    def open_lottery(self):
        """打开2D科技风转盘抽奖"""
        if self.lottery_times <= 0:
            messagebox.warning("提示", "⚠️ 抽奖次数不足！每300积分可抽奖1次")
            return
        
        # 创建抽奖窗口
        lottery_win = tk.Toplevel(self.root)
        lottery_win.title("2D科技转盘抽奖")
        lottery_win.geometry("500x500")
        lottery_win.resizable(False, False)
        lottery_win.configure(bg=TECH_STYLE["bg_main"])
        lottery_win.grab_set()
        
        # 2D转盘画布
        lottery_canvas = tk.Canvas(
            lottery_win, width=450, height=450,
            bg=TECH_STYLE["bg_canvas"], highlightthickness=0
        )
        lottery_canvas.pack(pady=10)
        
        # 抽奖奖项
        prizes = {
            "100积分 🎫": 25,
            "200积分 🎟️": 20,
            "500积分 🏆": 10,
            "800积分 🚀": 5,
            "谢谢参与 ❌": 40
        }
        
        # 绘制2D转盘
        def draw_lottery_wheel(angle=0):
            lottery_canvas.delete("all")
            center_x, center_y = 225, 225
            radius = 200
            
            # 转盘背景环
            lottery_canvas.create_oval(
                center_x-radius-5, center_y-radius-5,
                center_x+radius+5, center_y+radius+5,
                fill=TECH_STYLE["bg_panel"], outline=TECH_STYLE["text_primary"], width=2
            )
            
            # 绘制奖项扇区
            total_weight = sum(prizes.values())
            start_angle = angle
            colors = ["#ff3a3a", "#ff9500", "#ffd600", "#34c759", "#00e5ff"]
            prize_list = list(prizes.items())
            
            for i, (prize, weight) in enumerate(prize_list):
                angle_range = 360 * weight / total_weight
                end_angle = start_angle + angle_range
                
                # 2D扇区
                lottery_canvas.create_arc(
                    center_x-radius, center_y-radius,
                    center_x+radius, center_y+radius,
                    start=start_angle, extent=angle_range,
                    fill=colors[i%len(colors)], outline=TECH_STYLE["bg_canvas"], width=1
                )
                
                # 奖项文字
                text_angle = start_angle + angle_range/2
                text_rad = math.radians(text_angle - 90)
                text_x = center_x + (radius*0.7)*math.cos(text_rad)
                text_y = center_y + (radius*0.7)*math.sin(text_rad)
                
                lottery_canvas.create_text(
                    text_x, text_y, text=prize,
                    font=("Consolas", 11, "bold"), fill="white"
                )
                start_angle = end_angle
            
            # 2D指针
            lottery_canvas.create_polygon(
                220, 30, 230, 30, 225, 70,
                fill=TECH_STYLE["accent"], outline="white", width=1
            )
        
        # 转盘旋转逻辑
        def spin_wheel():
            # 消耗抽奖次数
            self.lottery_times -= 1
            self.total_score -= 300
            self.update_display()
            
            # 禁用按钮
            spin_btn.config(state=tk.DISABLED, bg=TECH_STYLE["border"])
            
            # 旋转参数
            random_angle = random.randint(0, 360)
            target_angle = random.randint(2000, 3000) + random_angle
            speed = 20
            current_angle = 0
            
            def rotate():
                nonlocal current_angle, speed
                if current_angle < target_angle:
                    current_angle += speed
                    speed = max(1, speed - 0.15)
                    draw_lottery_wheel(current_angle)
                    lottery_win.after(15, rotate)
                else:
                    # 计算结果
                    final_angle = current_angle % 360
                    total_weight = sum(prizes.values())
                    current_weight = 0
                    result = ""
                    
                    for prize, weight in prizes.items():
                        current_weight += weight
                        angle_range = 360 * current_weight / total_weight
                        if final_angle <= angle_range:
                            result = prize
                            break
                    
                    # 发放奖励
                    if "100积分" in result:
                        self.total_score += 100
                    elif "200积分" in result:
                        self.total_score += 200
                    elif "500积分" in result:
                        self.total_score += 500
                    elif "800积分" in result:
                        self.total_score += 800
                    
                    self.update_display()
                    messagebox.showinfo(
                        "2D抽奖结果",
                        f"🎰 2D科技转盘结果\n——————\n{result}\n总积分: {self.total_score}"
                    )
                    lottery_win.destroy()
            
            rotate()
        
        # 初始化转盘
        draw_lottery_wheel()
        
        # 抽奖按钮
        spin_btn = tk.Button(
            lottery_win, text="启动2D转盘", command=spin_wheel,
            font=("Consolas", 12, "bold"), bg=TECH_STYLE["text_primary"],
            fg="black", width=18, relief=tk.FLAT
        )
        spin_btn.pack(pady=10)

    # ========== 车模型商城 ==========
    def open_model_shop(self):
        """打开2D车模型商城"""
        shop_win = tk.Toplevel(self.root)
        shop_win.title("2D车模型商城")
        shop_win.geometry("700x450")
        shop_win.resizable(False, False)
        shop_win.configure(bg=TECH_STYLE["bg_main"])
        shop_win.grab_set()
        
        # 商城标题
        shop_title = tk.Label(
            shop_win, text="2D 车模型商城 | 积分解锁专属模型",
            font=("Consolas", 16, "bold"), bg=TECH_STYLE["bg_main"],
            fg=TECH_STYLE["text_primary"]
        )
        shop_title.pack(pady=10)
        
        # 模型展示区
        model_frame = tk.Frame(shop_win, bg=TECH_STYLE["bg_panel"])
        model_frame.pack(padx=20, pady=10, fill=tk.BOTH, expand=True)
        
        # 遍历所有车模型
        row = 0
        for model_name, model_data in CAR_MODELS.items():
            # 模型项面板
            item_frame = tk.Frame(model_frame, bg=TECH_STYLE["bg_main"], relief=tk.FLAT, bd=1)
            item_frame.grid(row=row, column=0, padx=10, pady=8, sticky="ew")
            
            # 模型预览区（左侧）
            preview_canvas = tk.Canvas(
                item_frame, width=80, height=60,
                bg=TECH_STYLE["bg_canvas"], highlightthickness=0
            )
            preview_canvas.grid(row=0, column=0, padx=10, pady=5)
            # 绘制模型预览
            self.draw_car_model(40, 30, model_name, scale=0.6)
            
            # 模型信息（中间）
            info_text = (
                f"{model_name} | 价格: {model_data['price']}积分\n"
                f"技能: {model_data['skill']}"
            )
            fg_color = TECH_STYLE["text_primary"] if model_name in self.unlocked_models else TECH_STYLE["border"]
            info_label = tk.Label(
                item_frame, text=info_text, font=("Consolas", 10),
                bg=TECH_STYLE["bg_main"], fg=fg_color, justify=tk.LEFT
            )
            info_label.grid(row=0, column=1, padx=10, pady=5, sticky="w")
            
            # 操作按钮（右侧）
            if model_name == self.equipped_model:
                # 已装备
                btn = tk.Button(
                    item_frame, text="已装备", bg=TECH_STYLE["border"],
                    fg=TECH_STYLE["text_secondary"], state=tk.DISABLED, width=8
                )
            elif model_name in self.unlocked_models:
                # 可装备
                btn = tk.Button(
                    item_frame, text="装备", bg=TECH_STYLE["text_primary"],
                    fg="black", width=8,
                    command=lambda s=model_name: self.equip_model(s, shop_win)
                )
            else:
                # 可购买
                btn = tk.Button(
                    item_frame, text="购买", bg=TECH_STYLE["accent"],
                    fg="white", width=8,
                    command=lambda s=model_name: self.buy_model(s, shop_win)
                )
            btn.grid(row=0, column=2, padx=10, pady=5)
            row += 1

    def buy_model(self, model_name, shop_win):
        """购买2D车模型"""
        model_price = CAR_MODELS[model_name]["price"]
        if self.total_score < model_price:
            messagebox.warning("提示", f"❌ 积分不足！购买{model_name}需要{model_price}积分")
            return
        
        if messagebox.askyesno("确认", f"是否花费{model_price}积分购买{model_name}车模型？"):
            self.total_score -= model_price
            self.unlocked_models.append(model_name)
            self.update_display()
            messagebox.showinfo("成功", f"✅ 已解锁{model_name}专属2D车模型！")
            shop_win.destroy()
            self.open_model_shop()

    def equip_model(self, model_name, shop_win):
        """装备2D车模型"""
        self.equipped_model = model_name
        self.load_car_model_attr()
        self.update_display()
        messagebox.showinfo("成功", f"✅ 已装备{model_name}车模型！下次游戏生效")
        shop_win.destroy()
        self.show_welcome()

    # ========== 数据重置 ==========
    def reset_data(self):
        """重置所有数据"""
        if messagebox.askyesno("确认", "⚠️ 确定重置所有数据？（积分/车模型/抽奖次数）"):
            self.total_score = 0
            self.lottery_times = 0
            self.unlocked_models = ["基础款 🚗"]
            self.equipped_model = "基础款 🚗"
            self.load_car_model_attr()
            self.update_display()
            self.show_welcome()
            messagebox.showinfo("重置成功", "✅ 所有数据已重置为初始状态")

# 启动程序
if __name__ == "__main__":
    root = tk.Tk()
    app = Tech2DRacingWithModel(root)
    root.mainloop()