【发布时间】:2015-04-03 05:43:05
【问题描述】:
我正在尝试创建一个迷宫生成器,但我的代码遇到了一些问题。在脚本的开头,我创建了一个多维数组 (@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
【问题讨论】:
-
请注意,
$neighbors{'top'} = defined($maze[ $y - 1 ][ $x ]) ? $maze[ $y - 1 ][ $x ] : undef与$neighbors{'top'} = $maze[ $y-1][$x]相同。此外,您可以使用my $rows = (defined($ARGV[ 0 ]) ? $ARGV[ 0 ] : 60)的定义或来写my $rows = $ARGV[ 0 ] // 60。避免 C 风格的for循环并迭代一个范围也更好,所以for(my $y = 0; $y < $rows; ++$y) { ... }变为for my $y ( 0 .. $rows-1 ) { ... }