我正在嘗試創建一個迷宮生成器,並且我的代碼出現了一些麻煩。我對Perl比較陌生,對我來說很裸露。在我的腳本開頭,我創建了一個多維數組(@maze
),其中X列數和Y行數。有一個循環遍歷數組,並將所有元素設置爲初始值1. get_neighbors
子例程假設創建一個與top
,right
,bottom
,left
鍵的散列。然後根據傳入的x
和y
座標值設置這些鍵的值。對於top
鍵,我將它的值設置爲正上方的元素應爲[ $y - 1 ][ $x ]
。我假設,如果例如協調0, 0
被傳入,top
將被設置爲undef,因爲這不是一個有效的元素/位置,但它不是..它被設置爲1.不知道爲什麼......希望有人可以發現並解釋爲什麼會發生這種情況。這裏是整個腳本:散列中的意外值?
#!/usr/bin/perl
use warnings;
use strict;
use Switch;
use Data::Dumper;
# Rows is set equal to the first arg passed in
# unless it hasn't been. If it hasn't been, the
# value defaults to 60. This also applies to the
# columns.
my $rows = (defined($ARGV[ 0 ]) ? $ARGV[ 0 ] : 60);
my $cols = (defined($ARGV[ 1 ]) ? $ARGV[ 1 ] : 60);
my $cells = $rows * $cols;
my @maze;
# "Pre-allocate" each "Cell" for the maze.
for(my $y = 0; $y < $rows; ++$y) {
for(my $x = 0; $x < $cols; ++$x) { $maze[ $y ][ $x ] = 1; }
}
# Run
main();
#--------------------------
# Main ~
#--------------------------
sub main {
print Dumper(get_neighbors(0, 0));
generate();
print_maze();
return;
}
#--------------------------
# Generate the maze w/ BFS
#--------------------------
sub generate {
return;
}
#--------------------------
# Print maze to console
#--------------------------
sub print_maze {
for(my $y = 0; $y < $rows; ++$y) {
for(my $x = 0; $x < $cols; ++$x) {
print $maze[ $y ][ $x ] . " ";
}
print "\n";
}
}
#--------------------------
# Returns the values of
# neighboring cells
#--------------------------
sub get_neighbors {
my $x = shift;
my $y = shift;
my %neighbors;
$neighbors{'top'} = defined($maze[ $y - 1 ][ $x ]) ? $maze[ $y - 1 ][ $x ] : undef;
$neighbors{'bottom'} = defined($maze[ $y + 1 ][ $x ]) ? $maze[ $y + 1 ][ $x ] : undef;
$neighbors{'left'} = defined($maze[ $y ][ $x - 1 ]) ? $maze[ $y ][ $x - 1 ] : undef;
$neighbors{'right'} = defined($maze[ $y ][ $x + 1 ]) ? $maze[ $y ][ $x + 1 ] : undef;
return %neighbors;
}
的,當我運行此腳本是:
# perl mazegen.pl 10 10
$VAR1 = 'left';
$VAR2 = 1;
$VAR3 = 'right';
$VAR4 = 1;
$VAR5 = 'top';
$VAR6 = 1;
$VAR7 = 'bottom';
$VAR8 = 1;
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
需要注意的是'$鄰居{ '頂'} =定義($迷宮[ $ y - 1] [$ x])? $ maze [$ y - 1] [$ x]:undef'與* $ neighbors {'top'} = $ maze [$ y-1] [$ x]'*相同。另外,你可以使用defined或者my $ rows =(定義的($ ARGV [0])?$ ARGV [0]:60)'來寫'my $ rows = $ ARGV [0] // 60' 。避免使用C風格的for循環也更好,因爲for(my $ y = 0; $ y <$ rows; ++ $ y){...}成爲'對於我的$ y(0.. $ rows-1){...}' – Borodin 2015-04-03 15:11:34