Well, yes and no. I said
and then, either computing each of the valid moves for each space, or just verifying them on a per-move basis.
If all you're doing is having a chess game between two human players, it may be enough to validate each move on a per-move basis. If you're trying to create an AI, then I'd have some initialization function that runs at startup to build the complex per-space tables based on the simple formulas.
So, for instance, in your case, as you're using an AI, you could compute all of the valid rook moves with:
my %moves; foreach my $i ( -7..-1, 1..7 ) { push @{$moves{'rook'}}, [$i,0], [0,$i]; } my %valid_moves; $valid_moves{'rook'} = []; foreach my $i ( 0 .. 7 ) { $valid_moves{'rook'}->[$i] = []; foreach my $j ( 0 .. 7 ) { $valid_moves{'rook'}->[$i]->[$j] = []; foreach my $move ( @{$moves{'rook'}} ) { my $x = $i - ($move->[0]); next if ( $x < 0 or $x > 7 ); my $y = $j - ($move->[1]); next if ( $y < 0 or $y > 7 ); push @{$valid_moves{'rook'}->[$i]->[$j]}, [$x,$y]; } } }
You can shorten it, of course (rely on autovivication, etc ...) I just did that for the sake of what I find to be easy to come back to at some future point. And to save some time, a queen's valid moves are the union of a bishop and a rook's valid moves.
Oh -- and I have no idea how you'd handle castling after building this table (whereas, by validating each move individually, it's an easy case to test for).
In reply to Re^3: Representing Complex but Static Data in Perl
by jhourcle
in thread Representing Complex but Static Data in Perl
by cyocum
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |