#!perl

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

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

my ($size, $symbol);

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

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

do {
    print {*STDOUT} "Please select the symbol [X / O]: ";
    $symbol = <STDIN>;
    chomp($symbol);
} unless (defined $symbol && ($symbol =~ /^[X|O]$/i));

$tictactoe->addPlayer($symbol);

my $response = 'Y';
while (defined($response)) {
    if ($response =~ /^Y$/i) {
        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 {
                    print {*STDOUT} "What is your next move [$available] ? ";
                    $move = <STDIN>;
                    chomp($move);
                    while (defined $move && !$tictactoe->isValidMove($move)) {
                        print {*STDOUT} "Please make a valid move [$available]: ";
                        $move = <STDIN>;
                        chomp($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;

        print {*STDOUT} "Do you wish to continue (Y/N)? ";
        $response = <STDIN>;
        chomp($response);
    }
    elsif ($response =~ /^N$/i) {
        print {*STDOUT} "Thank you.\n";
        last;
    }
    elsif ($response !~ /^[Y|N]$/i) {
        print {*STDOUT} "Invalid response, please enter (Y/N): ";
        $response = <STDIN>;
        chomp($response);
    }
}
