import pygame
import random
import os

# 初始化pygame
pygame.init()

# 窗口设置
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("石头剪刀布")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (180, 180, 180)
BLUE = (60, 120, 220)
RED = (220, 60, 60)
GREEN = (60, 180, 80)

# ===== 修复中文字体（Windows系统通用路径，不用外部文件）=====
try:
    # Windows自带微软雅黑绝对路径
    font_path = r"C:\Windows\Fonts\msyh.ttc"
    font = pygame.font.Font(font_path, 32)
    small_font = pygame.font.Font(font_path, 24)
except:
    # 兜底方案，如果上面失败，切换英文防止崩溃
    font = pygame.font.Font(None, 32)
    small_font = pygame.font.Font(None, 24)

# 游戏数据
choices = ["石头", "剪刀", "布"]
player_choice = ""
computer_choice = ""
result_text = "请选择石头、剪刀或布！"
score_player = 0
score_computer = 0

# 按钮区域
buttons = [
    {"text": "石头", "rect": pygame.Rect(80, 280, 120, 60)},
    {"text": "剪刀", "rect": pygame.Rect(240, 280, 120, 60)},
    {"text": "布", "rect": pygame.Rect(400, 280, 120, 60)},
]

def get_result(player, computer):
    global score_player, score_computer
    if player == computer:
        return "平局！"
    win_rules = {
        ("石头", "剪刀"),
        ("剪刀", "布"),
        ("布", "石头")
    }
    if (player, computer) in win_rules:
        score_player += 1
        return "你赢了！"
    else:
        score_computer += 1
        return "你输了！"

clock = pygame.time.Clock()
running = True

while running:
    screen.fill(WHITE)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mouse_pos = pygame.mouse.get_pos()
            for btn in buttons:
                if btn["rect"].collidepoint(mouse_pos):
                    player_choice = btn["text"]
                    computer_choice = random.choice(choices)
                    result_text = get_result(player_choice, computer_choice)

    # 绘制文字信息
    score_text = font.render(f"你:{score_player}  电脑:{score_computer}", True, BLACK)
    screen.blit(score_text, (20, 20))

    p_text = font.render(f"你的选择：{player_choice}", True, BLUE)
    screen.blit(p_text, (20, 80))

    c_text = font.render(f"电脑选择：{computer_choice}", True, RED)
    screen.blit(c_text, (20, 130))

    res_text = font.render(result_text, True, GREEN)
    screen.blit(res_text, (20, 180))

    # 绘制按钮
    for btn in buttons:
        pygame.draw.rect(screen, GRAY, btn["rect"], border_radius=8)
        pygame.draw.rect(screen, BLACK, btn["rect"], 2, border_radius=8)
        text_surf = small_font.render(btn["text"], True, BLACK)
        tx = btn["rect"].x + (btn["rect"].w - text_surf.get_width()) // 2
        ty = btn["rect"].y + (btn["rect"].h - text_surf.get_height()) // 2
        screen.blit(text_surf, (tx, ty))

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

pygame.quit()