我正在编写一个用于制作井字游戏的 python 代码。我需要编写一个函数,它接受三个输入,板、x 和 y。棋盘是棋盘的当前显示,然后 x 和 y 的值是 0、1 或 2。游戏设置为向用户询问坐标。
def CheckVictory(board, x, y):
#check if previous move was on vertical line and caused a win
if board[0][y] == ('X') and board[1][y] == ('X') and board [2][y] == ('X'):
return True
if board[0][y] == ('O') and board[1][y] == ('O') and board [2][y] == ('O'):
return True
#check if previous move was on horizontal line and caused a win
if board[x][0] == ('X') and board[x][1] == ('X') and board [x][2] == ('X'):
return True
if board[x][0] == ('O') and board[x][1] == ('O') and board [x][2] == ('O'):
return True
#check if previous move was on the main diagonal and caused a win
if board[0][0] == ('X') and board[1][1] == ('X') and board [2][2] == ('X'):
return True
if board[0][0] == ('O') and board[1][1] == ('O') and board [2][2] == ('O'):
return True
#check if previous move was on the secondary diagonal and caused a win
if board[0][2] == ('X') and board[1][1] == ('X') and board [2][0] == ('X'):
return True
if board[0][2] == ('O') and board[1][1] == ('O') and board [2][0] == ('O'):
return True
return False
#end of CheckVictory function
该函数在游戏循环中被调用,如下所示
p_x, p_y = playerTurn(board) #let player take turn
displayBoard(board) #show board after move has been made
if CheckVictory(board, p_x, p_y): #see if user has won
print("CONGRATULATIONS, you win!")
newGame(board) #game over start new one
continue
电脑转也是类似的
我觉得有更好的方法来编写这个函数。我觉得我应该更多地使用 x 和 y 或者有更好的方法来检查而不是写下所有的可能性。那么有什么更好的方法来写这个呢?使其简短明了。