gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
write a code for a simple tic tac toe game in python
- User
write a code for a simple tic tac toe game in python
- Assistant
Sure! Here's a simple implementation of a tic-tac-toe game in Python:
# Tic Tac Toe # Create the board board = [' ' for _ in range(9)] # Function to display the board def display_board(): print('---------') print('|', board[0], '|', board[1], '|', board[2], '|') print('---------') print('|', board[3], '|', board[4], '|', board[5], '|') print('---------') print('|', board[6], '|', board[7], '|', board[8], '|') print('---------') # Function to check for a win def check_win(): # Check rows for i in range(0, 9, 3): if board[i] == board[i+1] == board[i+2] != ' ': return True # Check columns for i in range(3): if board[i] == board[i+3] == board[i+6] != ' ': return True # Check diagonals if board[0] == board[4] == board[8] != ' ': return True if board[2] == board[4] == board[6] != ' ': return True return False # Function to play the game def play_game(): current_player = 'X' game_over = False # Loop until the game is over while not game_over: display_board() position = int(input(f"Player '{current_player}', choose a position (1-9): ")) - 1 # Check if the chosen position is valid if position < 0 or position > 8 or board[position] != ' ': print('Invalid position! Try again.') continue # Place the player's symbol on the board board[position] = current_player # Check for a win if check_win(): display_board() print(f"Player '{current_player}' wins!") game_over = True break # Check for a tie if ' ' not in board: display_board() print("It's a tie!") game_over = True break # Switch to the other player if current_player == 'X': current_player = 'O' else: current_player = 'X' # Start the game play_game()