import random
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
def check_winner(board, player):
# Check rows, columns, and diagonals
for i in range(3):
if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)):
return True
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
return True
return False
def is_board_full(board):
return all(cell != ' ' for row in board for cell in row)
def get_user_move():
while True:
try:
position = int(input("Enter a number between 1 and 9: "))
if 1 <= position <= 9:
return position - 1
print("Invalid input. Please enter a number between 1 and 9.")
except ValueError:
print("Invalid input. Please enter a number between 1 and 9.")
def get_user_symbol():
while True:
user_choice = input("Choose 'X' or 'O': ").upper()
if user_choice in ['X', 'O']:
return user_choice
print("Invalid choice. Please choose 'X' or 'O.")
def play_game():
user_symbol = get_user_symbol()
computer_symbol = 'X' if user_symbol == 'O' else 'O'
board = [[' ' for _ in range(3)] for _ in range(3)]
players = [user_symbol, computer_symbol]
random.shuffle(players) # Randomize the starting player
current_player = players[0]
while True:
print_board(board)
position = get_user_move() if current_player == user_symbol else random.choice([(i, j) for i in range(3) for j in range(3) if board[i][j] == ' '])
row, col = divmod(position, 3)
if board[row][col] == ' ':
board[row][col] = current_player
if check_winner(board, current_player):
print_board(board)
print(f"Congratulations! {current_player} wins!")
break
if is_board_full(board):
print_board(board)
print("It's a tie!")
break
current_player = players[1] if current_player == players[0] else players[0]
else:
print("The cell is already taken. Choose another one.")
if __name__ == "__main__":
play_game()