写一个扫雷的Python代码
时间: 2024-03-28 22:18:57 浏览: 86
以下是一个简单的扫雷游戏的 Python 代码,基于 tkinter 模块实现:
```python
import tkinter as tk
import random
class MineSweeper:
def __init__(self, master):
self.master = master
self.master.title("扫雷")
self.width = 10
self.height = 10
self.mines = 10
self.create_board()
self.create_mines()
self.create_buttons()
def create_board(self):
self.board = []
for i in range(self.height):
row = []
for j in range(self.width):
row.append(0)
self.board.append(row)
def create_mines(self):
count = 0
while count < self.mines:
x = random.randint(0, self.width - 1)
y = random.randint(0, self.height - 1)
if self.board[y][x] != -1:
self.board[y][x] = -1
count += 1
def create_buttons(self):
self.buttons = []
for i in range(self.height):
row = []
for j in range(self.width):
button = tk.Button(self.master, width=2, height=1, command=lambda x=i, y=j: self.click_button(x, y))
button.grid(row=i, column=j)
row.append(button)
self.buttons.append(row)
def click_button(self, x, y):
button = self.buttons[x][y]
if self.board[x][y] == -1:
button.config(text="*", bg="red")
self.show_mines()
else:
count = self.count_mines(x, y)
if count == 0:
button.config(text=" ")
button.config(state="disabled")
self.check_neighbors(x, y)
else:
button.config(text=count, state="disabled")
def count_mines(self, x, y):
count = 0
for i in range(max(0, x-1), min(x+2, self.height)):
for j in range(max(0, y-1), min(y+2, self.width)):
if self.board[i][j] == -1:
count += 1
return count
def check_neighbors(self, x, y):
for i in range(max(0, x-1), min(x+2, self.height)):
for j in range(max(0, y-1), min(y+2, self.width)):
if self.board[i][j] != -1 and self.buttons[i][j].cget("state") != "disabled":
self.click_button(i, j)
def show_mines(self):
for i in range(self.height):
for j in range(self.width):
if self.board[i][j] == -1:
self.buttons[i][j].config(text="*", state="disabled")
root = tk.Tk()
game = MineSweeper(root)
root.mainloop()
```
这段代码实现了一个简单的 10x10 的扫雷游戏,其中包括了随机生成地雷、点击格子、计算周围地雷数量等基本功能,还有一个红色的地雷标记。这只是一个基础版本,你可以根据需要对其进行修改和扩展。
阅读全文