gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
I want to code a tic tac toe app with python
- User
I want to code a tic tac toe app with python
- Assistant
Sure! I can help you get started with coding a tic tac toe app in Python. Here's a simple example:
# Tic Tac Toe # Create an empty board board = [' ' for _ in range(9)] # Function to display the board def print_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 if someone won def check_winner(): # Check rows for i in range(0, 9, 3): if board[i] == board[i+1] == board[i+2] != ' ': return board[i] # Check columns for i in range(3): if board[i] == board[i+3] == board[i+6] != ' ': return board[i] # Check diagonals if board[0] == board[4] == board[8] != ' ': return board[0] if board[2] == board[4] == board[6] != ' ': return board[2] # No winner return None # Function to play the game def play_game(): current_player = 'X' game_over = False while not game_over: print_board() position = int(input("Enter a position (0-8): ")) # Validate the position if position < 0 or position > 8 or board[position] != ' ': print("Invalid position, try again.") continue # Update the board board[position] = current_player # Check if current player won winner = check_winner() if winner: print_board() print("Congratulations! Player", winner, "wins!") game_over = True # Check if it's a tie if ' ' not in board: print_board() print("It's a tie!") game_over = True # Switch to the other player current_player = 'O' if current_player == 'X' else 'X' # Start the game play_game()