用python生成一个扫雷游戏
时间: 2023-12-29 18:18:36 浏览: 77
生成扫雷游戏可以使用Python的图形界面库(例如PyQt或Tkinter)和事件驱动编程。这里是一个简单的示例代码,它使用Tkinter作为图形界面库:
```
import tkinter as tk
import random
class MineSweeper:
def __init__(self, master):
self.master = master
self.grid = []
self.buttons = []
for i in range(9):
row = []
button_row = []
for j in range(9):
row.append(0)
b = tk.Button(self.master, text=' ', width=2, height=1, command=lambda i=i, j=j: self.click(i, j))
b.grid(row=i, column=j)
button_row.append(b)
self.grid.append(row)
self.buttons.append(button_row)
self.plant_mines()
def plant_mines(self):
mines = 10
while mines > 0:
i = random.randint(0, 8)
j = random.randint(0, 8)
if self.grid[i][j] == 0:
self.grid[i][j] = -1
mines -= 1
def click(self, i, j):
if self.grid[i][j] == -1:
self.master.quit()
else:
count = 0
for x in range(max(0, i-1), min(9, i+2)):
for y in range(max(0, j-1), min(9, j+2)):
if self.grid[x][y] == -1:
count += 1
if count > 0:
self.buttons[i][j].config(text=str(count))
else:
self.buttons[i][j].config(text=' ', state='disabled')
for x in range(max(0, i-1), min(9, i+2)):
for y in range(max(0, j-1), min(9, j+2)):
if self.grid[x][y] == 0:
self.click(x, y)
root = tk.Tk()
app = MineSweeper(root)
root.mainloop()
```
这个代码可以生成一个9x9的扫雷游戏,游戏中随机分布着10个地雷。玩家通过点击按钮来探测地图。如果点击到地雷
阅读全文