import random
import os


class Minesweeper:
    def __init__(self, width=10, height=10, mines=10):
        self.width = width
        self.height = height
        self.mines = mines
        self.board = [[0 for _ in range(width)] for _ in range(height)]
        self.revealed = [[False for _ in range(width)] for _ in range(height)]
        self.marked = [[False for _ in range(width)] for _ in range(height)]
        self.game_over = False
        self.win = False
        self.first_click = True

    def place_mines(self, exclude_x, exclude_y):
        """在除了第一次点击位置之外的地方放置地雷"""
        positions = [(x, y) for x in range(self.width) for y in range(self.height)]
        positions.remove((exclude_x, exclude_y))  # 确保第一次点击的位置没有地雷
        mine_positions = random.sample(positions, self.mines)

        for x, y in mine_positions:
            self.board[y][x] = -1  # -1 表示地雷

        # 计算每个非地雷格子周围的地雷数
        for y in range(self.height):
            for x in range(self.width):
                if self.board[y][x] == -1:
                    continue
                count = 0
                for dy in [-1, 0, 1]:
                    for dx in [-1, 0, 1]:
                        if dx == 0 and dy == 0:
                            continue
                        nx, ny = x + dx, y + dy
                        if 0 <= nx < self.width and 0 <= ny < self.height:
                            if self.board[ny][nx] == -1:
                                count += 1
                self.board[y][x] = count

    def reveal(self, x, y):
        """揭示一个格子"""
        if not (0 <= x < self.width and 0 <= y < self.height):
            return
        if self.revealed[y][x] or self.marked[y][x]:
            return

        if self.first_click:
            self.place_mines(x, y)
            self.first_click = False

        self.revealed[y][x] = True

        # 如果点击到地雷，游戏结束
        if self.board[y][x] == -1:
            self.game_over = True
            return

        # 如果周围没有地雷，自动揭示周围的格子
        if self.board[y][x] == 0:
            for dy in [-1, 0, 1]:
                for dx in [-1, 0, 1]:
                    if dx == 0 and dy == 0:
                        continue
                    self.reveal(x + dx, y + dy)

        # 检查是否获胜
        self.check_win()

    def toggle_mark(self, x, y):
        """标记或取消标记一个格子"""
        if not (0 <= x < self.width and 0 <= y < self.height):
            return
        if self.revealed[y][x]:
            return
        self.marked[y][x] = not self.marked[y][x]
        self.check_win()

    def check_win(self):
        """检查是否获胜"""
        for y in range(self.height):
            for x in range(self.width):
                # 如果所有非地雷格子都被揭示，则获胜
                if self.board[y][x] != -1 and not self.revealed[y][x]:
                    return
        self.win = True
        self.game_over = True

    def display(self):
        """显示游戏板"""
        # 清屏
        os.system('cls' if os.name == 'nt' else 'clear')

        # 打印列号
        print("  ", end="")
        for x in range(self.width):
            print(f"{x % 10} ", end="")
        print()

        # 打印分隔线
        print("  ", end="")
        for x in range(self.width):
            print("- ", end="")
        print()

        # 打印行
        for y in range(self.height):
            print(f"{y % 10}|", end="")  # 行号
            for x in range(self.width):
                if self.marked[y][x]:
                    print("F ", end="")  # 标记
                elif not self.revealed[y][x]:
                    print(". ", end="")  # 未揭示
                elif self.board[y][x] == -1:
                    print("* ", end="")  # 地雷
                elif self.board[y][x] == 0:
                    print("  ", end="")  # 空白
                else:
                    print(f"{self.board[y][x]} ", end="")  # 数字
            print()

    def play(self):
        """开始游戏"""
        while not self.game_over:
            self.display()
            print("\n命令:")
            print("  r x y - 揭示格子 (例如: r 3 5)")
            print("  m x y - 标记/取消标记格子 (例如: m 3 5)")
            print("  q - 退出游戏")

            try:
                command = input("\n请输入命令: ").strip().split()
                if not command:
                    continue

                if command[0].lower() == 'q':
                    return

                if len(command) != 3:
                    print("无效命令！请按照格式输入。")
                    continue

                action = command[0].lower()
                x = int(command[1])
                y = int(command[2])

                if action == 'r':
                    self.reveal(x, y)
                elif action == 'm':
                    self.toggle_mark(x, y)
                else:
                    print("无效命令！使用 'r' 揭示或 'm' 标记。")

            except (ValueError, IndexError):
                print("无效输入！请确保输入正确的坐标。")

        # 游戏结束，显示最终结果
        self.display()
        if self.win:
            print("\n恭喜你！你赢了！")
        else:
            print("\n游戏结束！你踩到地雷了。")


def main():
    print("欢迎来到扫雷游戏！")
    print("游戏规则：")
    print("1. 输入 'r x y' 来揭示坐标 (x,y) 的格子")
    print("2. 输入 'm x y' 来标记/取消标记可能有地雷的格子")
    print("3. 数字表示周围8个格子中有多少个地雷")
    print("4. 标记所有地雷并揭示所有安全格子即可获胜")
    print("\n按回车键开始游戏...")
    input()

    # 创建游戏实例（10x10的棋盘，10个地雷）
    game = Minesweeper(10, 10, 10)
    game.play()


if __name__ == "__main__":
    main()
