#!/usr/bin/env python3
"""A simple terminal Tic Tac Toe game for two players."""

board = [" "] * 9
current_player = "X"


def print_board():
    for i in range(3):
        row = " | ".join(board[i * 3:(i + 1) * 3])
        print(f" {row}")
        if i < 2:
            print("-----------")


def check_winner():
    lines = [
        (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 lines:
        if board[a] == board[b] == board[c] != " ":
            return board[a]
    return None


def play():
    global current_player
    print("\nTic Tac Toe")
    print("Positions are numbered 1-9, left to right, top to bottom.\n")

    for turn in range(9):
        print_board()
        while True:
            try:
                move = int(input(f"\nPlayer {current_player}, enter position (1-9): ")) - 1
                if 0 <= move <= 8 and board[move] == " ":
                    break
                print("Invalid move. Try again.")
            except (ValueError, EOFError):
                print("Invalid input. Enter a number 1-9.")

        board[move] = current_player
        winner = check_winner()
        if winner:
            print_board()
            print(f"\nPlayer {winner} wins!")
            return
        current_player = "O" if current_player == "X" else "X"

    print_board()
    print("\nIt's a draw!")


if __name__ == "__main__":
    play()
