我用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'
您应该尝试使用“or”条件,因为每个单独的求值结果都需要是一个断点,而不是所有这些求值结果都是相同的true或false。你知道吗
并且代码用相同的“”值初始化了每个键的“theBoards”变量,因此当您尝试使用“or”条件时,非常适合在第一次运行时中断循环。你知道吗
尝试“或”条件,而不是“和”,不要在第一个回合检查赢家。你知道吗
这些条件应该与
or
相联系,而不是与and
相联系,因为您可以通过在一行中生成任意3个来赢得tic tac toe。与and
一起,一行中的每个3必须相同。你知道吗它在第一个回合后结束的原因是,您没有检查单元格是否已实际填充。所以一个空的行、列或对角线将被认为是匹配的,因为所有的空格都是相等的。你知道吗
与其只是检查它们是否相等,不如检查它们是否等于
turn
。你知道吗相关问题 更多 >
编程相关推荐