gpt4 book ai didi

python - 为什么我的井字游戏有时过快宣布获胜?

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:53 25 4
gpt4 key购买 nike

我正在尝试用 Python 制作井字棋游戏,但我无法让它检测到胜利。这是本书的一部分:使用 python 自动化无聊的东西。

下面是代码和我的尝试:

theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}


def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])

turn = 'X'

for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn

#X wins
if theBoard['top-L' and 'top-M' and 'top-R'] == 'X':
print('X Won!')
break

if theBoard['mid-L' and 'mid-M' and 'mid-R'] == 'X':
print('X Won!')
break

if theBoard['low-L' and 'low-M' and 'low-R'] == 'X':
print('X Won!')
break

if theBoard['top-L' and 'mid-L' and 'low-L'] == 'X':
print('X Won!')
break

if theBoard['top-M' and 'mid-M' and 'low-M'] == 'X':
print('X Won!')
break

if theBoard['top-R' and 'mid-R' and 'low-R'] == 'X':
print('X Won!')
break

if theBoard['top-L' and 'mid-M' and 'low-R'] == 'X':
print('X Won!')
break

if theBoard['top-R' and 'mid-M' and 'low-L'] == 'X':
print('X Won!')
break

#O wins
if theBoard['top-L' and 'top-M' and 'top-R'] == 'O':
print('O Won!')
break

if theBoard['mid-L' and 'mid-M' and 'mid-R'] == 'O':
print('O Won!')
break

if theBoard['low-L' and 'low-M' and 'low-R'] == 'O':
print('O Won!')
break

if theBoard['top-L' and 'mid-L' and 'low-L'] == 'O':
print('O Won!')
break

if theBoard['top-M' and 'mid-M' and 'low-M'] == 'O':
print('O Won!')
break

if theBoard['top-R' and 'mid-R' and 'low-R'] == 'O':
print('O Won!')
break

if theBoard['top-L' and 'mid-M' and 'low-R'] == 'O':
print('O Won!')
break

if theBoard['top-R' and 'mid-M' and 'low-L'] == 'O':
print('O Won!')
break

if turn == 'X':
turn = 'O'

else:
turn = 'X'

printBoard(theBoard)

发生的事情是:当我键入例如:mid-R 时,它会立即说 X 赢了。前四个“Xwins”工作得很好,但之后一切都出错了,正如我刚才解释的那样。

最佳答案

你的代码的问题是 if theBoard['mid-L' and 'mid-M' and 'mid-R'] == 'X': 没有按照你的想法去做它在做。它不检查所有三个位置是否都是“X”。它只是始终返回最正确的值。参见 Boolean Operation来自文档:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

由于非空字符串的 bool 值始终为 True,因此 'mid-L' and 'mid-M' and 'mid-R' 将始终返回'mid-R',它为您提供 theBoard['mid-R'] == 'X' 的条件并将产生 True ,给你 X 获胜的条件。

至于补救措施,我相信@Endyd 已经为您解决了。

最理想的情况是不要对所有获胜条件进行硬编码,但这需要重构您的代码……也许当您有更好的理解时,我建议您回来尝试更动态的解决方案。至于现在,祝你学习愉快!

关于python - 为什么我的井字游戏有时过快宣布获胜?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54093749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com