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

时间:2019-08-01 01:15:56

标签: python

我通过使用python中的字典来制作一个简单的Tic Tac Toe游戏,该字典来自python自动化无聊的东西。当条件匹配时,while循环应该中断。但它一直在继续。

我尝试用“或”替换“和”运算符,并且第一次运行时循环中断。它出什么问题了?为什么即使条件满足,循环也不会中断?


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'  

2 个答案:

答案 0 :(得分:4)

这些条件应该与or而不是and关联,因为您可以连续3个赢得井字游戏。对于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):

答案 1 :(得分:0)

您应该尝试使用“或”条件,因为每个评估结果都必须是一个断点,而不是所有评估结果都是对还是错。

并且代码对每个键使用相同的''值初始化了'theBoards'变量,因此当您尝试使用'or'条件时,非常适合在第一次运行时打破循环。

尝试“或”条件而不是“与”,并且不要在第一回合检查获胜者。