Python扫雷机计数相邻地雷错误

2024-09-27 00:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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))

Tags: 函数代码游戏列表数量ifcolpass
1条回答
网友
1楼 · 发布于 2024-09-27 00:18:23

我不是100%确定我理解了这个问题,但是如果我没有弄错的话,您希望python不要因为列表中的索引-1而转到最后一行吗

如果是这样的话,试着使用像这样的max函数

L[max(0,row-1)][1]

编辑: 我以前的解决方案是假的,并且计算了你想忽略的细胞数,所以我把它去掉了。相反,您可以做的是在适当的情况下向

def countAdjacentMines(lis,row,col):
    total = 0        
    if ((row > 0 and col > 0) and lis[row-1][col-1] == 'x'):
        total+=1               
    if  (row > 0 and lis[row-1][col] == 'x'):
        print("here")
        total+=1
    if ((row > 0 and col < len(lis)-1) and lis[row-1][col+1] == 'x'):
        total+=1
    if (col > 0 and lis[row][col-1] == 'x'):
        total+=1 
    if (col < len(lis)-1 and lis[row][col+1] == 'x'):
        total+=1
    if ((row < len(lis)-1 and col > 0) and lis[row+1][col-1] == 'x'):
        total+=1
    if (row < len(lis)-1 and lis[row+1][col] == 'x'):
        total+=1
    if ((row < len(lis)-1 and col < len(lis)-1) and lis[row+1][col+1] == 'x'):
        total+=1
    return total

L = [
['','',''],
['x','',''],
['x','','']
]

只要你有一个方阵,这就行,否则,你可以使用len(lis[row])或类似的东西

此外,我建议找到另一种方法来处理错误,而不是尝试传递

第四次的魅力

最后一次编辑:如果你对邻接挖掘(L,2,0)进行计数,它会输出1,因为没有理由像现在这样对当前单元格进行计数

相关问题 更多 >

    热门问题