Python
import tkinter as tk
from tkinter import messagebox
class Minesweeper:
def __init__(self, master, width=10, height=10, mines=15):
self.master = master
self.width = width
self.height = height
self.total_mines = mines
self.first_click = True
self.game_over = False
# 初始化游戏数据
self.grid = [[0 for _ in range(width)] for _ in range(height)]
self.buttons = [[None for _ in range(width)] for _ in range(height)]
self.mine_locations = set()
self.revealed = [[False for _ in range(width)] for _ in range(height)]
self.flags = [[False for _ in range(width)] for _ in range(height)]
# 创建界面
self.create_widgets()
self.reset_game_data()
def create_widgets(self):
# 顶部信息栏
top_frame = tk.Frame(self.master)
top_frame.pack(pady=10, fill=tk.X, padx=10)
self.mine_label = tk.Label(top_frame, text=f"地雷: {self.total_mines}", font=("Arial", 12))
self.mine_label.pack(side=tk.LEFT, padx=10)
self.restart_btn = tk.Button(top_frame, text="重置", command=self.reset_game_data, font=("Arial", 12))
self.restart_btn.pack(side=tk.LEFT, padx=10)
self.status_label = tk.Label(top_frame, text="游戏中", font=("Arial", 12))
self.status_label.pack(side=tk.LEFT, padx=10)
# 游戏区域容器
self.game_container = tk.Frame(self.master)
self.game_container.pack(padx=10, pady=10)
def reset_game_data(self):
self.first_click = True
self.game_over = False
self.mine_locations.clear()
self.revealed = [[False for _ in range(self.width)] for _ in range(self.height)]
self.flags = [[False for _ in range(self.width)] for _ in range(self.height)]
self.grid = [[0 for _ in range(self.width)] for _ in range(self.height)]
# 清除旧按钮
for widget in self.game_container.winfo_children():
widget.destroy()
# 创建新按钮网格
for y in range(self.height):
for x in range(self.width):
btn = tk.Button(
self.game_container,
width=2,
height=1,
font=("Arial", 10, "bold"),
bg="#c0c0c0",
relief=tk.RAISED
)
btn.bind("<Button-1>", lambda e, x=x, y=y: self.on_left_click(x, y))
btn.bind("<Button-3>", lambda e, x=x, y=y: self.on_right_click(x, y))
btn.grid(row=y, column=x)
self.buttons[y][x] = btn
self.update_status("游戏中")
self.mine_label.config(text=f"地雷: {self.total_mines}")
def place_mines(self, safe_x, safe_y):
# 确保第一次点击的位置及其周围没有雷
safe_zone = set()
for dy in [-1, 0, 1]:
for dx in [-1, 0, 1]:
nx, ny = safe_x + dx, safe_y + dy
if 0 <= nx < self.width and 0 <= ny < self.height:
safe_zone.add((nx, ny))
placed = 0
while placed < self.total_mines:
x = random.randint(0, self.width - 1)
y = random.randint(0, self.height - 1)
if (x, y) not in self.mine_locations and (x, y) not in safe_zone:
self.mine_locations.add((x, y))
self.grid[y][x] = -1 # -1 表示地雷
placed += 1
# 计算数字
for y in range(self.height):
for x in range(self.width):
if self.grid[y][x] == -1:
continue
count = 0
for dy in [-1, 0, 1]:
for dx in [-1, 0, 1]:
nx, ny = x + dx, y + dy
if 0 <= nx < self.width and 0 <= ny < self.height:
if self.grid[ny][nx] == -1:
count += 1
self.grid[y][x] = count
def on_left_click(self, x, y):
if self.game_over or self.flags[y][x] or self.revealed[y][x]:
return
if self.first_click:
self.place_mines(x, y)
self.first_click = False
self.reveal_cell(x, y)
self.check_win()
def reveal_cell(self, x, y):
if not (0 <= x < self.width and 0 <= y < self.height):
return
if self.revealed[y][x] or self.flags[y][x]:
return
self.revealed[y][x] = True
btn = self.buttons[y][x]
btn.config(relief=tk.SUNKEN, bg="#e0e0e0")
val = self.grid[y][x]
if val == -1:
btn.config(text="💣", bg="red")
self.game_over = True
self.reveal_all_mines()
self.update_status("游戏失败!")
messagebox.showerror("游戏结束", "你被地雷崩飞了!")
elif val > 0:
colors = ["", "blue", "green", "red", "darkblue", "brown", "cyan", "black", "gray"]
btn.config(text=str(val), fg=colors[val])
else:
# 空白格,递归展开
for dy in [-1, 0, 1]:
for dx in [-1, 0, 1]:
self.reveal_cell(x + dx, y + dy)
def on_right_click(self, x, y):
if self.game_over or self.revealed[y][x]:
return
btn = self.buttons[y][x]
if self.flags[y][x]:
self.flags[y][x] = False
btn.config(text="", bg="#c0c0c0")
else:
self.flags[y][x] = True
btn.config(text="🚩", fg="red")
# 更新剩余雷数显示
flag_count = sum(row.count(True) for row in self.flags)
self.mine_label.config(text=f"地雷: {self.total_mines - flag_count}")
def reveal_all_mines(self):
for (x, y) in self.mine_locations:
btn = self.buttons[y][x]
if not self.flags[y][x]:
btn.config(text="💣", bg="red")
def check_win(self):
if self.game_over:
return
revealed_count = sum(row.count(True) for row in self.revealed)
total_safe = self.width * self.height - self.total_mines
if revealed_count == total_safe:
self.game_over = True
self.update_status("游戏胜利!")
messagebox.showinfo("恭喜", "你赢了!")
def update_status(self, status):
self.status_label.config(text=status)
class DifficultySelector(tk.Tk):
def __init__(self):
super().__init__()
self.title("扫雷 - 难度选择")
self.geometry("400x300")
self.resizable(False, False)
# 居中窗口
self.update_idletasks()
width = self.winfo_width()
height = self.winfo_height()
x = (self.winfo_screenwidth() // 2) - (width // 2)
y = (self.winfo_screenheight() // 2) - (height // 2)
self.geometry(f'+{x}+{y}')
# 标题
title_label = tk.Label(self, text="选择难度", font=("Arial", 18, "bold"))
title_label.pack(pady=20)
# 难度按钮框架
btn_frame = tk.Frame(self)
btn_frame.pack(pady=10)
# 初级
easy_btn = tk.Button(btn_frame, text="初级 (9x9, 10雷)", width=20, height=2,
command=lambda: self.start_game(9, 9, 10),
bg="#4CAF50", fg="white", font=("Arial", 12))
easy_btn.pack(pady=5)
# 中级
medium_btn = tk.Button(btn_frame, text="中级 (16x16, 40雷)", width=20, height=2,
command=lambda: self.start_game(16, 16, 40),
bg="#FF9800", fg="white", font=("Arial", 12))
medium_btn.pack(pady=5)
# 高级
hard_btn = tk.Button(btn_frame, text="高级 (30x16, 99雷)", width=20, height=2,
command=lambda: self.start_game(30, 16, 99),
bg="#F44336", fg="white", font=("Arial", 12))
hard_btn.pack(pady=5)
def start_game(self, width, height, mines):
self.destroy() # 关闭选择窗口
game_root = tk.Tk()
game_root.title("Python 扫雷")
game_root.resizable(False, False)
game = Minesweeper(game_root, width=width, height=height, mines=mines)
# 居中游戏窗口
game_root.update_idletasks()
w_width = game_root.winfo_width()
w_height = game_root.winfo_height()
x = (game_root.winfo_screenwidth() // 2) - (w_width // 2)
y = (game_root.winfo_screenheight() // 2) - (w_height // 2)
game_root.geometry(f'+{x}+{y}')
game_root.mainloop()
if __name__ == "__main__":
import random
selector = DifficultySelector()
selector.mainloop()