gpt-4-0125-preview· OpenAI
Arena Human Preference 55K
write a tic tac toe game in python
- User
write a tic tac toe game in python
- Assistant
Certainly! Below is a simple implementation of a Tic Tac Toe game in Python. This code will allow two players to play the game in the console.
def print_board(board): for row in board: print(" | ".join(row)) print("-" * 9) def check_win(board, player): win_conditions = [ [board[0][0], board[0][1], board[0][2]], [board[1][0], board[1][1], board[1][2]], [board[2][0], board[2][1], board[2][2]], [board[0][0], board[1][0], board[2][0]], [board[0][1], board[1][1], board[2][1]], [board[0][2], board[1][2], board[2][2]], [board[0][0], board[1][1], board[2][2]], [board[2][0], board[1][1], board[0][2]] ] return [player, player, player] in win_conditions def get_move(player): while True: try: move = int(input(f"Player {player}, enter your move (1-9): ")) - 1 if move >= 0 and move < 9: return divmod(move, 3) else: print("Invalid input. Please enter a number between 1 and 9.") except ValueError: print("Invalid input. Please enter a number.") def play_game(): board = [[" " for _ in range(3)] for _ in range(3)] players = ["X", "O"] for turn in range(9): current_player = players[turn % 2] print_board(board) row, col = get_move(current_player) if board[row][col] == " ": board[row][col] = current_player else: print("This space is already taken. Please choose another space.") continue if check_win(board, current_player): print_board(board) print(f"Player {current_player} wins!") return print_board(board) print("It's a tie!") if __name__ == "__main__": play_game()This game:
- Uses a 3x3 matrix to represent the board.
- Alternates turns between two players, X and O.
- Checks for a win or a tie after each move.
- Allows players to input their move as a number between 1 and 9, corresponding to positions on the board as follows:
1 | 2 | 3 --------- 4 | 5 | 6 --------- 7 | 8 | 9- Validates the input for the correct format and availability of the chosen spot.
- Ends when a player wins or all spaces are filled, resulting in a tie.
To play, simply run this script in a Python environment, and follow the on-screen prompts.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.