# $Id: Position.pm,v 1.1.1.1 2008/10/12 04:05:34 alamos Exp $ # The state is in an array package TicTacToe::Position; use strict; use TicTacToe::Display; use base qw(Exporter); use vars qw($VERSION); $VERSION='1.0'; sub new() { return bless [' ',' ',' ', ' ',' ',' ', ' ',' ',' ']; } sub clone($) { my $self = shift; return bless [@$self]; } sub square { my $self = shift; my $square = shift; if(@_) { $self->[$square] = shift } return $self->[$square]; } sub display { my $self = shift; return &display_position($self); } sub won($$) { my $self = shift; my $player = shift; return &game_won($player, $self); } sub child() { my $self = shift; my $square = shift; my $player = shift; my($newpos)=$self->clone(); $newpos->square($square, $player); return bless $newpos; } sub test_slice { my($player,$pos,$offset,$step)=@_; for(my($i) = 0; $i < 3; $i ++) { return 0 unless $pos->[$offset] eq $player; $offset+=$step; } return 1; } sub game_won { my($player,$pos)=@_; return # Diagonals &test_slice($player, $pos, 0, 4) || &test_slice($player, $pos, 2, 2) || # Rows &test_slice($player, $pos, 0, 1) || &test_slice($player, $pos, 3, 1) || &test_slice($player, $pos, 6, 1) || # Columns &test_slice($player, $pos, 0, 3) || &test_slice($player, $pos, 1, 3) || &test_slice($player, $pos, 2, 3); } sub unoccupied_squares { my($position)=@_; my @squares; # Squares in the order of importance foreach (4,0,2,6,8,1,3,5,7) { if($position->[$_] eq ' ') { push @squares, $_; } } return @squares; } 1;