TypeError:列表索引必须是整数或切片,而不是None在Connect 4游戏上为Type

问题描述

我正在学习python,并正在训练Im制作connect4游戏。 当我试图清除“玩家”的所有错误输入时,我只想询问“列”的输入,它会自动添加到最后一个可用的“行”上,很遗憾,我还没有找到一种方法它。

这是我到目前为止所拥有的:

编辑:现在粘贴所有代码

for (int i : digits) {
    cout << i << endl;    
}

解决方法

作为以后的参考,如果您发布的代码可运行并演示与您的问题相关的问题或情况,那么您的StackOverflow问题会更好。我从您的代码开始,并将其添加到main()的末尾以使其能够执行某些操作:

result = choose_location(board,'0',board_list)
print(result)
for r in board:
    print(r)

然后我运行它并看到此错误。此堆栈跟踪将很好地包含在您的问题中:

Traceback (most recent call last):
  File "x.py",line 51,in <module>
    main()
  File "x.py",line 19,in main
    result = choose_location(board,board_list)
  File "x.py",line 33,in choose_location
    while board[row][column] is None:
TypeError: list indices must be integers or slices,not NoneType

您可以通过设置不同的索引来解决索引问题。将行初始化为零,而不是None。并检查最大可能行索引。

row = 0
n_rows = len(board)
while row < n_rows and board[row][column] is None:
    row += 1

顺便说一句,我认为您可以摆脱board_list。似乎没有必要。您知道法律列必须在range(1,len(board[0] + 1))中。

,

使用此功能获取给定列的最低位置

# returns [row,col] of players piece,returns None if column is filled up
def get_row(col,board):
    if board[0][col] != None:# column is filled up
        return None
    for row in range(7):# find lowest unfilled position
        if (board[row][col] != None) or (row == 6):# place is filled or at bottom of board
            return [row-1,col]