这是一个 Python 扫雷游戏的示例代码:
```
导入需要的库
import random import tkinter as tk
定义常量
SIZE = 400 GRID_LEN = 4 GRID_PADDING = 10
创建游戏界面
root = tk.Tk() root.title('扫雷游戏')
创建画布
canvas = tk.Canvas(root, width=SIZE, height=SIZE, highlightthickness=0) canvas.pack()
生成地图
def generate_map(): return [[random.randint(0, 1) for _ in range(GRID_LEN)] for _ in range(GRID_LEN)]
获取某个方块周围的雷数
def get_adjacent_mines(mine_map, row, col): count = 0 for i in range(row-1, row+2): for j in range(col-1, col+2): if i >= 0 and i < GRID_LEN and j >= 0 and j < GRID_LEN: if mine_map[i][j] == 1: count += 1 return count
绘制游戏界面
def draw_grid(): for i in range(GRID_LEN): for j in range(GRID_LEN): top_left_x = j * SIZE/GRID_LEN top_left_y = i * SIZE/GRID_LEN bottom_right_x = (j+1) * SIZE/GRID_LEN bottom_right_y = (i+1) * SIZE/GRID_LEN canvas.create_rectangle(top_left_x, top_left_y, bottom_right_x, bottom_right_y, fill="white", tags="block")
点击事件处理函数
def on_block_click(event): # 计算点击的方块的行列坐标 row = int(event.y / (SIZE/GRID_LEN)) col = int(event.x / (SIZE/GRID_LEN)) # 如果周围有雷,显示周围雷数 if mine_map[row][col] == 1: canvas.create_text(event.x, event.y, text=str(get_adjacent_mines(mine_map, row, col)), font=("Arial", 20), tags="text") else: # 如果周围没有雷