python扫雷游戏代码简易
时间: 2024-01-06 07:05:28 浏览: 105
python编写的扫雷小游戏,包括源文件和打包好的可执行exe文件
以下是一个简易的Python扫雷游戏代码示例:
```python
import tkinter as tk
import random
# 游戏设置
ROWS = 10
COLS = 10
MINES = 10
# 创建游戏窗口
window = tk.Tk()
window.title("扫雷游戏")
# 创建按钮格子
buttons = []
for row in range(ROWS):
button_row = []
for col in range(COLS):
button = tk.Button(window, width=2, relief="raised")
button.grid(row=row, column=col)
button_row.append(button)
buttons.append(button_row)
# 随机布置地雷
mines = []
while len(mines) < MINES:
mine = (random.randint(0, ROWS-1), random.randint(0, COLS-1))
if mine not in mines:
mines.append(mine)
# 点击按钮的处理函数
def button_click(row, col):
if (row, col) in mines:
buttons[row][col].config(text="X", bg="red")
else:
count = 0
for r in range(max(0, row-1), min(row+2, ROWS)):
for c in range(max(0, col-1), min(col+2, COLS)):
if (r, c) in mines:
count += 1
buttons[row][col].config(text=count, bg="light gray")
# 绑定按钮点击事件
for row in range(ROWS):
for col in range(COLS):
buttons[row][col].config(command=lambda r=row, c=col: button_click(r, c))
# 运行游戏
window.mainloop()
```
阅读全文