#!/usr/bin/env python3

def print_board(board):
    # board is a list of 9 elements: 'X', 'O', or ' '
    # print as 3x3 grid with cell numbers for empty cells
    def cell_str(i):
        return board[i] if board[i] != ' ' else str(i+1)
    print()
    print(f" {cell_str(0)} | {cell_str(1)} | {cell_str(2)} ")
    print("---+---+---")
    print(f" {cell_str(3)} | {cell_str(4)} | {cell_str(5)} ")
    print("---+---+---")
    print(f" {cell_str(6)} | {cell_str(7)} | {cell_str(8)} ")
    print()

def check_winner(board, player):
    # Returns True if player has a winning line
    lines = [
        (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
    ]
    for a,b,c in lines:
        if board[a] == board[b] == board[c] == player:
            return True
    return False

def board_full(board):
    return all(cell != ' ' for cell in board)

def prompt_move(player, board):
    while True:
        move = input(f"Player {player}, enter your move (1-9): ").strip()
        if not move.isdigit():
            print("Invalid input. Please enter a number 1-9.")
            continue
        pos = int(move)
        if not 1 <= pos <= 9:
            print("Invalid move. Number must be between 1 and 9.")
            continue
        if board[pos-1] != ' ':
            print("That cell is already occupied. Choose another.")
            continue
        return pos-1

def main():
    board = [' '] * 9
    current_player = 'X'

    while True:
        print_board(board)
        pos = prompt_move(current_player, board)
        board[pos] = current_player

        if check_winner(board, current_player):
            print_board(board)
            print(f"Player {current_player} wins!")
            break
        if board_full(board):
            print_board(board)
            print("It's a draw!")
            break

        current_player = 'O' if current_player == 'X' else 'X'

if __name__ == "__main__":
    main()
