写一个井字棋游戏,增加人机对战和比分系统
- User
写一个井字棋游戏,增加人机对战和比分系统
Assistant
井字棋游戏
我们将实现一个标准的井字棋游戏,包括人机对战和比分系统。游戏中,玩家可以选择是否使用人机或人人对战。
游戏规则
- 井字棋游戏是一种简单的博弈游戏,玩家可以在 3x3 的网格中下棋。
- 每个玩家轮流下棋,用"X"或"O"标记棋子。
- 如果玩家获得三连珠,则获胜。
- 如果网格满了而没有玩家获胜,则为平局。
代码实现
井字棋游戏类
pythonimport random class TicTacToe: def __init__(self): self.board = [' ' for _ in range(9)] self.current_player = 'X' def print_board(self): print(' {} | {} | {}'.format(self.board[0], self.board[1], self.board[2])) print('-----------') print(' {} | {} | {}'.format(self.board[3], self.board[4], self.board[5])) print('-----------') print(' {} | {} | {}'.format(self.board[6], self.board[7], self.board[8])) def is_valid(self, move): try: int(move) return 0 <= int(move) <= 8 except ValueError: return False def is_winner(self): win_conditions = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)] for condition in win_conditions: if self.board[condition[0]] == self.board[condition[1]] == self.board[condition[2]] != ' ': return True return False def is_draw(self): return ' ' not in self.board def play(self): while True: self.print_board() move = input("Player {}, enter your move (1-9): ".format(self.current_player)) if self.is_valid(move): if self.board[int(move) - 1] == ' ': self.board[int(move) - 1] = self.current_player if self.is_winner(): self.print_board() print("Player {} wins! Congratulations!".format(self.current_player)) break elif self.is_draw(): self.print_board() print("It's a draw!") break self.current_player = 'O' if self.current_player == 'X' else 'X' else: print("Invalid move, try again.") else: print("Invalid move, please enter a number between 1 and 9.")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.