import pygame
import random
import sys

pygame.init()
WIDTH, HEIGHT = 900, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("斗地主 人机对战")

# 颜色常量（补上缺失的BLUE！）
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (200, 0, 0)
GREEN = (0, 120, 0)
GRAY = (160, 160, 160)
LIGHT_BLUE = (180, 220, 255)
BLUE = (20, 60, 160)   # 修复：新增缺失的蓝色定义

# 字体兼容海龟编辑器
font = pygame.font.Font(None, 36)
small_font = pygame.font.Font(None, 28)

# 扑克牌定义
card_values = ["3","4","5","6","7","8","9","10","J","Q","K","A","2","★","☆"]
card_suit_color = [RED]*13 + [RED, BLACK]
CARD_W = 70
CARD_H = 100

# 生成完整扑克牌
def create_deck():
    deck = []
    # 3~2 各4张
    for v in range(13):
        for _ in range(4):
            deck.append(v)
    deck.append(13)  #小王
    deck.append(14)  #大王
    random.shuffle(deck)
    return deck

# 绘制单张卡牌
def draw_card(x, y, card_val, selected=False, hidden=False):
    if hidden:
        pygame.draw.rect(screen, BLUE, (x, y, CARD_W, CARD_H))
        pygame.draw.rect(screen, BLACK, (x, y, CARD_W, CARD_H), 2)
        return
    fill_color = LIGHT_BLUE if selected else WHITE
    pygame.draw.rect(screen, fill_color, (x, y, CARD_W, CARD_H))
    pygame.draw.rect(screen, BLACK, (x, y, CARD_W, CARD_H), 2)
    text = font.render(card_values[card_val], True, card_suit_color[card_val])
    screen.blit(text, (x + 6, y + 6))

# 游戏初始化
def reset_game():
    global deck, player_hand, ai_hand, bottom_cards
    global is_player_landlord, stage, msg, selected_index
    global last_play, player_turn, pass_count
    deck = create_deck()
    player_hand = sorted(deck[:17])
    ai_hand = sorted(deck[17:34])
    bottom_cards = deck[34:]
    is_player_landlord = False
    stage = "bid"      # bid抢地主 / play对战
    msg = "空格抢地主，N不抢"
    selected_index = []
    last_play = []     # 上一轮打出的牌
    player_turn = False
    pass_count = 0

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

while running:
    screen.fill(GREEN)
    mouse_x, mouse_y = pygame.mouse.get_pos()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 键盘事件
        if event.type == pygame.KEYDOWN:
            if stage == "bid":
                # 抢地主阶段
                if event.key == pygame.K_SPACE:
                    is_player_landlord = True
                    player_hand.extend(bottom_cards)
                    player_hand.sort()
                    stage = "play"
                    player_turn = True
                    msg = "你是地主，请出牌！鼠标点击选牌，回车出牌，P不出"
                if event.key == pygame.K_n:
                    is_player_landlord = False
                    ai_hand.extend(bottom_cards)
                    ai_hand.sort()
                    stage = "play"
                    player_turn = False
                    msg = "AI是地主，等待AI出牌..."
            elif stage == "play":
                # 玩家回合操作
                if player_turn:
                    # 回车出牌
                    if event.key == pygame.K_RETURN:
                        if len(selected_index) > 0:
                            out_cards = [player_hand[i] for i in selected_index]
                            # 移除手牌
                            for i in sorted(selected_index, reverse=True):
                                del player_hand[i]
                            last_play = out_cards
                            selected_index.clear()
                            pass_count = 0
                            player_turn = False
                            msg = "等待AI出牌"
                    # P键 不出
                    if event.key == pygame.K_p:
                        pass_count += 1
                        selected_index.clear()
                        player_turn = False
                        msg = "你选择不出，等待AI"
        # 鼠标点击选牌
        if event.type == pygame.MOUSEBUTTONDOWN and stage == "play" and player_turn:
            for idx, card in enumerate(player_hand):
                cx = 50 + idx * (CARD_W + 6)
                cy = HEIGHT - CARD_H - 20
                rect = pygame.Rect(cx, cy, CARD_W, CARD_H)
                if rect.collidepoint(mouse_x, mouse_y):
                    if idx in selected_index:
                        selected_index.remove(idx)
                    else:
                        selected_index.append(idx)

    # ===================== AI出牌逻辑 =====================
    if stage == "play" and not player_turn and pass_count < 2:
        # 防止持续循环卡顿，加标记避免无限执行
        if "ai_action_wait" not in locals():
            import time
            time.sleep(0.6)
            if len(ai_hand) > 0:
                out = [ai_hand.pop(0)]
                last_play = out
                pass_count = 0
                player_turn = True
                msg = f"AI打出 {card_values[out[0]]}，轮到你！"
            else:
                # AI手牌打完，AI胜利
                msg = "AI胜利！关闭窗口重开"
                stage = "end"
            ai_action_wait = True
    else:
        if "ai_action_wait" in locals():
            del ai_action_wait

    # 玩家胜利判定
    if len(player_hand) == 0 and stage == "play":
        msg = "你胜利！关闭窗口重开"
        stage = "end"

    # 绘制AI手牌（上方暗牌）
    for i in range(len(ai_hand)):
        draw_card(50 + i * (CARD_W + 4), 30, 0, hidden=True)

    # 绘制玩家手牌（底部）
    for idx, card in enumerate(player_hand):
        cx = 50 + idx * (CARD_W + 6)
        cy = HEIGHT - CARD_H - 20
        sel = idx in selected_index
        draw_card(cx, cy, card, selected=sel)

    # 绘制底牌（抢地主阶段显示）
    if stage == "bid":
        for i, c in enumerate(bottom_cards):
            draw_card(WIDTH//2 - 100 + i*(CARD_W+10), HEIGHT//2, c)

    # 文字提示
    tip_text = font.render(msg, True, WHITE)
    screen.blit(tip_text, (20, 10))

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

pygame.quit()
sys.exit()