import pygame
import random
import os

# ===================== 初始化 =====================
pygame.init()
WIDTH, HEIGHT = 680, 460
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("石头剪刀布 - 五局三胜")
clock = pygame.time.Clock()

# 字体
font_main = pygame.font.SysFont("simhei", 34)
font_btn = pygame.font.SysFont("simhei", 24)
font_info = pygame.font.SysFont("simhei", 22)
font_small = pygame.font.SysFont("simhei", 18)

# 颜色
BG_COLOR = (230, 240, 255)
WHITE = (255, 255, 255)
BLACK = (10, 10, 10)
GRAY = (110, 110, 110)
GREEN = (35, 165, 70)
RED = (195, 45, 45)
BLUE = (45, 105, 200)
ORANGE = (220, 125, 25)

# 选项
ROCK = "石头"
SCISSORS = "剪刀"
PAPER = "布"
choices = [ROCK, SCISSORS, PAPER]

# ===================== 音效加载（容错处理） =====================
sound_win = None
sound_lose = None
try:
    sound_win = pygame.mixer.Sound("sound/win.wav")
    sound_lose = pygame.mixer.Sound("sound/lose.wav")
except:
    print("警告：未找到音效文件，程序静音运行")

# ===================== 最高分文件读写 =====================
SCORE_FILE = "score.txt"
best_record = 0

def load_best_score():
    global best_record
    if os.path.exists(SCORE_FILE):
        try:
            with open(SCORE_FILE, "r", encoding="utf-8") as f:
                best_record = int(f.read())
        except:
            best_record = 0

def save_best_score(val):
    with open(SCORE_FILE, "w", encoding="utf-8") as f:
        f.write(str(val))

load_best_score()

# ===================== 游戏变量 =====================
def reset_game():
    """重置一局比赛（五局三胜重新开始）"""
    global player_win_round, computer_win_round, player_choice, computer_choice, result_text, game_over
    player_win_round = 0
    computer_win_round = 0
    player_choice = ""
    computer_choice = ""
    result_text = "点击下方按钮开始对局！"
    game_over = False

reset_game()

# 按钮矩形
btn_rock = pygame.Rect(50, 330, 140, 60)
btn_scissors = pygame.Rect(230, 330, 140, 60)
btn_paper = pygame.Rect(410, 330, 140, 60)
btn_restart = pygame.Rect(250, 398, 160, 45)


def judge_round(player, computer):
    """单局判定，返回对局结果文本"""
    global player_win_round, computer_win_round
    if player == computer:
        return "本局：平局"
    win_condition = (
        (player == ROCK and computer == SCISSORS) or
        (player == SCISSORS and computer == PAPER) or
        (player == PAPER and computer == ROCK)
    )
    if win_condition:
        player_win_round += 1
        if sound_win:
            sound_win.play()
        return "本局：你获胜！"
    else:
        computer_win_round += 1
        if sound_lose:
            sound_lose.play()
        return "本局：电脑获胜！"


running = True
while running:
    mouse_pos = pygame.mouse.get_pos()
    screen.fill(BG_COLOR)

    # 标题
    title_surf = font_main.render("石头剪刀布｜五局三胜", True, BLACK)
    screen.blit(title_surf, (WIDTH//2 - title_surf.get_width()//2, 20))

    # 比分信息
    score_text = font_info.render(f"你的胜场：{player_win_round} | 电脑胜场：{computer_win_round}", True, BLUE)
    screen.blit(score_text, (WIDTH//2 - score_text.get_width()//2, 70))

    best_text = font_small.render(f"历史最佳连胜局数：{best_record}", True, GRAY)
    screen.blit(best_text, (20, 20))

    # 选择信息
    p_text = font_info.render(f"你的选择：{player_choice}", True, GREEN)
    screen.blit(p_text, (80, 120))
    c_text = font_info.render(f"电脑选择：{computer_choice}", True, RED)
    screen.blit(c_text, (80, 160))

    # 当前对局结果
    res_surf = font_main.render(result_text, True, BLACK)
    screen.blit(res_surf, (WIDTH//2 - res_surf.get_width()//2, 210))

    # 绘制按钮函数
    def draw_button(rect, text, hover_color=ORANGE, normal_color=BLUE):
        hover = rect.collidepoint(mouse_pos)
        color = hover_color if hover else normal_color
        pygame.draw.rect(screen, color, rect, border_radius=9)
        pygame.draw.rect(screen, BLACK, rect, 2, border_radius=9)
        txt = font_btn.render(text, True, WHITE)
        screen.blit(txt, (rect.centerx - txt.get_width()//2, rect.y + 14))

    if not game_over:
        draw_button(btn_rock, ROCK)
        draw_button(btn_scissors, SCISSORS)
        draw_button(btn_paper, PAPER)
    else:
        draw_button(btn_restart, "重新开始游戏", GREEN, (20,140,60))

    # 事件循环
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if not game_over:
                # 玩家出拳
                if btn_rock.collidepoint(mouse_pos):
                    player_choice = ROCK
                elif btn_scissors.collidepoint(mouse_pos):
                    player_choice = SCISSORS
                elif btn_paper.collidepoint(mouse_pos):
                    player_choice = PAPER
                else:
                    continue
                # 电脑随机
                computer_choice = random.choice(choices)
                result_text = judge_round(player_choice, computer_choice)

                # 判断五局三胜结束条件
                if player_win_round >= 3:
                    result_text = "🎉恭喜！你赢得本场比赛！"
                    game_over = True
                    # 更新最高分
                    if 3 > best_record:
                        best_record = 3
                        save_best_score(best_record)
                elif computer_win_round >= 3:
                    result_text = "😥遗憾！电脑赢得本场比赛！"
                    game_over = True
            else:
                # 游戏结束，点击重新开始
                if btn_restart.collidepoint(mouse_pos):
                    reset_game()

    pygame.display.flip()
    clock.tick(60)

pygame.quit()