我通过使用 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/