import tkinter as tk
from tkinter import messagebox
import random

class Car:
    """车辆类"""
    def __init__(self, x, y, color, size=20):
        self.x = x
        self.y = y
        self.color = color
        self.size = size
        self.speed = 0
    
    def draw(self, canvas):
        """绘制车辆"""
        # 车身
        x1, y1 = self.x - self.size//2, self.y - self.size//2
        x2, y2 = self.x + self.size//2, self.y + self.size//2
        
        # 绘制主体
        canvas.create_rectangle(x1, y1, x2, y2, fill=self.color, outline='black', width=2)
        
        # 车窗
        window_size = self.size // 3
        canvas.create_rectangle(x1 + 2, y1 + 2, x2 - 2, y2 - window_size, 
                               fill='#87CEEB', outline='black', width=1)
        
        # 车轮
        wheel_color = '#333333'
        wheel_radius = self.size // 5
        canvas.create_oval(x1 + 3, y2 - 4, x1 + 3 + wheel_radius*2, y2 - 4 + wheel_radius*2, 
                          fill=wheel_color, outline='black')
        canvas.create_oval(x2 - 3 - wheel_radius*2, y2 - 4, x2 - 3, y2 - 4 + wheel_radius*2, 
                          fill=wheel_color, outline='black')
        canvas.create_oval(x1 + 3, y1 - 1, x1 + 3 + wheel_radius*2, y1 - 1 + wheel_radius*2, 
                          fill=wheel_color, outline='black')
        canvas.create_oval(x2 - 3 - wheel_radius*2, y1 - 1, x2 - 3, y1 - 1 + wheel_radius*2, 
                          fill=wheel_color, outline='black')

