我正在尝试制作一个tic-tac-toe游戏。不确定约定是什么,但是我使用1表示X,4表示O表示,因为在列,行或对角线上的总和3表示X的胜利,而12的总和表示O的胜利,并且在非获胜场景中无法达到该组合。同样,如果所有行,列和对角线等于1,1,4或1,4,4(即6或9),那么游戏就是平局。
除了胜利条件外,游戏的其余部分工作正常:
#if a row, column, or diagonal sums to 3, you win, if 12, they win
#a number 1 = X, a number 4 = O
if ( row1 == 3
or row2 == 3
or row3 == 3
or col1 == 3
or col2 == 3
or col3 == 3
or dia1 == 3
or dia2 == 3
):
endCondition = True
whoWon = "You won!"
if ( row1 == 12
or row2 == 12
or row3 == 12
or col1 == 12
or col2 == 12
or col3 == 12
or dia1 == 12
or dia2 == 12
):
endCondition = True
whoWon = "You lost! Computer wins."
#if that was the last spot, then it is a draw
#a losing row is either 1,1,4 or 1,4,4 which equal six and 9 respectively
if (row1 and row2 and row3 and col1 and col2 and col3 and dia1 and dia2) == (6 or 9):
endCondition = True
whoWon = "No one. It was a draw."
有任何帮助吗?我知道这是一个简单的错误。
答案 0 :(得分:2)
if (row1 and row2 and row3 and col1 and col2 and col3 and dia1 and dia2) == (6 or 9):
这不是针对多个其他值检查多个值的正确语法。 (6 or 9)
将始终评估为9
。如果任何值为0,(row1 and row2 and ... and dia2)
将评估为0;如果没有值为0,则为dia2
的值。因此,如果电路板已满且dia2
不是9,则条件将错误地评估为False。
相反,请尝试:
if all(x == 6 or x == 9 for x in (row1, row2, row3, col1, col2, col3, dia1, dia2)):