#!/usr/bin/perl
use strict ;

push ( @INC, "." ) ;
use coins ;

while( 1 ) { print "\n\n\t\tNEW GAME?"; <>; print "\n\n"; play_game() ; }

sub play_game {
	my $game = new coins ;
	print "\n" ;
	$game->display ;

	while ( 1 ) {

#PLAYER 0 = COMPUTER
		my ( $coin, $pos ) = search( $game ) ;
		if ( defined $coin ) {
			print "\tMy move:\n\t\tCoin: $coin\n\t\tPos:  $pos\n\n" ;
			$game->move( $coin, $pos ) ;
			$game->display ;
			if( $game->evaluate_state == 1 ) { print "\n\t\tI WIN!\n\n" ; return ; }
		} else {
			print "\tChoosing to skip firt turn\n\n" ;
		}

#PLAYER 1 = HUMAN

		my $state ;
		do {
			print "\tYour move: \n\t\tCoin: " ;
			$coin = <> ; chomp($coin) ;
			print "\t\tPos:  " ;
			$pos = <> ; chomp($pos) ;
			print "\n" ;
			$state = $game->move($coin,$pos) ;
		} until ( defined $state ) ;
		$game->display ;
		if( $game->evaluate_state == 1 ) { print "\n\t\tYOU WIN!\n\n" ; return ; }
	}
}




sub search {
	my ( $game ) = @_ ;

	my @all_possible_moves = $game->allowed_moves ;
	for( my $i=0 ; $i <= $#all_possible_moves ; $i++ ) {
		my $coin = $all_possible_moves[$i]->[0] ;
		my $pos  = $all_possible_moves[$i]->[1] ;
		my $game_after_move = $game->clone; 
		$game_after_move->move( $coin, $pos ) ;
		if( sure_winner($game_after_move) ) { return( $coin, $pos ) ; }
	}
	return ( undef, undef ) ;
}



sub sure_winner {
	my ( $game ) = @_ ;

	if ( $game->evaluate_state == 1 ) { return 1 ; }

	my @all_possible_moves = $game->allowed_moves ;
	for( my $i=0 ; $i <= $#all_possible_moves ; $i++ ) {
		my $coin = $all_possible_moves[$i]->[0] ;
		my $pos  = $all_possible_moves[$i]->[1] ;
		my $game_after_move = $game->clone ;
		$game_after_move->move( $coin, $pos ) ;
		if ( sure_winner($game_after_move) ) { return 0 ; }
	}
	return 1 ;
}




