插入错误消息而列表索引超出范围

时间:2017-08-05 21:11:05

标签: python python-3.x

当输入值不在电路板上时,我希望this was wrong try again!打印,但是不知何故,当我在电路板外面选择一个值时,代替打印的消息,代码会中断。

    def legalMove(self):
            if self.board[startX][startY] != False:


    def playerMove(self,tile): 
                if self.legalMove(tile, x, y) == False:
                    continue
                else:
                    break
            else:
                print('this was wrong try again!.')
        return [x, y]

错误

  

如果是self.board [startX] [startY]!=' '或不是self.isOnBoard(startX,startY):   IndexError:列表索引超出范围

1 个答案:

答案 0 :(得分:2)

你应该在条件中交换语句,这样你就不会出现这样的错误:

def legalMove(self,tile,isOnBoard,startX, startY):
    # swap the statements
    if not self.isOnBoard(startX, startY) or self.board[startX][startY] != ' ':
        print('this was wrong try again!')
        return False
    return True

虽然我建议您playerMove方法中进行打印,以便您可以重复使用legalMove方法,例如,如果您以后要构建AI播放器。

def isOnBoard(self, x, y):
    return 0 <= x < 8 and 0 <= y < 8


def legalMove(self, startX, startY): # remove arguments
    return self.isOnBoard(startX, startY) and self.board[startX][startY] != ' '


def playerMove(self,tile): 
    validMove = '0 1 2 3 4 5 6 7'.split()
    while True:
        move = input().lower()
        if len(move) == 2 and move[0] in validMove and move[1] in validMove:
            x = int(move[0])
            y = int(move[1])
            if not self.legalMove(x, y):
                print('this was wrong try again!')
                continue
            else:
                break
        else:
            print('this was wrong try again!.')
    return [x, y]

此外,Python允许将比较链接在一起,例如0 <= x < 8更优雅。

最后虽然我错了,但我认为有效的移动应该只有07(包括在内)。所以validMove = '0 1 2 3 4 5 6 7'.split()