import pygame
import random
import sys

pygame.init()
WIDTH = 400
HEIGHT = 440
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("扫雷")

# 颜色
GRAY = (180, 180, 180)
DARK_GRAY = (120, 120, 120)
WHITE = (240, 240, 240)
BLACK = (0, 0, 0)
RED = (220, 0, 0)
BLUE = (0, 0, 220)
GREEN = (0, 160, 0)

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

# 地图参数
SIZE = 10
CELL = 40
MINE_COUNT = 15

# 数字颜色
num_color = [
    None,
    (0, 0, 255),    #1蓝
    (0, 128, 0),    #2绿
    (255, 0, 0),    #3红
    (0, 0, 128),    #4深蓝
    (128, 0, 0),    #5暗红
    (0, 128, 128),  #6青
    (0, 0, 0),      #7黑
    (128, 128, 128) #8灰
]

# 初始化数据
grid = []
is_mine = []
opened = []
flag = []
game_over = False
win = False

def reset_game():
    global grid, is_mine, opened, flag, game_over, win
    game_over = False
    win = False
    # 初始化数组
    grid = [[0]*SIZE for _ in range(SIZE)]
    is_mine = [[False]*SIZE for _ in range(SIZE)]
    opened = [[False]*SIZE for _ in range(SIZE)]
    flag = [[False]*SIZE for _ in range(SIZE)]
    
    # 随机放地雷
    mines_placed = 0
    while mines_placed < MINE_COUNT:
        x = random.randint(0, SIZE-1)
        y = random.randint(0, SIZE-1)
        if not is_mine[y][x]:
            is_mine[y][x] = True
            mines_placed += 1
    # 计算周围地雷数量
    for y in range(SIZE):
        for x in range(SIZE):
            if is_mine[y][x]:
                continue
            cnt = 0
            for dy in (-1,0,1):
                for dx in (-1,0,1):
                    ny = y + dy
                    nx = x + dx
                    if 0<=ny<SIZE and 0<=nx<SIZE and is_mine[ny][nx]:
                        cnt += 1
            grid[y][x] = cnt

# 递归翻开空白格子
def open_cell(x, y):
    if opened[y][x] or flag[y][x]:
        return
    opened[y][x] = True
    if grid[y][x] == 0:
        for dy in (-1,0,1):
            for dx in (-1,0,1):
                ny = y + dy
                nx = x + dx
                if 0<=ny<SIZE and 0<=nx<SIZE:
                    open_cell(nx, ny)

# 检查是否胜利
def check_win():
    open_cells = 0
    total = SIZE*SIZE - MINE_COUNT
    for y in range(SIZE):
        for x in range(SIZE):
            if opened[y][x]:
                open_cells += 1
    return open_cells == total

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

running = True
while running:
    screen.fill(GRAY)
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN and not game_over:
            mx, my = event.pos
            gx = mx // CELL
            gy = my // CELL
            if 0 <= gx < SIZE and 0 <= gy < SIZE:
                # 左键翻开
                if event.button == 1:
                    if flag[gy][gx]:
                        continue
                    if is_mine[gy][gx]:
                        game_over = True
                    else:
                        open_cell(gx, gy)
                        if check_win():
                            game_over = True
                            win = True
                # 右键插旗
                elif event.button == 3:
                    if not opened[gy][gx]:
                        flag[gy][gx] = not flag[gy][gx]
        # 按R重新开局
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r:
                reset_game()

    # 绘制格子
    for y in range(SIZE):
        for x in range(SIZE):
            rect = pygame.Rect(x*CELL, y*CELL, CELL-1, CELL-1)
            if opened[y][x]:
                pygame.draw.rect(screen, WHITE, rect)
                if is_mine[y][x]:
                    pygame.draw.circle(screen, BLACK, rect.center, 12)
                else:
                    num = grid[y][x]
                    if num > 0:
                        txt = font.render(str(num), True, num_color[num])
                        r = txt.get_rect(center=rect.center)
                        screen.blit(txt, r)
            else:
                pygame.draw.rect(screen, DARK_GRAY, rect)
                if flag[y][x]:
                    pygame.draw.circle(screen, RED, rect.center, 10)
    
    # 游戏结束提示
    if game_over:
        overlay = pygame.Surface((WIDTH, HEIGHT))
        overlay.set_alpha(140)
        overlay.fill(BLACK)
        screen.blit(overlay, (0,0))
        if win:
            text = tip_font.render("胜利！按R重开", True, GREEN)
        else:
            text = tip_font.render("踩雷！按R重开", True, RED)
        rt = text.get_rect(center=(WIDTH//2, HEIGHT//2))
        screen.blit(text, rt)
    
    pygame.display.update()
    clock.tick(60)

pygame.quit()
sys.exit()