class DrivingGame:
    def __init__(self, root):
        self.root = root
        self.root.title("驾驶小游戏 - 高速驾驶挑战")
        self.root.resizable(False, False)
        
        # 游戏设置
        self.width = 400
        self.height = 600
        self.lane_width = 60
        self.num_lanes = 3
        self.player_width = 30
        self.player_height = 30
        
        # 游戏变量
        self.player = None
        self.obstacles = []
        self.score = 0
        self.lives = 3
        self.game_running = True
        self.paused = False
        self.game_speed = 5
        self.difficulty = 1
        self.spawn_counter = 0
        self.spawn_delay = 40
        
        # 道路偏移（用于道路动画）
        self.road_offset = 0
        
        # 颜色
        self.colors = {
            'road': '#555555',
            'road_edge': '#333333',
            'lane_marking': '#FFD700',
            'grass': '#228B22',
            'player': '#FF4444',
            'obstacle': '#333333',
            'score_bg': '#2C3E50'
        }
        
        # 创建界面
        self.setup_ui()
        
        # 绑定键盘事件
        self.root.bind('<Left>', self.move_left)
        self.root.bind('<Right>', self.move_right)
        self.root.bind('<Up>', self.increase_speed)
        self.root.bind('<Down>', self.decrease_speed)
        self.root.bind('<space>', self.toggle_pause)
        self.root.bind('<r>', self.restart_game)
        
        # 开始游戏
        self.start_game()
    
    def setup_ui(self):
        """设置用户界面"""
        # 顶部信息栏
        info_frame = tk.Frame(self.root, bg=self.colors['score_bg'], height=80)
        info_frame.pack(fill=tk.X, pady=(0, 5))
        
        self.score_label = tk.Label(info_frame, text="分数: 0", font=('Arial', 16, 'bold'),
                                   bg=self.colors['score_bg'], fg='white')
        self.score_label.pack(side=tk.LEFT, padx=20, pady=10)
        
        self.lives_label = tk.Label(info_frame, text="❤️ x 3", font=('Arial', 16, 'bold'),
                                   bg=self.colors['score_bg'], fg='red')
        self.lives_label.pack(side=tk.LEFT, padx=20, pady=10)
        
        self.speed_label = tk.Label(info_frame, text="速度: 100", font=('Arial', 16, 'bold'),
                                   bg=self.colors['score_bg'], fg='#FFD700')
        self.speed_label.pack(side=tk.LEFT, padx=20, pady=10)
        
        self.difficulty_label = tk.Label(info_frame, text="难度: 1", font=('Arial', 16, 'bold'),
                                        bg=self.colors['score_bg'], fg='#00FF00')
        self.difficulty_label.pack(side=tk.LEFT, padx=20, pady=10)
        
        # 游戏画布
        self.canvas = tk.Canvas(self.root, width=self.width, height=self.height,
                               bg=self.colors['grass'])
        self.canvas.pack()
        
        # 控制说明
        control_frame = tk.Frame(self.root, bg='#2C3E50', height=40)
        control_frame.pack(fill=tk.X, pady=(5, 0))
        
        controls = [
            "← → 移动", "↑ ↓ 速度", "空格 暂停", "R 重开"
        ]
        
        for text in controls:
            label = tk.Label(control_frame, text=text, font=('Arial', 10),
                            bg='#2C3E50', fg='white')
            label.pack(side=tk.LEFT, padx=15, pady=10)
    
    def start_game(self):
        """开始游戏"""
        # 初始化玩家车辆（固定在底部中央）
        player_x = self.width // 2
        player_y = self.height - 60
        self.player = Car(player_x, player_y, self.colors['player'], 30)
        
        # 初始化障碍物列表
        self.obstacles = []
        
        # 游戏状态
        self.game_running = True
        self.paused = False
        self.score = 0
        self.lives = 3
        self.game_speed = 5
        self.difficulty = 1
        self.spawn_counter = 0
        
        # 更新显示
        self.update_score_display()
        
        # 清除画布上的游戏结束文本
        self.canvas.delete("all")
        
        # 开始游戏循环
        self.game_loop()
    
    def draw_road(self):
        """绘制道路"""
        # 道路主体
        road_width = self.num_lanes * self.lane_width
        road_x = (self.width - road_width) // 2
        
        self.canvas.create_rectangle(road_x, 0, road_x + road_width, self.height,
                                     fill=self.colors['road'], outline=self.colors['road_edge'], width=3)
        
        # 车道线
        for i in range(1, self.num_lanes):
            line_x = road_x + i * self.lane_width
            # 动态虚线效果
            dash_length = 20
            offset = self.road_offset % dash_length
            
            self.canvas.create_line(line_x, 0, line_x, self.height,
                                   fill=self.colors['lane_marking'], width=3,
                                   dash=(10, 15), dashoffset=-offset)
        
        # 道路边缘线
        self.canvas.create_line(road_x, 0, road_x, self.height,
                               fill=self.colors['road_edge'], width=4)
        self.canvas.create_line(road_x + road_width, 0, road_x + road_width, self.height,
                               fill=self.colors['road_edge'], width=4)
    
    def draw_obstacles(self):
        """绘制障碍物车辆"""
        for obstacle in self.obstacles:
            obstacle.draw(self.canvas)
    
    def update_score_display(self):
        """更新分数显示"""
        self.score_label.config(text=f"分数: {self.score}")
        self.lives_label.config(text=f"❤️ x {self.lives}")
        self.speed_label.config(text=f"速度: {int(100 + self.game_speed * 10)}")
        self.difficulty_label.config(text=f"难度: {self.difficulty}")
    
    def move_left(self, event):
        """向左移动"""
        if self.game_running and not self.paused:
            road_width = self.num_lanes * self.lane_width
            road_x = (self.width - road_width) // 2
            min_x = road_x + self.player.size // 2
            self.player.x = max(min_x, self.player.x - self.lane_width)
    
    def move_right(self, event):
        """向右移动"""
        if self.game_running and not self.paused:
            road_width = self.num_lanes * self.lane_width
            road_x = (self.width - road_width) // 2
            max_x = road_x + road_width - self.player.size // 2
            self.player.x = min(max_x, self.player.x + self.lane_width)
    
    def increase_speed(self, event):
        """增加速度"""
        if self.game_running and not self.paused:
            self.game_speed = min(15, self.game_speed + 1)
            self.update_score_display()
    
    def decrease_speed(self, event):
        """减少速度"""
        if self.game_running and not self.paused:
            self.game_speed = max(3, self.game_speed - 1)
            self.update_score_display()
    
    def toggle_pause(self, event):
        """暂停/继续游戏"""
        if self.game_running:
            self.paused = not self.paused
            if self.paused:
                self.canvas.create_text(self.width//2, self.height//2,
                                       text="暂停", font=('Arial', 40, 'bold'),
                                       fill='white', tag="pause_text")
            else:
                self.canvas.delete("pause_text")
    
    def restart_game(self, event):
        """重新开始游戏"""
        self.start_game()
    
    def spawn_obstacle(self):
        """生成障碍物"""
        road_width = self.num_lanes * self.lane_width
        road_x = (self.width - road_width) // 2
        
        # 随机选择车道
        lane = random.randint(0, self.num_lanes - 1)
        x = road_x + lane * self.lane_width + self.lane_width // 2
        
        # 随机颜色
        colors = ['#666666', '#888888', '#555555', '#777777']
        color = random.choice(colors)
        
        obstacle = Car(x, -20, color, 30)
        self.obstacles.append(obstacle)
    
    def check_collision(self):
        """检查碰撞"""
        player_bbox = [
            self.player.x - self.player.size//2,
            self.player.y - self.player.size//2,
            self.player.x + self.player.size//2,
            self.player.y + self.player.size//2
        ]
        
        for obstacle in self.obstacles[:]:
            obstacle_bbox = [
                obstacle.x - obstacle.size//2,
                obstacle.y - obstacle.size//2,
                obstacle.x + obstacle.size//2,
                obstacle.y + obstacle.size//2
            ]
            
            # 检查矩形碰撞
            if (player_bbox[0] < obstacle_bbox[2] and
                player_bbox[2] > obstacle_bbox[0] and
                player_bbox[1] < obstacle_bbox[3] and
                player_bbox[3] > obstacle_bbox[1]):
                return True
        return False
    
    def game_loop(self):
        """游戏主循环"""
        if not self.game_running:
            return
        
        if not self.paused:
            # 更新道路偏移（产生道路移动效果）
            self.road_offset = (self.road_offset + self.game_speed) % 40
            
            # 生成障碍物
            self.spawn_counter += 1
            if self.spawn_counter >= max(20, self.spawn_delay - self.difficulty * 2):
                self.spawn_obstacle()
                self.spawn_counter = 0
            
            # 移动障碍物
            for obstacle in self.obstacles[:]:
                obstacle.y += self.game_speed
                if obstacle.y - obstacle.size//2 > self.height:
                    self.obstacles.remove(obstacle)
                    # 成功躲避车辆，加分
                    self.score += 10
                    self.update_score_display()
                    
                    # 增加难度
                    if self.score > 0 and self.score % 500 == 0:
                        self.difficulty = min(10, self.difficulty + 1)
                        self.spawn_delay = max(20, 40 - self.difficulty * 2)
                        self.update_score_display()
            
            # 检查碰撞
            if self.check_collision():
                self.lives -= 1
                self.update_score_display()
                
                if self.lives <= 0:
                    self.game_over()
                    return
                else:
                    # 碰撞后短暂无敌和闪烁效果
                    self.handle_collision()
            
            # 根据分数自动增加难度
            if self.score > 0 and self.score % 1000 == 0 and self.score < 10000:
                self.difficulty = min(10, self.difficulty + 0.5)
                self.update_score_display()
        
        # 重新绘制
        self.canvas.delete("all")
        self.draw_road()
        self.draw_obstacles()
        self.player.draw(self.canvas)
        
        # 显示提示信息
        if self.paused:
            self.canvas.create_text(self.width//2, self.height//2,
                                   text="暂停", font=('Arial', 40, 'bold'),
                                   fill='white')
        
        # 继续循环
        self.root.after(30, self.game_loop)
    
    def handle_collision(self):
        """处理碰撞"""
        # 重置玩家位置
        self.player.x = self.width // 2
        
        # 清除所有障碍物
        self.obstacles.clear()
        
        # 显示碰撞效果
        flash = self.canvas.create_rectangle(0, 0, self.width, self.height,
                                            fill='red', stipple='gray50', tag="flash")
        self.root.after(200, lambda: self.canvas.delete("flash"))
        
        # 减速
        self.game_speed = max(3, self.game_speed - 2)
        self.update_score_display()
    
    def game_over(self):
        """游戏结束"""
        self.game_running = False
        
        # 显示游戏结束信息
        self.canvas.create_rectangle(0, 0, self.width, self.height,
                                    fill='black', stipple='gray50')
        self.canvas.create_text(self.width//2, self.height//2 - 50,
                               text="游戏结束", font=('Arial', 48, 'bold'),
                               fill='red')
        self.canvas.create_text(self.width//2, self.height//2,
                               text=f"最终得分: {self.score}", font=('Arial', 24, 'bold'),
                               fill='white')
        self.canvas.create_text(self.width//2, self.height//2 + 50,
                               text="按 R 键重新开始", font=('Arial', 18),
                               fill='yellow')

