【问题标题】:Why does this loop break even if the condition is true?为什么即使条件为真,这个循环也会中断?
【发布时间】:2019-08-01 01:15:56
【问题描述】:

我通过使用 Python 中的字典来制作一个简单的井字游戏,来自用 Python 自动化无聊的东西。当条件匹配时,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'  

【问题讨论】:

  • 你应该使用or。您不希望所有这些条件都是True。但是,大多数条件将在第一步之后满足,因为除了一个位置之外,所有位置都是' '

标签: python


【解决方案1】:

条件应该与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):

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2020-09-10
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多