You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调试Pygame扫雷程序中3x3邻域地雷数统计的数组问题

代码存在3个核心逻辑错误:

  • 索引映射错误:你给bombs数组加了1单位的外围填充,因此num_bombs[y][x]对应的实际bombs数组位置应该是bombs[y+1][x+1],而非直接用bombs[y][x]访问,否则会把外围填充的0值区域纳入判断,完全错位
  • 邻域遍历范围错误:Python的range是左闭右开区间,range(y-1, y+1)只能取到2个值,要覆盖3x3邻域需要改为range(y-1, y+2)
  • 不必要的当前单元格判断:if bombs[y,x] == 0的判断会导致当前单元格如果是地雷就跳过统计,即使你不需要雷位显示数字,也不影响计数逻辑,反而额外增加错误概率

修正后可正常运行的代码:

import random
import numpy as np
num_bomb = 10
num_cell_x = 10
num_cell_y = 8
# 外围加1层填充,避免边界判断
bombs = np.zeros([int(num_cell_y+2),int(num_cell_x+2)],dtype = np.uint)
for i in range(num_bomb):
    bombs[random.randint(1,num_cell_y),random.randint(1,num_cell_x)] = 1
num_bombs = np.zeros([num_cell_y,num_cell_x],dtype = np.uint)

# 修正后的统计逻辑
for x in range(0,num_cell_x):
    for y in range(0,num_cell_y):
        # 对应bombs数组的实际坐标
        bomb_y = y + 1
        bomb_x = x + 1
        count = 0
        # 遍历3x3邻域
        for sy in range(bomb_y -1, bomb_y +2):
            for sx in range(bomb_x -1, bomb_x +2):
                if bombs[sy][sx] == 1:
                    count +=1
        num_bombs[y][x] = count

print(bombs)
print()
print(num_bombs)

可选优化方案

如果想简化代码,也可以直接用二维卷积实现邻域求和,不需要手写多层嵌套循环:

from scipy.signal import convolve2d
kernel = np.ones((3,3), dtype=np.uint8)
num_bombs = convolve2d(bombs, kernel, mode='valid')

内容的提问来源于stack exchange,提问作者Léo Lepage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:36:02