import random # Board initialization board = [' ' for _ in range(9)] # A list to represent the 3x3 Tic-Tac-Toe board # Function to print the board def print_board(): print("\n") for i in range(0, 9, 3): print(f"{board[i]} | {board[i+1]} | {board[i+2]}") if i < 6: print("--+---+--") print("\n") # Function to check if a player has won def check_win(player): win_conditions = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], # Horizontal [0, 3, 6], [1, 4, 7], [2, 5, 8], # Vertical [0, 4, 8], [2, 4, 6] # Diagonal ] for condition in win_conditions: if all(board[i] == player for i in condition): return True return False # Function to check if the board is full (draw) def board_full(): return ' ' not in board # AI to make its move (choose a random empty spot) def ai_move(): available_moves = [i for i in range(9) if board[i] == ' '] return random.choice(available_moves) # Function to play the game def play_game(): print("Tic-Tac-Toe Game: You are 'X' and AI is 'O'.") while True: print_board() # Human player's move (X) human_move = int(input("Enter your move (0-8): ")) if board[human_move] != ' ': print("Invalid move, try again.") continue board[human_move] = 'X' if check_win('X'): print_board() print("You win!") break if board_full(): print_board() print("It's a draw!") break # AI player's move (O) print("AI is making its move...") ai_pos = ai_move() board[ai_pos] = 'O' if check_win('O'): print_board() print("AI wins!") break if board_full(): print_board() print("It's a draw!") break # Start the game play_game()