首页 > 解决方案 > 为什么我的井字游戏有时过快宣布获胜?

问题描述

我正在尝试在 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”工作得很好,但之后一切都出错了,正如我刚刚解释的那样。

标签: python

解决方案


您的代码的问题在于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 已经为您提供了保障。

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


推荐阅读