import pygame
import random
import sys
import math

# 初始化pygame
pygame.init()

# 设置窗口尺寸
WIDTH, HEIGHT = 900, 650
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("石头剪刀布游戏")

# 颜色定义
BACKGROUND = (25, 25, 40)
TEXT_COLOR = (240, 240, 255)
HIGHLIGHT = (100, 200, 255)
PLAYER_COLOR = (70, 180, 255)
COMPUTER_COLOR = (255, 100, 120)
WIN_COLOR = (100, 255, 150)
LOSE_COLOR = (255, 120, 100)
DRAW_COLOR = (255, 220, 100)
BUTTON_COLOR = (60, 60, 80)
BUTTON_HOVER = (80, 80, 100)

# 游戏状态
ROCK = 0
PAPER = 1
SCISSORS = 2
choices = ["石头", "剪刀", "布"]

# 游戏逻辑 - 判断胜负
def get_winner(player_choice, computer_choice):
    if player_choice == computer_choice:
        return 0  # 平局
    elif (player_choice == ROCK and computer_choice == SCISSORS) or \
         (player_choice == PAPER and computer_choice == ROCK) or \
         (player_choice == SCISSORS and computer_choice == PAPER):
        return 1  # 玩家赢
    else:
        return -1  # 电脑赢

# 加载字体
try:
    title_font = pygame.font.SysFont("microsoftyahei", 60, bold=True)
    choice_font = pygame.font.SysFont("microsoftyahei", 40, bold=True)
    score_font = pygame.font.SysFont("microsoftyahei", 36)
    result_font = pygame.font.SysFont("microsoftyahei", 48, bold=True)
    button_font = pygame.font.SysFont("microsoftyahei", 30)
    small_font = pygame.font.SysFont("microsoftyahei", 24)
except:
    # 如果找不到指定字体，使用默认字体
    title_font = pygame.font.Font(None, 60)
    choice_font = pygame.font.Font(None, 40)
    score_font = pygame.font.Font(None, 36)
    result_font = pygame.font.Font(None, 48)
    button_font = pygame.font.Font(None, 30)
    small_font = pygame.font.Font(None, 24)

# 绘制圆角矩形
def draw_rounded_rect(surface, color, rect, radius=10):
    x, y, width, height = rect
    pygame.draw.rect(surface, color, (x + radius, y, width - 2 * radius, height))
    pygame.draw.rect(surface, color, (x, y + radius, width, height - 2 * radius))
    pygame.draw.circle(surface, color, (x + radius, y + radius), radius)
    pygame.draw.circle(surface, color, (x + width - radius, y + radius), radius)
    pygame.draw.circle(surface, color, (x + radius, y + height - radius), radius)
    pygame.draw.circle(surface, color, (x + width - radius, y + height - radius), radius)

