我正在用 Python 制作一个 tic tac toe 游戏。我已经实现了胜利检查,但每次我在游戏中获得对角线、水平或垂直胜利时,它都不会做它应该做的事情(又名打印“你赢了!”并中断)。这是额外信息的代码(抱歉,有些行不在代码块中。我尝试修复它,但它不会改变。):
from numpy import array
board = [
[0,0,0],
[0,0,0],
[0,0,0]
]
turn = 1
while True:
print(board)
row = int(input('Row: '))
column = int(input('Column: '))
board[row,column] = turn
if turn == 1:
turn += 1
else:
turn -= 1
if (board[0,0] != 0 and board[1,1] != 0 and board[2,2] != 0) or (board[0,2] != 0 and board[1,1] != 0 and board[2,0]): #diagonals
if (board[0,0] != 0 and board[0,1] != 0 and board[0,2] != 0) or (board[1,0] != 0 and board[1,1] != 0 and board[1,2] != 0) or (board[2,0] != 0 and board[2,1] != 0 and board[2,2] != 0): #columns
if (board[0,0] != 0 and board[1,0] != 0 and board[2,0] != 0) or (board[0,1] != 0 and board[1,1] != 0 and board[2,1] != 0) or (board[0,2] != 0 and board[1,2] != 0 and board[2,2] != 0): #rows
print('\nYou Win!\n')
break
您的 if 表达式在逻辑上不必要地复杂,因此很容易出错。 Numpy 提供了一种更清晰的方法,如下例所示:
import numpy as np
board = np.array([
[0,0,1],
[1,1,0],
[1,0,1]
])
a = any(sum(board) == 3) # any of columns
b = any(sum(board.T) == 3) # any of rows
c = (np.trace(board) == 3) # right diagonal
d = (np.trace(np.rot90(board)) == 3) #left diagonal
if a or b or c or d:
print('Win!')
由于示例中的对角线而打印
Win!