It's got several different AI modules that you can play against. Right now, I'm working on a simplistic rules-based AI. All it does is look for particular cases (such as being able to win on its next move), and take the appropriate action.
I'd like to smarten it up a bit, by adding an additional check for potential "traps" (situations where you can win two different ways, thus guaranteeing your victory). I'm wondering if there's an easier way to check for them than just hard-coding in all the possibilities. I'd like to extend this to 3-D Tic Tac Toe later, and that strategy obviously won't scale. Any suggestions on how to go about it?
Incidentally, I do know about the minimax algorithm, and that will be another of the AI subroutines available. But I'd like to get a strong rule-based one set up as well, so I can compare their speed and ability.
Here's my current subroutine for reference, and some explanation as to what's going on in it:
---# 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 o +n 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)]; }
In reply to Tic Tac Toe quasi-AI by Sprad
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |