import pygame
import sys

# 初始化pygame
pygame.init()
WIDTH, HEIGHT = 600, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("井字棋 · 超难AI（无法战胜）")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (220, 30, 30)
BLUE = (30, 80, 220)
LINE_COLOR = (50, 50, 50)

CELL_SIZE = WIDTH // 3
board = [[0, 0, 0],
         [0, 0, 0],
         [0, 0, 0]]
# 0=空 1=玩家(X) 2=AI(O)
player = 1
game_over = False

# 绘制棋盘
def draw_board():
    screen.fill(WHITE)
    # 网格线
    for i in range(1, 3):
        pygame.draw.line(screen, LINE_COLOR, (i*CELL_SIZE, 0), (i*CELL_SIZE, HEIGHT), 5)
        pygame.draw.line(screen, LINE_COLOR, (0, i*CELL_SIZE), (WIDTH, i*CELL_SIZE), 5)
    # 画X O
    for y in range(3):
        for x in range(3):
            val = board[y][x]
            cx = x * CELL_SIZE + CELL_SIZE//2
            cy = y * CELL_SIZE + CELL_SIZE//2
            if val == 1:
                # X
                offset = CELL_SIZE//3
                pygame.draw.line(screen, RED, (cx-offset, cy-offset), (cx+offset, cy+offset), 6)
                pygame.draw.line(screen, RED, (cx+offset, cy-offset), (cx-offset, cy+offset), 6)
            elif val == 2:
                # O
                pygame.draw.circle(screen, BLUE, (cx, cy), CELL_SIZE//3, 6)

# 判断胜负
def check_winner(b):
    # 横
    for row in b:
        if row[0]==row[1]==row[2] and row[0]!=0:
            return row[0]
    # 竖
    for col in range(3):
        if b[0][col]==b[1][col]==b[2][col] and b[0][col]!=0:
            return b[0][col]
    # 对角线
    if b[0][0]==b[1][1]==b[2][2] and b[0][0]!=0:
        return b[0][0]
    if b[0][2]==b[1][1]==b[2][0] and b[0][2]!=0:
        return b[0][2]
    # 是否还有空位
    empty = False
    for r in b:
        if 0 in r:
            empty=True
    if not empty:
        return 0 #平局
    return -1 #继续对局

# ===== Minimax 核心AI算法（超难关键）=====
def minimax(b, is_ai_turn):
    res = check_winner(b)
    if res == 2: #AI胜
        return 1
    if res == 1: #玩家胜
        return -1
    if res == 0: #平局
        return 0

    if is_ai_turn:
        best = -2
        for y in range(3):
            for x in range(3):
                if b[y][x]==0:
                    b[y][x]=2
                    score = minimax(b, False)
                    b[y][x]=0
                    best = max(best, score)
        return best
    else:
        best = 2
        for y in range(3):
            for x in range(3):
                if b[y][x]==0:
                    b[y][x]=1
                    score = minimax(b, True)
                    b[y][x]=0
                    best = min(best, score)
        return best

# AI寻找最优落子
def ai_move():
    best_score = -2
    move_x, move_y = 0, 0
    for y in range(3):
        for x in range(3):
            if board[y][x]==0:
                board[y][x]=2
                sc = minimax(board, False)
                board[y][x]=0
                if sc > best_score:
                    best_score = sc
                    move_x, move_y = x, y
    board[move_y][move_x] = 2

# 文字渲染
font = pygame.font.SysFont(None, 55)
def show_text(text):
    surf = font.render(text, True, BLACK)
    rect = surf.get_rect(center=(WIDTH//2, HEIGHT//2))
    screen.blit(surf, rect)

clock = pygame.time.Clock()

# 主循环
while True:
    draw_board()
    status = check_winner(board)

    if not game_over:
        if status == 1:
            show_text("你赢了（理论不可能！）")
            game_over=True
        elif status == 2:
            show_text("AI获胜！")
            game_over=True
        elif status == 0:
            show_text("平局！")
            game_over=True

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        # 鼠标点击落子（玩家X）
        if event.type == pygame.MOUSEBUTTONDOWN and not game_over:
            mx, my = pygame.mouse.get_pos()
            gx = mx // CELL_SIZE
            gy = my // CELL_SIZE
            if board[gy][gx] == 0:
                board[gy][gx] = 1
                # 玩家下完，AI行动
                if check_winner(board) == -1:
                    ai_move()

        # 按R重新开始
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r:
                board = [[0,0,0],[0,0,0],[0,0,0]]
                game_over = False

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