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

标签 python

我通过使用 python 中的字典制作了一个简单的 Tic Tac Toe 游戏,来自 Automate the boring stuff with 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'  

最佳答案

条件应该与 or 相关联,而不是 and,因为您可以通过连续制作任何 3 个来赢得井字游戏。使用 连续的 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):

关于python - 为什么即使条件为真,这个循环也会中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300670/

相关文章:

python - __call__() 缺少 1 个必需的位置参数 : 'send' FastAPI on App Engine

python - 在python中查找文本文件中每个单词的频率

python - 尝试在 python 中多处理需要列表参数的函数

python - Python 中的一个令人困惑的案例

python - 如何在没有队列的情况下更改多处理中的类值?

python - 方法调用后更改变量值

javascript - 在JS中生成csv并使用ajax请求POST将其发送到flask

python - dataReceived() 方法在 python 扭曲框架中混淆行为

具有多个参数的 Python 多处理池映射

javascript - Flask - 让 JavaScript 和 Python 进行通信