编辑代码

import tkinter as tk
from tkinter import messagebox
import random

class Minesweeper:
    def __init__(self, master, rows=10, cols=10, mines=15):
        self.master = master
        self.rows = rows
        self.cols = cols
        self.mines = mines
        self.buttons = [[None for _ in range(cols)] for _ in range(rows)]
        self.board = [[0 for _ in range(cols)] for _ in range(rows)]
        self.game_over = False
        self.init_board()
        self.create_widgets()
        
    def init_board(self):
        # 随机布置地雷
        mines_placed = 0
        while mines_placed < self.mines:
            x = random.randint(0, self.rows-1)
            y = random.randint(0, self.cols-1)
            if self.board[x][y] != -1:
                self.board[x][y] = -1
                mines_placed += 1

        # 计算周围地雷数量
        for i in range(self.rows):
            for j in range(self.cols):
                if self.board[i][j] != -1:
                    self.board[i][j] = self.count_mines(i, j)

    def count_mines(self, x, y):
        count = 0
        for i in range(max(0, x-1), min(self.rows, x+2)):
            for j in range(max(0, y-1), min(self.cols, y+2)):
                if self.board[i][j] == -1:
                    count += 1
        return count

    def create_widgets(self):
        for i in range(self.rows):
            for j in range(self.cols):
                btn = tk.Button(self.master, width=2, height=1,
                              command=lambda x=i, y=j: self.click(x, y))
                btn.bind("<Button-3>", lambda e, x=i, y=j: self.right_click(x, y))
                btn.grid(row=i, column=j)
                self.buttons[i][j] = btn

    def click(self, x, y):
        if self.game_over or self.buttons[x][y]['state'] == 'disabled':
            return

        if self.board[x][y] == -1:  # 踩中地雷
            self.buttons[x][y].config(text='*', bg='red')
            self.game_over = True
            self.reveal_all()
            messagebox.showinfo("游戏结束", "你踩到地雷了!")
        else:
            self.reveal(x, y)
            if self.check_win():
                self.game_over = True
                messagebox.showinfo("游戏胜利", "恭喜你扫雷成功!")

    def right_click(self, x, y):
        btn = self.buttons[x][y]
        if btn['state'] == 'normal':
            if not btn['text']:
                btn.config(text='��', fg='red')
            elif btn['text'] == '��':
                btn.config(text='?', fg='blue')
            else:
                btn.config(text='')

    def reveal(self, x, y):
        if x < 0 or x >= self.rows or y < 0 or y >= self.cols:
            return
        btn = self.buttons[x][y]
        if btn['state'] == 'disabled' or btn['text'] == '��':
            return

        value = self.board[x][y]
        if value != 0:
            colors = ['', 'blue', 'green', 'red', 'purple', 'black', 'gray', 'orange', 'brown']
            btn.config(text=str(value) if value > 0 else '', 
                     fg=colors[value] if value > 0 else 'black',
                     state='disabled')
        else:
            btn.config(text='', state='disabled')
            # 递归翻开周围格子
            for i in range(max(0, x-1), min(self.rows, x+2)):
                for j in range(max(0, y-1), min(self.cols, y+2)):
                    self.reveal(i, j)

    def reveal_all(self):
        for i in range(self.rows):
            for j in range(self.cols):
                if self.board[i][j] == -1:
                    self.buttons[i][j].config(text='*', bg='yellow')
                elif self.board[i][j] > 0:
                    self.buttons[i][j].config(text=str(self.board[i][j]))

    def check_win(self):
        for i in range(self.rows):
            for j in range(self.cols):
                if self.board[i][j] != -1 and self.buttons[i][j]['state'] == 'normal':
                    return False
        return True

if __name__ == "__main__":
    root = tk.Tk()
    root.title("扫雷游戏")
    game = Minesweeper(root)
    root.mainloop()