用python运行扫雷
时间: 2024-04-26 07:21:56 浏览: 54
你可以使用Python编写一个扫雷游戏,其中包括一个GUI(图形用户界面)和游戏逻辑。以下是一个简单的示例:
```python
import tkinter as tk
import random
# 游戏设置
NUM_ROWS = 10
NUM_COLS = 10
NUM_MINES = 10
# 创建窗口
window = tk.Tk()
window.title('Minesweeper')
# 创建游戏面板
board = tk.Frame(window)
board.pack()
# 创建方块
squares = []
for row in range(NUM_ROWS):
for col in range(NUM_COLS):
square = tk.Button(board, width=2, height=1)
square.grid(row=row, column=col)
squares.append(square)
# 添加地雷
mines = random.sample(range(NUM_ROWS * NUM_COLS), NUM_MINES)
for mine in mines:
squares[mine].mine = True
# 点击方块时的动作
def click_square(event):
square = event.widget
if square.mine:
square.config(text='*', bg='red')
for s in squares:
if s.mine:
s.config(text='*', bg='red')
tk.messagebox.showerror('Game Over', 'You clicked on a mine!')
window.destroy()
else:
square.config(bg='gray')
row, col = get_square_position(square)
num_mines = count_adjacent_mines(row, col)
if num_mines > 0:
square.config(text=str(num_mines))
else:
reveal_adjacent_squares(row, col)
# 获取方块的位置
def get_square_position(square):
for i in range(len(squares)):
if squares[i] == square:
row = i // NUM_COLS
col = i % NUM_COLS
return row, col
# 计算相邻的地雷数量
def count_adjacent_mines(row, col):
count = 0
for r in range(max(row - 1, 0), min(row + 2, NUM_ROWS)):
for c in range(max(col - 1, 0), min(col + 2, NUM_COLS)):
if squares[r * NUM_COLS + c].mine:
count += 1
return count
# 显示相邻的方块
def reveal_adjacent_squares(row, col):
for r in range(max(row - 1, 0), min(row + 2, NUM_ROWS)):
for c in range(max(col - 1, 0), min(col + 2, NUM_COLS)):
if not squares[r * NUM_COLS + c].mine and squares[r * NUM_COLS + c]['bg'] == '':
num_mines = count_adjacent_mines(r, c)
if num_mines > 0:
squares[r * NUM_COLS + c].config(text=str(num_mines), bg='gray')
else:
squares[r * NUM_COLS + c].config(bg='gray')
reveal_adjacent_squares(r, c)
# 绑定点击事件
for square in squares:
square.bind('<Button-1>', click_square)
# 运行游戏
window.mainloop()
```
这个示例代码创建了一个10x10的扫雷游戏,其中有10个地雷。玩家可以点击方块来揭示它们,并尝试避免揭示地雷。如果玩家揭示到地雷,则游戏结束。
请注意,这只是一个简单的示例,实际上你可以根据自己的需求来修改和扩展这个代码。
阅读全文