为什么即使条件为真,循环也会中断?

2024-10-02 20:32:06 发布

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

我用python中的字典制作了一个简单的Tic-Tac-Toe游戏。当条件匹配时,while循环应该中断。但它还在继续。你知道吗

我尝试用“or”替换“and”操作符,循环在第一次运行时中断。怎么了?如果条件满足,为什么循环不平衡?你知道吗


theBoards = {'A' : ' ', 'B': ' ', 'C' : ' ',
            'D' : ' ', 'E' : ' ', 'F' : ' ',
            'G' : ' ', 'H': ' ', 'I': ' '}


def drawBoard(theBoard):
    print(theBoard['A'] + '|' + theBoard['B'] + '|' + theBoard['C'])
    print('-+-+-')
    print(theBoard['D'] + '|' + theBoard['E'] + '|' + theBoard['F'])
    print('-+-+-')
    print(theBoard['G'] + '|' + theBoard['H'] + '|' + theBoard['I'])

drawBoard(theBoards)    
turn = 'X'
while True:
    move = input("Where do you want your " + turn + ': ')
    theBoards[move] = turn
    drawBoard(theBoards)

    if(     theBoards['A'] == theBoards['B'] == theBoards['C']
        and theBoards['D'] == theBoards['E'] == theBoards['F']
        and theBoards['G'] == theBoards['H'] == theBoards['I']
        and theBoards['A'] == theBoards['D'] == theBoards['G']
        and theBoards['B'] == theBoards['E'] == theBoards['H']
        and theBoards['C'] == theBoards['F'] == theBoards['I']
        and theBoards['A'] == theBoards['E'] == theBoards['I']
        and theBoards['C'] == theBoards['E'] == theBoards['G']):
        print("Winner is " + turn)
        break
    if turn  == 'X':
        turn = 'O'
    else:
        turn = 'X'  

Tags: and游戏moveif字典tic条件turn
2条回答

您应该尝试使用“or”条件,因为每个单独的求值结果都需要是一个断点,而不是所有这些求值结果都是相同的true或false。你知道吗

并且代码用相同的“”值初始化了每个键的“theBoards”变量,因此当您尝试使用“or”条件时,非常适合在第一次运行时中断循环。你知道吗

尝试“或”条件,而不是“和”,不要在第一个回合检查赢家。你知道吗

这些条件应该与or相联系,而不是与and相联系,因为您可以通过在一行中生成任意3个来赢得tic tac toe。与and一起,一行中的每个3必须相同。你知道吗

它在第一个回合后结束的原因是,您没有检查单元格是否已实际填充。所以一个空的行、列或对角线将被认为是匹配的,因为所有的空格都是相等的。你知道吗

与其只是检查它们是否相等,不如检查它们是否等于turn。你知道吗

    if(    theBoards['A'] == theBoards['B'] == theBoards['C'] == turn
        or theBoards['D'] == theBoards['E'] == theBoards['F'] == turn
        or theBoards['G'] == theBoards['H'] == theBoards['I'] == turn
        or theBoards['A'] == theBoards['D'] == theBoards['G'] == turn
        or theBoards['B'] == theBoards['E'] == theBoards['H'] == turn
        or theBoards['C'] == theBoards['F'] == theBoards['I'] == turn
        or theBoards['A'] == theBoards['E'] == theBoards['I'] == turn
        or theBoards['C'] == theBoards['E'] == theBoards['G'] == turn):

相关问题 更多 >