帮我用python写一个扫雷
时间: 2023-06-16 08:02:24 浏览: 85
好的,以下是一个简单的扫雷游戏的Python代码,代码中使用了Tkinter模块进行界面设计:
```python
import tkinter as tk
import random
class Minesweeper:
def __init__(self, master, width, height, bombs):
self.master = master
self.width = width
self.height = height
self.bombs = bombs
self.grid = [[0 for _ in range(height)] for _ in range(width)]
self.buttons = [[None for _ in range(height)] for _ in range(width)]
self.create_widgets()
def create_widgets(self):
# 创建游戏界面
self.frame = tk.Frame(self.master)
self.frame.pack()
# 创建按钮
for i in range(self.width):
for j in range(self.height):
button = tk.Button(self.frame, text='', width=2, height=1)
button.grid(row=i, column=j)
button.bind('<Button-1>', lambda event, i=i, j=j: self.on_left_click(i, j))
button.bind('<Button-3>', lambda event, i=i, j=j: self.on_right_click(i, j))
self.buttons[i][j] = button
# 放置地雷
bombs = random.sample([(i, j) for i in range(self.width) for j in range(self.height)], self.bombs)
for i, j in bombs:
self.grid[i][j] = -1
# 计算数字
for i in range(self.width):
for j in range(self.height):
if self.grid[i][j] == -1:
continue
count = 0
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]:
x, y = i + dx, j + dy
if x < 0 or x >= self.width or y < 0 or y >= self.height:
continue
if self.grid[x][y] == -1:
count += 1
self.grid[i][j] = count
def on_left_click(self, i, j):
self.buttons[i][j].config(state=tk.DISABLED)
if self.grid[i][j] == -1:
self.buttons[i][j].config(text='*', bg='red')
self.show_bombs()
elif self.grid[i][j] == 0:
self.show_empty(i, j)
else:
self.buttons[i][j].config(text=str(self.grid[i][j]))
def on_right_click(self, i, j):
if self.buttons[i][j].cget('text') == '':
self.buttons[i][j].config(text='F')
elif self.buttons[i][j].cget('text') == 'F':
self.buttons[i][j].config(text='?')
else:
self.buttons[i][j].config(text='')
def show_empty(self, i, j):
self.buttons[i][j].config(text='')
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]:
x, y = i + dx, j + dy
if x < 0 or x >= self.width or y < 0 or y >= self.height:
continue
if self.buttons[x][y].cget('state') == tk.DISABLED:
continue
if self.grid[x][y] == 0:
self.show_empty(x, y)
else:
self.buttons[x][y].config(text=str(self.grid[x][y]))
self.buttons[x][y].config(state=tk.DISABLED)
def show_bombs(self):
for i in range(self.width):
for j in range(self.height):
if self.grid[i][j] == -1:
self.buttons[i][j].config(text='*', bg='red')
elif self.buttons[i][j].cget('text') == 'F':
self.buttons[i][j].config(bg='gray')
else:
self.buttons[i][j].config(text=str(self.grid[i][j]), state=tk.DISABLED)
if __name__ == '__main__':
root = tk.Tk()
root.title('Minesweeper')
app = Minesweeper(root, width=10, height=10, bombs=10)
root.mainloop()
```
运行代码后,将会弹出一个10x10的扫雷游戏界面,其中10个地雷随机放置在游戏区域内。玩家可以使用鼠标左键点击方格来探查是否有地雷,右键点击方格来标记地雷。当玩家点击到地雷时,游戏结束,所有地雷将被标记并显示在游戏界面上。
阅读全文