in reply to Writing a random dungeon generator in perl.

I think line 22 just refers to the start of the if chain. This is start of your problem:

elsif ($dungeon[$start] eq '#' && $dungeon[$start] + 1 eq '#'

You probably want to do the "+1" inside the brackets.

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Replies are listed 'Best First'.
Re^2: Writing a random dungeon generator in perl.
by xdg (Monsignor) on Aug 15, 2005 at 22:47 UTC

    To the second part of your question, you'll probably have an easier time with your project if you try some of these tips:

    • Parameterize your sizes and use them in your code; it will help you catch logical errors and makes it easier to test how it works on a small size array
    • Parameterize your map symbols; easier to change later and easier to understand in the logic of your code
    • Write in logical paragraph and consider commenting them for clarity of intent
    • Replace some of your loop flags and "init then increment" loops with logic that more closely resembles what you're trying to do

    I've revised parts of your example to show what I mean. (Not the most Perlish way to do it, but a step closer that should be clear to see the difference.) I've left out most of your room logic as it wasn't clear what you intended.

    #!/usr/bin/perl use strict; use warnings; my ($dungeon_width, $dungeon_height) = (20, 20); my $WALL = '#'; my $ROOM = '.'; my @dungeon = ($WALL) x ( $dungeon_width * $dungeon_height ); + sub generatemap { # clear a starting location my $cur_location = int rand( @dungeon ); # 0 to $#dungeon $dungeon[ $cur_location ] = $ROOM; # clear squares for (about) half the dungeon my $room_count = 1; while ($room_count < @dungeon / 2) { # pick a square adjacent to the current one my $choice = (-1, +1, -$dungeon_width, +$dungeon_width)[int ra +nd 4]; my $new_location = $cur_location + $choice; # pick again if it would take us out of bounds if ($new_location < 0 || $new_location > $#dungeon) { redo; } # clear it if it's not already a room $cur_location = $new_location; if ( $dungeon[ $cur_location ] ne $ROOM ) { $dungeon[ $cur_location ] = $ROOM; $room_count++; } } } sub printmap { for my $row (0 .. $dungeon_height - 1) { my $first_col = $row * $dungeon_width; my $last_col = $first_col + $dungeon_width - 1; print @dungeon[ $first_col .. $last_col ], "\n"; } } generatemap; printmap;

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.