python - 为什么我的井字游戏有时过快宣布获胜?
问题描述
我正在尝试在 python 中制作井字游戏,但我无法让它检测到胜利。这是本书的一部分:Automating the Boring stuff using 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”。它只是在任何时候都返回最正确的价值。请参阅文档中的布尔运算:
表达式
x and y
首先计算x
; 如果x
为假,则返回其值;否则,y
评估并返回结果值。表达式
x or y
首先计算x
; 如果x
为真,则返回其值;否则,y
评估并返回结果值。
由于非空字符串的布尔值 always True
,'mid-L' and 'mid-M' and 'mid-R'
will always return 'mid-R'
,这给了你的条件,theBoard['mid-R'] == 'X'
将 yield True
,给你 X 获胜的条件。
至于补救措施,我相信@Endyd 已经为您提供了保障。
最理想的情况不是对所有获胜条件进行硬编码,但它需要重组你的代码......也许当你有更好的理解时,我建议你回来尝试一个更动态的解决方案。至于现在,快乐学习!
推荐阅读
- haskell - 带有列表的 Show 的新实例声明
- python - 在类中使用函数时出错。我无法将函数分配给新的类方法
- c# - 将文本文件转换为列表
(C#) - javascript - Javascript 小费计算器
- sql - 具有相同值和条件的属性的 SQL SUM
- javascript - 如何在 React 中使用 Eonasdan Datetimepicker
- reactjs - 在生产模式下使用 Router 的 basename 属性时,路由无效
- c - arr[] 作为参数是 C 中的指针吗?
- azure - 如何删除面部 api 中不再需要的人员组名?
- java - 如何在项目的 makefile 中指定任何类的路径?