# rulesAI($x_or_o, @board); # Returns index of chosen move # @board = 9-element array, initialized to ($c,$c,$c,$c,$c,$c,$c,$c,$c) # $c - character representing unoccupied square # sub legals() - accepts a @board, returns list of unoccupied spaces on it # sub check() - accepts a @board, returns "x" or "o" if x or o won, -1 if tie, 0 otherwise sub rulesAI { my $mv = -1; my $col = shift; my @choices = legals(@_); # priorities: # 1. Win, if possible foreach $m (@choices) { $_[$m] = $col; if (check(@_) =~ /$col/) { $mv = $m; last; } $_[$m] = $c; } unless ($mv == -1) { return $mv; } # 2. Block opponent, if necessary my $opcol = ($col =~ /x/) ? 'o' : 'x'; foreach $m (@choices) { $_[$m] = $opcol; if (check(@_) =~ /$opcol/) { $mv = $m; last; } $_[$m] = $c; } unless ($mv == -1) { return $mv; } # 3. Set up a trap # 4. Choose at random return $choices[(rand$#choices+1) % ($#choices+1)]; }