#!/usr/bin/env python3
import sys

def print_board(board):
    """Display the current board."""
    line = " {} | {} | {} "
    separator = "---+---+---"
    print()
    print(line.format(board[0], board[1], board[2]))
    print(separator)
    print(line.format(board[3], board[4], board[5]))
    print(separator)
    print(line.format(board[6], board[7], board[8]))
    print()

def check_winner(board, player):
    """Return True if the given player has won."""
    win_combos = [
        (0, 1, 2), (3, 4, 5), (6, 7, 8),  # rows
        (0, 3, 6), (1, 4, 7), (2, 5, 8),  # columns
        (0, 4, 8), (2, 4, 6)              # diagonals
    ]
    return any(all(board[i] == player for i in combo) for combo in win_combos)

def is_draw(board):
    """Return True if the board is full and there is no winner."""
    return all(cell in ('X', 'O') for cell in board)

def get_move(board, player):
    """Prompt the player for a legal move and return the board index."""
    while True:
        try:
            move = input(f"Player {player}, enter your move (1-9): ").strip()
            if not move:
                print("Empty input, please enter a number between 1 and 9.")
                continue
            pos = int(move)
            if not 1 <= pos <= 9:
                print("Number out of range. Choose 1-9.")
                continue
            idx = pos - 1
            if board[idx] in ('X', 'O'):
                print("Cell already taken. Choose another one.")
                continue
            return idx
        except ValueError:
            print("Invalid input. Please enter a number between 1 and 9.")
        except EOFError:
            print("\nInput terminated. Exiting game.")
            sys.exit(0)

def main():
    board = [str(i) for i in range(1, 10)]  # initial board shows numbers
    current_player = 'X'

    while True:
        print_board(board)
        idx = get_move(board, current_player)
        board[idx] = current_player

        if check_winner(board, current_player):
            print_board(board)
            print(f"Player {current_player} wins! Congratulations!")
            break

        if is_draw(board):
            print_board(board)
            print("It's a draw! Well played both.")
            break

        # Switch player
        current_player = 'O' if current_player == 'X' else 'X'

if __name__ == "__main__":
    main()
