import sys

def print_board(board):
    """Prints the 3x3 board in a readable format."""
    print("\n")
    for i in range(0, 9, 3):
        row = board[i:i+3]
        # Replace empty spaces with numbers for easier user reference
        display_row = []
        for idx, cell in enumerate(row):
            actual_idx = i + idx + 1
            display_row.append(cell if cell != " " else str(actual_idx))
        print(" | ".join(display_row))
        if i < 6:
            print("-" * 9)
    print("\n")

def check_winner(board):
    """Checks if there is a winner or a draw."""
    win_conditions = [
        (0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows
        (0, 3, 6), (1, 4, 7), (2, 5, 8), # Cols
        (0, 4, 8), (2, 4, 6)             # Diagonals
    ]
    for a, b, c in win_conditions:
        if board[a] == board[b] == board[c] and board[a] != " ":
            return board[a]
    
    if " " not in board:
        return "Draw"
    
    return None

def main():
    # Initialize board as a list of 9 spaces
    board = [" "] * 9
    current_player = "X"
    
    print("Welcome to Tic-Tac-Toe!")
    print("Instructions: Enter a number 1-9 to place your mark.")
    
    while True:
        print_board(board)
        
        # Get user input
        try:
            move_input = input(f"Player {current_player}, enter your move (1-9): ")
            move = int(move_input) - 1
            
            if move < 0 or move > 8:
                print("Invalid input. Please choose a number between 1 and 9.")
                continue
            
            if board[move] != " ":
                print("That cell is already occupied! Try again.")
                continue
                
        except ValueError:
            print("Invalid input. Please enter a numeric digit.")
            continue

        # Place the mark
        board[move] = current_player
        
        # Check for game end
        result = check_winner(board)
        if result:
            print_board(board)
            if result == "Draw":
                print("It's a draw!")
            else:
                print(f"Player {result} wins!")
            break
        
        # Switch players
        current_player = "O" if current_player == "X" else "X"

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nGame exited.")
        sys.exit(0)