# 绘制按钮
def draw_button(surface, text, rect, hover=False, active=False):
    color = BUTTON_HOVER if hover else BUTTON_COLOR
    if active:
        color = HIGHLIGHT
    draw_rounded_rect(surface, color, rect, 15)
    
    text_surf = button_font.render(text, True, TEXT_COLOR)
    text_rect = text_surf.get_rect(center=(rect[0] + rect[2] // 2, rect[1] + rect[3] // 2))
    surface.blit(text_surf, text_rect)
    
    # 按钮边框
    border_color = HIGHLIGHT if hover or active else (40, 40, 60)
    pygame.draw.rect(surface, border_color, rect, 3, border_radius=15)

# 绘制选择图标
def draw_choice(surface, choice_type, x, y, size, is_player=True, is_winner=False, is_loser=False):
    color = PLAYER_COLOR if is_player else COMPUTER_COLOR
    
    if is_winner:
        color = WIN_COLOR
    elif is_loser:
        color = LOSE_COLOR
    
    # 绘制图标背景
    icon_rect = pygame.Rect(x - size//2, y - size//2, size, size)
    draw_rounded_rect(screen, (color[0]//4, color[1]//4, color[2]//4), icon_rect, 20)
    
    # 绘制图标
    if choice_type == ROCK:  # 石头
        # 绘制石头形状
        pygame.draw.circle(surface, color, (x, y), size//2 - 10)
        # 添加石头纹理
        for _ in range(5):
            tx = x + random.randint(-size//4, size//4)
            ty = y + random.randint(-size//4, size//4)
            pygame.draw.circle(surface, (color[0]-20, color[1]-20, color[2]-20), (tx, ty), 5)
    
    elif choice_type == PAPER:  # 布
        # 绘制纸张形状
        paper_rect = pygame.Rect(x - size//2 + 10, y - size//2 + 10, size - 20, size - 20)
        pygame.draw.rect(surface, color, paper_rect, border_radius=10)
        # 添加折痕效果
        pygame.draw.line(surface, (color[0]-30, color[1]-30, color[2]-30), 
                         (x - size//3, y - size//3), (x + size//3, y - size//3), 3)
        pygame.draw.line(surface, (color[0]-30, color[1]-30, color[2]-30), 
                         (x - size//3, y + size//3), (x + size//3, y + size//3), 3)
    
    elif choice_type == SCISSORS:  # 剪刀
        # 绘制剪刀形状
        # 左刀片
        left_points = [
            (x - size//4, y - size//3),
            (x, y),
            (x - size//4, y + size//3),
            (x - size//2, y)
        ]
        pygame.draw.polygon(surface, color, left_points)
        # 右刀片
        right_points = [
            (x + size//4, y - size//3),
            (x, y),
            (x + size//4, y + size//3),
            (x + size//2, y)
        ]
        pygame.draw.polygon(surface, color, right_points)
        # 连接点
        pygame.draw.circle(surface, (color[0]-30, color[1]-30, color[2]-30), (x, y), 10)
    
    # 如果是赢家，添加光环效果
    if is_winner:
        for i in range(3):
            radius = size//2 + 5 + i*5
            alpha = 100 - i*30
            s = pygame.Surface((radius*2, radius*2), pygame.SRCALPHA)
            pygame.draw.circle(s, (*color, alpha), (radius, radius), radius, 3)
            surface.blit(s, (x - radius, y - radius))

# 绘制动画特效
def draw_animation(surface, animation_step):
    if animation_step <= 0:
        return
    
    # 绘制冲击波效果
    center_x, center_y = WIDTH // 2, HEIGHT // 2 - 50
    max_radius = min(WIDTH, HEIGHT) // 3
    
    for i in range(3):
        progress = (animation_step + i * 5) % 60 / 60.0
        radius = int(progress * max_radius)
        alpha = int(150 * (1 - progress))
        
        if radius > 0:
            s = pygame.Surface((radius*2, radius*2), pygame.SRCALPHA)
            pygame.draw.circle(s, (*HIGHLIGHT, alpha), (radius, radius), radius, 3)
            surface.blit(s, (center_x - radius, center_y - radius))

# 主游戏类
class RockPaperScissorsGame:
    def __init__(self):
        self.player_score = 0
        self.computer_score = 0
        self.draws = 0
        self.total_games = 0
        
        self.player_choice = None
        self.computer_choice = None
        self.result = None  # 1: 玩家赢, -1: 电脑赢, 0: 平局
        self.result_text = ""
        
        self.animation_step = 0
        self.show_computer_choice = False
        self.game_state = "CHOOSING"  # CHOOSING, SHOWING, RESULT
        
        # 按钮定义
        button_width, button_height = 200, 80
        button_margin = 20
        start_y = HEIGHT - 150
        
        self.buttons = [
            {"rect": pygame.Rect(WIDTH//2 - button_width - button_margin, start_y, button_width, button_height), 
             "text": "石 头", "choice": ROCK, "hover": False},
            {"rect": pygame.Rect(WIDTH//2, start_y, button_width, button_height), 
             "text": "剪 刀", "choice": PAPER, "hover": False},
            {"rect": pygame.Rect(WIDTH//2 + button_width + button_margin, start_y, button_width, button_height), 
             "text": "布", "choice": SCISSORS, "hover": False}
        ]
        
        # 重置按钮
        self.reset_button = pygame.Rect(WIDTH - 150, 20, 120, 50)
        self.reset_hover = False  # 修复：初始化reset_hover属性
        
        # 历史记录
        self.history = []
        self.max_history = 10
    
    def player_choose(self, choice):
        if self.game_state != "CHOOSING":
            return
            
        self.player_choice = choice
        self.computer_choice = random.randint(0, 2)
        self.result = get_winner(self.player_choice, self.computer_choice)
        
        # 更新分数
        self.total_games += 1
        if self.result == 1:
            self.player_score += 1
            self.result_text = "你赢了！"
        elif self.result == -1:
            self.computer_score += 1
            self.result_text = "电脑赢了！"
        else:
            self.draws += 1
            self.result_text = "平局！"
        
        # 添加到历史记录
        self.history.insert(0, {
            "player": choices[self.player_choice],
            "computer": choices[self.computer_choice],
            "result": self.result_text
        })
        
        # 限制历史记录长度
        if len(self.history) > self.max_history:
            self.history = self.history[:self.max_history]
        
        # 切换到显示状态
        self.game_state = "SHOWING"
        self.animation_step = 0
        self.show_computer_choice = False
    
    def update(self):
        # 更新动画
        if self.game_state == "SHOWING":
            self.animation_step += 1
            
            # 在动画的中间部分显示电脑选择
            if self.animation_step > 30:
                self.show_computer_choice = True
            
            # 动画结束后显示结果
            if self.animation_step > 90:
                self.game_state = "RESULT"
    
    def draw(self, surface):
        # 绘制背景
        surface.fill(BACKGROUND)
        
        # 绘制标题
        title = title_font.render("石头剪刀布", True, HIGHLIGHT)
        surface.blit(title, (WIDTH//2 - title.get_width()//2, 20))
        
        # 绘制分数
        score_text = score_font.render(f"玩家: {self.player_score}  电脑: {self.computer_score}  平局: {self.draws}", 
                                      True, TEXT_COLOR)
        surface.blit(score_text, (WIDTH//2 - score_text.get_width()//2, 100))
        
        # 绘制总游戏数
        total_text = small_font.render(f"总游戏数: {self.total_games}", True, TEXT_COLOR)
        surface.blit(total_text, (WIDTH//2 - total_text.get_width()//2, 140))
        
        # 绘制玩家和电脑的选择区域
        player_x, computer_x = WIDTH//4, 3*WIDTH//4
        center_y = HEIGHT//2 - 50
        
        # 绘制玩家区域
        player_label = choice_font.render("玩家", True, PLAYER_COLOR)
        surface.blit(player_label, (player_x - player_label.get_width()//2, center_y - 150))
        
        # 绘制电脑区域
        computer_label = choice_font.render("电脑", True, COMPUTER_COLOR)
        surface.blit(computer_label, (computer_x - computer_label.get_width()//2, center_y - 150))
        
        # 绘制玩家选择
        if self.player_choice is not None:
            is_player_winner = self.result == 1
            is_player_loser = self.result == -1
            draw_choice(surface, self.player_choice, player_x, center_y, 120, 
                       is_player=True, is_winner=is_player_winner, is_loser=is_player_loser)
            
            player_choice_text = choice_font.render(choices[self.player_choice], True, PLAYER_COLOR)
            surface.blit(player_choice_text, (player_x - player_choice_text.get_width()//2, center_y + 100))
        
        # 绘制电脑选择
        if self.computer_choice is not None and self.show_computer_choice:
            is_computer_winner = self.result == -1
            is_computer_loser = self.result == 1
            draw_choice(surface, self.computer_choice, computer_x, center_y, 120, 
                       is_player=False, is_winner=is_computer_winner, is_loser=is_computer_loser)
            
            computer_choice_text = choice_font.render(choices[self.computer_choice], True, COMPUTER_COLOR)
            surface.blit(computer_choice_text, (computer_x - computer_choice_text.get_width()//2, center_y + 100))
        elif self.game_state == "SHOWING":
            # 显示电脑正在思考的动画
            thinking_text = choice_font.render("思考中...", True, COMPUTER_COLOR)
            surface.blit(thinking_text, (computer_x - thinking_text.get_width()//2, center_y))
            
            # 绘制思考动画
            dot_radius = 8
            dot_spacing = 20
            for i in range(3):
                progress = (self.animation_step + i * 10) % 30 / 30.0
                alpha = int(100 + 155 * abs(math.sin(progress * math.pi)))
                dot_y = center_y + 40 + int(10 * math.sin(progress * math.pi * 2))
                s = pygame.Surface((dot_radius*2, dot_radius*2), pygame.SRCALPHA)
                pygame.draw.circle(s, (COMPUTER_COLOR[0], COMPUTER_COLOR[1], COMPUTER_COLOR[2], alpha), 
                                 (dot_radius, dot_radius), dot_radius)
                surface.blit(s, (computer_x - dot_spacing + i * dot_spacing - dot_radius, dot_y - dot_radius))
        
        # 绘制动画特效
        if self.game_state == "SHOWING":
            draw_animation(surface, self.animation_step)
        
        # 绘制结果
        if self.game_state == "RESULT":
            result_color = WIN_COLOR if self.result == 1 else LOSE_COLOR if self.result == -1 else DRAW_COLOR
            result_display = result_font.render(self.result_text, True, result_color)
            surface.blit(result_display, (WIDTH//2 - result_display.get_width()//2, center_y + 150))
            
            # 绘制提示
            hint_text = small_font.render("点击任意按钮继续游戏", True, TEXT_COLOR)
            surface.blit(hint_text, (WIDTH//2 - hint_text.get_width()//2, center_y + 200))
        elif self.game_state == "CHOOSING":
            # 绘制提示
            hint_text = small_font.render("请选择你的出拳", True, TEXT_COLOR)
            surface.blit(hint_text, (WIDTH//2 - hint_text.get_width()//2, center_y - 200))
        
        # 绘制按钮
        for button in self.buttons:
            is_active = (self.game_state == "CHOOSING" and 
                        self.player_choice is not None and 
                        button["choice"] == self.player_choice)
            draw_button(surface, button["text"], button["rect"], button["hover"], is_active)
        
        # 绘制重置按钮
        draw_button(surface, "重置游戏", self.reset_button, self.reset_hover, False)
        
        # 绘制VS标识
        if self.player_choice is not None and self.computer_choice is not None and self.show_computer_choice:
            vs_text = title_font.render("VS", True, HIGHLIGHT)
            surface.blit(vs_text, (WIDTH//2 - vs_text.get_width()//2, center_y - 30))
        
        # 绘制历史记录
        history_title = small_font.render("最近对战记录:", True, TEXT_COLOR)
        surface.blit(history_title, (20, HEIGHT - 200))
        
        for i, record in enumerate(self.history[:5]):
            result_color = WIN_COLOR if "你赢了" in record["result"] else LOSE_COLOR if "电脑赢了" in record["result"] else DRAW_COLOR
            history_text = small_font.render(f"{record['player']} vs {record['computer']} - {record['result']}", True, result_color)
            surface.blit(history_text, (20, HEIGHT - 170 + i * 25))
        
        # 绘制游戏规则
        rules = [
            "游戏规则:",
            "• 石头打败剪刀",
            "• 剪刀打败布", 
            "• 布打败石头"
        ]
        
        for i, rule in enumerate(rules):
            rule_text = small_font.render(rule, True, TEXT_COLOR)
            surface.blit(rule_text, (WIDTH - 200, HEIGHT - 200 + i * 25))
    
    def handle_event(self, event):
        mouse_pos = pygame.mouse.get_pos()
        
        # 更新按钮悬停状态
        for button in self.buttons:
            button["hover"] = button["rect"].collidepoint(mouse_pos)
        
        self.reset_hover = self.reset_button.collidepoint(mouse_pos)
        
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            # 检查按钮点击
            for button in self.buttons:
                if button["rect"].collidepoint(mouse_pos):
                    if self.game_state == "CHOOSING":
                        self.player_choose(button["choice"])
                    elif self.game_state == "RESULT":
                        # 在结果显示状态下点击按钮，开始新的一轮
                        self.player_choose(button["choice"])
                    return
            
            # 检查重置按钮点击
            if self.reset_button.collidepoint(mouse_pos):
                self.reset_game()
                return
        
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_1 or event.key == pygame.K_KP1:
                # 按1选择石头
                if self.game_state == "CHOOSING":
                    self.player_choose(ROCK)
                elif self.game_state == "RESULT":
                    self.player_choose(ROCK)
            elif event.key == pygame.K_2 or event.key == pygame.K_KP2:
                # 按2选择剪刀
                if self.game_state == "CHOOSING":
                    self.player_choose(PAPER)
                elif self.game_state == "RESULT":
                    self.player_choose(PAPER)
            elif event.key == pygame.K_3 or event.key == pygame.K_KP3:
                # 按3选择布
                if self.game_state == "CHOOSING":
                    self.player_choose(SCISSORS)
                elif self.game_state == "RESULT":
                    self.player_choose(SCISSORS)
            elif event.key == pygame.K_r:
                # 按R重置游戏
                self.reset_game()
            elif event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()
    
    def reset_game(self):
        self.player_score = 0
        self.computer_score = 0
        self.draws = 0
        self.total_games = 0
        self.player_choice = None
        self.computer_choice = None
        self.result = None
        self.result_text = ""
        self.animation_step = 0
        self.show_computer_choice = False
        self.game_state = "CHOOSING"
        self.history = []

# 主函数
def main():
    clock = pygame.time.Clock()
    game = RockPaperScissorsGame()
    
    # 绘制初始界面
    screen.fill(BACKGROUND)
    title = title_font.render("石头剪刀布游戏", True, HIGHLIGHT)
    screen.blit(title, (WIDTH//2 - title.get_width()//2, HEIGHT//2 - 50))
    
    instruction = small_font.render("按任意键开始游戏", True, TEXT_COLOR)
    screen.blit(instruction, (WIDTH//2 - instruction.get_width()//2, HEIGHT//2 + 30))
    
    controls = [
        "控制说明:",
        "• 鼠标点击按钮选择出拳",
        "• 键盘1/2/3快速选择(石头/剪刀/布)",
        "• R键重置游戏",
        "• ESC键退出游戏"
    ]
    
    for i, line in enumerate(controls):
        control_text = small_font.render(line, True, TEXT_COLOR)
        screen.blit(control_text, (WIDTH//2 - control_text.get_width()//2, HEIGHT//2 + 80 + i * 25))
    
    pygame.display.flip()
    
    # 等待开始
    waiting = True
    while waiting:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN:
                waiting = False
    
    # 游戏主循环
    running = True
    while running:
        for event in pygame.event.get():
            game.handle_event(event)
        
        game.update()
        game.draw(screen)
        
        pygame.display.flip()
        clock.tick(60)

if __name__ == "__main__":
    main()
