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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.