做一个井字棋游戏,可以直接运行
- User
做一个井字棋游戏,可以直接运行
Assistant
好的,下面是一个简单的井字棋游戏,使用 Python 编写,可以直接运行。这个游戏允许两个玩家在终端上进行游戏。
def print_board(board): for row in board: print(" | ".join(row)) print("-" * 5) def check_winner(board, player): # 检查行、列和对角线是否有玩家获胜 for i in range(3): if all([s == player for s in board[i]]) or all([board[j][i] == player for j in range(3)]): return True if board[0][0] == board[1][1] == board[2][2] == player or board[0][2] == board[1][1] == board[2][0] == player: return True return False def is_board_full(board): for row in board: if " " in row: return False return True def tic_tac_toe(): board = [[" " for _ in range(3)] for _ in range(3)] current_player = "X" while True: print_board(board) print(f"玩家 {current_player} 的回合") try: row = int(input("输入行 (0, 1, 或 2): ")) col = int(input("输入列 (0, 1, 或 2): ")) except ValueError: print("无效输入,请输入数字。") continue if row not in [0, 1, 2] or col not in [0, 1, 2]: print("输入超出范围,请输入 0, 1, 或 2。") continue if board[row][col] != " ": print("该位置已被占用,请选择其他位置。") continue board[row][col] = current_player if check_winner(board, current_player): print_board(board) print(f"玩家 {current_player} 获胜!") break if is_board_full(board): print_board(board) print("平局!") break current_player = "O" if current_player == "X" else "X" if __name__ == "__main__": tic_tac_toe()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.