# $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 base qw(Exporter); use vars qw(@ISA $VERSION @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION='1.0'; ## Export these symbols automatically @EXPORT = qw(&init_position); ## Let the caller import this @EXPORT_OK = qw(&game_won &unoccupied_squares &child_position); ## Create export tags (lists of symbols for selective import from other modules) %EXPORT_TAGS = (all=> [qw(&init_position &game_won &unoccupied_squares &child_position)]); 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; } sub child_position { my($position, $square, $player)=@_; my($newpos)=[@$position]; $newpos->[$square]=$player; return $newpos; } sub init_position { return [' ',' ',' ', ' ',' ',' ', ' ',' ',' ']; } 1;