Tic Tac Toe(井字棋)是一种简单的两人对弈游戏,通常在3x3的网格上进行。确定游戏结束时间的算法主要涉及判断游戏是否已经结束,包括以下几种情况:
def check_winner(board):
# 检查横向
for row in board:
if row[0] == row[1] == row[2] and row[0] != ' ':
return row[0]
# 检查纵向
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] and board[0][col] != ' ':
return board[0][col]
# 检查对角线
if board[0][0] == board[1][1] == board[2][2] and board[0][0] != ' ':
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] and board[0][2] != ' ':
return board[0][2]
return None
def is_game_over(board):
winner = check_winner(board)
if winner:
return True, f"Player {winner} wins!"
if all(cell != ' ' for row in board for cell in row):
return True, "It's a draw!"
return False, ""
通过上述算法,可以有效地判断井字棋游戏的结束时间,并处理相关的胜利和平局情况。
领取专属 10元无门槛券
手把手带您无忧上云