# $Id: Board.pm,v 1.1.1.1 2008/10/12 04:05:34 alamos Exp $ # The state is in an array package TicTacToe::Board; use strict; use TicTacToe::Display; use TicTacToe::Position qw(:all); use base qw(Exporter); use vars qw(@ISA $VERSION @EXPORT); $VERSION='1.0'; @EXPORT = qw(&init_game &display_game &make_move &generate_moves &apply_move); # Mapping to the opponent my($opponent) = { x =>'o', o => 'x'}; sub apply_move { my($game,$move)=@_; my($value); my($result) = undef; my($new_game)= { position => &child_position($game->{position}, $move->{square}, $game->{player}), player => $opponent->{$game->{player}}, ply => $game->{ply} + 1 }; if(game_won($game->{player}, $new_game->{position})) { $move->{value} = 100 - $new_game->{ply} ; $new_game->{result} = 'won'; } else { # Number of occupied squares is the value my(@blanks) = grep /^ $/, @{$new_game->{position}}; if($new_game->{ply} == 9) { $new_game->{result}='stalemate'; } $move->{value} = $new_game->{ply}; } return $new_game; } sub generate_moves { my($game)=@_; my(@squares) = &unoccupied_squares($game->{position}); $game->{result}='stalemate' unless(@squares); map { &make_move($_) } @squares; } sub make_move { my($square)=@_; return { square => $square, value => undef }; } sub display_game { my($game)=@_; &display_position($game->{position}); print "Ply: $game->{ply}\n"; print "$game->{player} to move\n"; } sub init_game { return { position => &init_position, player => 'o', ply => 0 }; } 1;