我正在用python编写一个扫雷游戏。我在python中使用countAdjacentMines函数时遇到问题。我试图在2d列表中计算给定单元格周围的地雷数量,如下所示:
L = [
['','',''],
['x','',''],
['x','','']
]
当我尝试运行第1行第2列的代码时,我应该得到1,因为在第1行第2列周围的3x3中只有1个我的代码,但我的函数返回2。当python2d列表得到像L[-1][1]这样的值时,-1只是不计算任何值,而不是len(lis)-1位置,我该如何处理这个事实呢
这是我的密码:
def countAdjacentMines(lis,row,col):
total = 0
try:
if lis[row-1][col-1] == 'x':
total+=1
except IndexError:
pass
try:
if lis[row-1][col] == 'x':
total+=1
except:
pass
try:
if lis[row-1][col+1] == 'x':
total+=1
except:
pass
try:
if lis[row][col-1] == 'x':
total+=1
except:
pass
try:
if lis[row][col+1] == 'x':
total+=1
except:
pass
try:
if lis[row+1][col-1] == 'x':
total+=1
except:
pass
try:
if lis[row+1][col] == 'x':
total+=1
except:
pass
try:
if lis[row+1][col+1] == 'x':
total+=1
except:
pass
return total
L = [
['','',''],
['x','',''],
['x','','']
]
print(countAdjacentMines(L,0,1))
我不是100%确定我理解了这个问题,但是如果我没有弄错的话,您希望python不要因为列表中的索引-1而转到最后一行吗
如果是这样的话,试着使用像这样的max函数
编辑: 我以前的解决方案是假的,并且计算了你想忽略的细胞数,所以我把它去掉了。相反,您可以做的是在适当的情况下向
只要你有一个方阵,这就行,否则,你可以使用len(lis[row])或类似的东西
此外,我建议找到另一种方法来处理错误,而不是尝试传递
第四次的魅力
最后一次编辑:如果你对邻接挖掘(L,2,0)进行计数,它会输出1,因为没有理由像现在这样对当前单元格进行计数
相关问题 更多 >
编程相关推荐