#!perl

use strict; use warnings;
use Games::TicTacToe;

$|=1;

$SIG{'INT'} = sub { print {*STDOUT} "\n\nCaught Interrupt (^C), Aborting\n"; exit(1); };

my ($size);
my $tictactoe = Games::TicTacToe->new;

do {
    print {*STDOUT} "Please enter game board size (type 3 if you want 3x3): ";
    $size = <STDIN>;
    chomp($size);
} while (!$tictactoe->isValidGameBoardSize($size));

$tictactoe->setGameBoard($size);

my ($symbol);
do {
    print {*STDOUT} "Please select the symbol [X / O]: ";
    $symbol = <STDIN>;
    chomp($symbol);
} while (!$tictactoe->isValidSymbol($symbol));

$tictactoe->addPlayer($symbol);

my ($response);
do {
    print {*STDOUT} $tictactoe->getGameBoard;
    my $index = 1;
    my $board = $tictactoe->board;
    while (!$tictactoe->isGameOver) {
        my $move = undef;
        if ($tictactoe->needNextMove) {
            my $available = $board->availableIndex;
            if ($tictactoe->isLastMove) {
                $move = $available;
            }
            else {
                do {
                    print {*STDOUT} "What is your next move [$available] ? ";
                    $move = <STDIN>;
                    chomp($move);
                } while (defined $move && !$tictactoe->isValidMove($move));
            }
        }

        $tictactoe->play($move);

        if (($index % 2 == 0) && !$tictactoe->isGameOver) {
            print {*STDOUT} $tictactoe->getGameBoard;
        }
        $index++;
    }

    print {*STDOUT} $tictactoe->result;
    print {*STDOUT} $tictactoe->getGameBoard;

    $tictactoe->board->reset;

    do {
        print {*STDOUT} "Do you wish to continue (Y/N)? ";
        $response = <STDIN>;
        chomp($response);
    } while (defined $response && ($response !~ /^[Y|N]$/i));

} while (defined($response) && ($response =~ /^Y$/i));

print {*STDOUT} "Thank you.\n";
