冲浪的口香糖 发表于 2025-7-3 13:36:56

tkinter扫雷

背景是黑色,其他玩法和普通扫雷一样,代码如下:
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 = {}
      self.mine_positions = set()
      self.create_widgets()
      self.place_mines()
      self.calculate_adjacent_mines()
      
    def create_widgets(self):
      # 设置主窗口背景为黑色
      self.master.configure(bg='black')
      
      # 创建菜单
      menubar = tk.Menu(self.master, bg='black', fg='white')
      self.master.config(menu=menubar)
      game_menu = tk.Menu(menubar, tearoff=0, bg='black', fg='white')
      game_menu.add_command(label="新游戏", command=self.reset_game)
      game_menu.add_separator()
      game_menu.add_command(label="退出", command=self.master.quit)
      menubar.add_cascade(label="游戏", menu=game_menu)
      
      # 创建扫雷区域
      for row in range(self.rows):
            for col in range(self.cols):
                btn = tk.Button(
                  self.master,
                  text=' ',
                  width=2,
                  height=1,
                  bg='black',# 初始背景为黑色
                  fg='white',# 文字颜色为白色
                  activebackground='gray',# 点击时的背景色
                  relief=tk.RAISED,# 按钮凸起效果
                  command=lambda r=row, c=col: self.on_click(r, c)
                )
                btn.bind('<Button-3>', lambda e, r=row, c=col: self.on_right_click(r, c))
                btn.grid(row=row, column=col)
                self.buttons[(row, col)] = btn
               
    def place_mines(self):
      # 随机放置地雷
      while len(self.mine_positions) < self.mines:
            row = random.randint(0, self.rows - 1)
            col = random.randint(0, self.cols - 1)
            self.mine_positions.add((row, col))
            
    def calculate_adjacent_mines(self):
      # 计算每个格子周围的地雷数
      self.adjacent_mines = {}
      for row in range(self.rows):
            for col in range(self.cols):
                if (row, col) in self.mine_positions:
                  self.adjacent_mines[(row, col)] = -1# -1表示地雷
                  continue
               
                count = 0
                for r in range(max(0, row-1), min(self.rows, row+2)):
                  for c in range(max(0, col-1), min(self.cols, col+2)):
                        if (r, c) in self.mine_positions:
                            count += 1
                self.adjacent_mines[(row, col)] = count
               
    def on_click(self, row, col):
      # 处理左键点击
      if (row, col) in self.mine_positions:
            self.game_over()
      else:
            self.reveal_cell(row, col)
            self.check_win()
            
    def on_right_click(self, row, col):
      # 处理右键点击(标记地雷)
      btn = self.buttons[(row, col)]
      if btn['state'] == 'normal':
            btn.config(text='&#128681;', state='disabled', bg='black')
      elif btn['text'] == '&#128681;':
            btn.config(text=' ', state='normal', bg='black')
            
    def reveal_cell(self, row, col):
      # 显示格子内容
      if (row, col) not in self.buttons or self.buttons[(row, col)]['state'] == 'disabled':
            return
            
      btn = self.buttons[(row, col)]
      btn.config(state='disabled', bg='white')# 被点击后背景变为白色
      
      mines = self.adjacent_mines[(row, col)]
      if mines > 0:
            # 数字颜色保持不变,但背景变为白色
            colors = ['', 'blue', 'green', 'red', 'darkblue',
                     'brown', 'cyan', 'black', 'gray']
            btn.config(text=str(mines), fg=colors, bg='white')
      else:
            btn.config(text='', bg='white')
            # 如果是空白格子,递归显示周围的格子
            for r in range(max(0, row-1), min(self.rows, row+2)):
                for c in range(max(0, col-1), min(self.cols, col+2)):
                  if (r, c) != (row, col):
                        self.reveal_cell(r, c)
                        
    def game_over(self):
      # 游戏结束,显示所有地雷
      for row, col in self.mine_positions:
            self.buttons[(row, col)].config(text='&#128163;', bg='red', fg='black')
      messagebox.showinfo("游戏结束", "你踩到地雷了!")
      self.reset_game()
      
    def check_win(self):
      # 检查是否获胜
      for row in range(self.rows):
            for col in range(self.cols):
                if (row, col) not in self.mine_positions and self.buttons[(row, col)]['state'] == 'normal':
                  return
      messagebox.showinfo("恭喜", "你赢了!")
      self.reset_game()
      
    def reset_game(self):
      # 重置游戏
      self.mine_positions = set()
      for row, col in self.buttons:
            btn = self.buttons[(row, col)]
            btn.config(text=' ', state='normal', bg='black', fg='white')
      self.place_mines()
      self.calculate_adjacent_mines()

if __name__ == "__main__":
    root = tk.Tk()
    root.title("扫雷 - 黑色主题版")
    game = Minesweeper(root)
    root.mainloop()

某一个“天” 发表于 2025-7-3 14:59:37

{:10_275:}

pyzyd 发表于 2025-7-3 15:30:44

{:5_106:}

sunshine_8205 发表于 2025-7-3 15:52:58

{:5_106:}
页: [1]
查看完整版本: tkinter扫雷