class RacingGame(DrivingGame):
    """增强版赛车游戏，添加更多功能"""
    
    def __init__(self, root):
        # 先初始化父类
        super().__init__(root)
        # 再初始化增强版的专属属性
        self.powerups = []
        self.shield_active = False
        self.root.title("驾驶小游戏 - 高级挑战模式")
    
    def start_game(self):
        """重写开始游戏方法"""
        # 先重置增强版的属性
        self.powerups = []
        self.shield_active = False
        # 再调用父类的start_game
        super().start_game()
    
    def spawn_powerup(self):
        """生成道具"""
        if random.randint(1, 100) < 5:  # 5%几率生成道具
            road_width = self.num_lanes * self.lane_width
            road_x = (self.width - road_width) // 2
            lane = random.randint(0, self.num_lanes - 1)
            x = road_x + lane * self.lane_width + self.lane_width // 2
            
            powerup = {
                'x': x,
                'y': -20,
                'type': random.choice(['nitro', 'shield', 'health'])
            }
            self.powerups.append(powerup)
    
    def draw_powerups(self):
        """绘制道具"""
        for powerup in self.powerups:
            x, y = powerup['x'], powerup['y']
            powerup_colors = {
                'nitro': '#FFA500',
                'shield': '#4169E1',
                'health': '#FF69B4'
            }
            color = powerup_colors.get(powerup['type'], '#FFFFFF')
            
            # 绘制道具图标
            self.canvas.create_oval(x-15, y-15, x+15, y+15, fill=color, outline='gold', width=2)
            # 添加图标文字
            icon_text = {
                'nitro': '⚡',
                'shield': '🛡️',
                'health': '❤️'
            }
            text = icon_text.get(powerup['type'], '?')
            self.canvas.create_text(x, y, text=text, 
                                   font=('Arial', 16, 'bold'), fill='white')
    
    def check_powerup_collision(self):
        """检查道具收集"""
        for powerup in self.powerups[:]:
            # 检查碰撞
            if (abs(powerup['x'] - self.player.x) < 25 and 
                abs(powerup['y'] - self.player.y) < 25):
                
                # 根据道具类型应用效果
                if powerup['type'] == 'nitro':
                    # 氮气加速
                    self.game_speed = min(20, self.game_speed + 5)
                    self.show_message("⚡ 氮气加速! ⚡", 'orange', 1000)
                
                elif powerup['type'] == 'shield':
                    # 护盾
                    self.shield_active = True
                    self.show_message("🛡️ 护盾激活! (5秒) 🛡️", 'blue', 2000)
                    # 5秒后失效
                    self.root.after(5000, lambda: setattr(self, 'shield_active', False))
                
                elif powerup['type'] == 'health':
                    # 增加生命
                    self.lives = min(5, self.lives + 1)
                    self.update_score_display()
                    self.show_message("❤️ 生命+1 ❤️", 'pink', 1000)
                
                # 移除道具
                self.powerups.remove(powerup)
                break
    
    def show_message(self, text, color, duration):
        """显示临时消息"""
        msg_id = self.canvas.create_text(self.width//2, self.height//3,
                                        text=text, font=('Arial', 20, 'bold'),
                                        fill=color, tag="powerup_msg")
        self.root.after(duration, lambda: self.canvas.delete("powerup_msg"))
    
    def check_collision(self):
        """重写碰撞检测，加入护盾保护"""
        if self.shield_active:
            # 有护盾时无敌，但消耗护盾并显示效果
            collision = super().check_collision()
            if collision:
                self.shield_active = False
                self.show_message("💔 护盾破碎! 💔", 'red', 500)
                return False
            return False
        return super().check_collision()
    
    def game_loop(self):
        """重写游戏主循环，添加道具系统"""
        if not self.game_running:
            return
        
        if not self.paused:
            # 更新道路偏移
            self.road_offset = (self.road_offset + self.game_speed) % 40
            
            # 生成障碍物和道具
            self.spawn_counter += 1
            if self.spawn_counter >= max(20, self.spawn_delay - self.difficulty * 2):
                self.spawn_obstacle()
                self.spawn_powerup()  # 生成道具
                self.spawn_counter = 0
            
            # 移动障碍物
            for obstacle in self.obstacles[:]:
                obstacle.y += self.game_speed
                if obstacle.y - obstacle.size//2 > self.height:
                    self.obstacles.remove(obstacle)
                    self.score += 10
                    self.update_score_display()
                    
                    # 增加难度
                    if self.score > 0 and self.score % 500 == 0:
                        self.difficulty = min(10, self.difficulty + 1)
                        self.spawn_delay = max(20, 40 - self.difficulty * 2)
                        self.update_score_display()
            
            # 移动道具
            for powerup in self.powerups[:]:
                powerup['y'] += self.game_speed
                if powerup['y'] > self.height:
                    self.powerups.remove(powerup)
            
            # 检查道具碰撞
            self.check_powerup_collision()
            
            # 检查车辆碰撞
            if self.check_collision():
                self.lives -= 1
                self.update_score_display()
                
                if self.lives <= 0:
                    self.game_over()
                    return
                else:
                    self.handle_collision()
        
        # 重新绘制
        self.canvas.delete("all")
        self.draw_road()
        self.draw_powerups()  # 绘制道具
        self.draw_obstacles()
        self.player.draw(self.canvas)
        
        # 显示护盾效果
        if self.shield_active:
            self.canvas.create_oval(self.player.x-25, self.player.y-25,
                                   self.player.x+25, self.player.y+25,
                                   outline='#4169E1', width=4, dash=(5, 5, 2, 5))
        
        # 显示暂停信息
        if self.paused:
            self.canvas.create_text(self.width//2, self.height//2,
                                   text="暂停", font=('Arial', 40, 'bold'),
                                   fill='white')
        
        # 继续循环
        self.root.after(30, self.game_loop)
    
    def handle_collision(self):
        """重写碰撞处理"""
        if not self.shield_active:
            # 清除所有道具（碰撞后重置）
            self.powerups.clear()
            super().handle_collision()

def main():
    """主函数"""
    root = tk.Tk()
    
    # 选择游戏模式
    choice = messagebox.askyesno("选择模式", 
                                "🚗 选择游戏模式 🚗\n\n"
                                "【是】- 高级模式\n"
                                "• 道具系统（氮气加速、护盾、生命恢复）\n"
                                "• 视觉特效和护盾效果\n"
                                "• 更多游戏元素\n\n"
                                "【否】- 普通模式\n"
                                "• 基础驾驶挑战\n"
                                "• 适合新手体验")
    
    if choice:
        game = RacingGame(root)
    else:
        game = DrivingGame(root)
    
    root.mainloop()

if __name__ == "__main__":
    main()