Untitled
unknown
plain_text
2 years ago
2.0 kB
5
Indexable
# Define the initial empty board board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] # Function to print the board def print_board(): print(board[0] + " | " + board[1] + " | " + board[2]) print("--|---|--") print(board[3] + " | " + board[4] + " | " + board[5]) print("--|---|--") print(board[6] + " | " + board[7] + " | " + board[8]) # Function to check if the game is over def check_game_over(): # Check rows for i in range(0, 9, 3): if board[i] == board[i+1] and board[i+1] == board[i+2] and board[i] != " ": return True # Check columns for i in range(0, 3): if board[i] == board[i+3] and board[i+3] == board[i+6] and board[i] != " ": return True # Check diagonals if board[0] == board[4] and board[4] == board[8] and board[0] != " ": return True if board[2] == board[4] and board[4] == board[6] and board[2] != " ": return True # Check if the board is full if " " not in board: return True return False # Function to play the game def play_game(): # Define the initial player current_player = "X" # Loop until the game is over while not check_game_over(): # Print the board print_board() # Get the player's move move = input(current_player + "'s turn. Enter a position (1-9): ") # Check if the move is valid if not move.isdigit() or int(move) < 1 or int(move) > 9 or board[int(move)-1] != " ": print("Invalid move. Please try again.") continue # Update the board board[int(move)-1] = current_player # Switch to the other player current_player = "O" if current_player == "X" else "X" # Print the final board print_board() # Check who won or if it was a tie if check_game_over() and " " not in board: print("It's a tie!") else: print(current_player + " wins!") # Start the game play_game()
Editor is loading...