in reply to 2D Arrays as a Gameboard
A hash of hashes will do the trick nicely and is infinitely extensible. Here I populate a game board that extends from x = -5 to x = +5 with the same range for y then pluck a value from one square (I store the co-ordinates there for simplicity). Probably the simplest, if not the most memory efficient way to do it.
Hope this helps.
Cheers
tachyon
# declare $grid to hold ref to anon hashes (thanks tye) my $grid; for my $x(-5..5) { for my $y(-5..5) { $grid->{$x}{$y} = "co-ords x:$x, y:$y"; } } print "Here is -2,3 : ", $grid->{-2}{3}; print "\nHere is 0,0 : ", $grid->{0}{0};
If you want to store a range of attributes for each square a super grid made of a hash of hashes will work.
my %grid1; for my $x(-5..5) { for my $y(-5..5) { $grid1{$x,$y} = { name => "$x,$y", power => int rand(10), allow => "all" }; } } print "\nHere is name 0,0 : ", $grid1{0,0}{'name'}; print "\nHere is power -2,3 : ", $grid1{-2,3}{'power'}; print "\nHere is allow 5,4 : ", $grid1{0,0}{'allow'};
A hash of hash of arrays is more space efficient but you must index the contents of each square numerically
my %grid2; for my $x(-5..5) { for my $y(-5..5) { $grid2{$x,$y} = ["$x,$y",int rand(10),"all"]; } } print "\nHere is name 0,0 : ", $grid2{0,0}[0]; print "\nHere is power -2,3 : ", $grid2{-2,3}[1]; print "\nHere is allow 5,4 : ", $grid2{0,0}[2];
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(tye)Re: 2D Arrays as a Gameboard
by tye (Sage) on Jun 06, 2001 at 22:51 UTC | |
by tachyon (Chancellor) on Jun 06, 2001 at 23:26 UTC | |
by tye (Sage) on Jun 07, 2001 at 00:00 UTC |