gregor42 has asked for the wisdom of the Perl Monks concerning the following question:

I have been playing around with coordinate systems for a simple RPG. What I'm trying to do is to spit out a series of coordinates, starting from a center point (0,0) & circling outwards.

I have come up with this. But there's a lot of redundancy in the code. I know there is a simpler way to do this. Please bretheren, I ask your advice.

#!E:\perl\bin\perl.exe $max_range = 3; for $range(0..$max_range) { $y = $range; for $x(-$range..$range) { print "$x,$y \n"; } $x = $range; for $y(reverse(-$range..$range)) { print "$x,$y \n"; } $y = -($range); for $x(reverse(-$range..$range)) { print "$x,$y \n"; } $x = -$range; for $y(-$range..$range) { print "$x,$y \n"; } }


Wait! This isn't a Parachute, this is a Backpack!

Replies are listed 'Best First'.
(boo) Re: 2D coords circling outwards
by boo_radley (Parson) on Jun 09, 2001 at 00:44 UTC
    You pick up a fortune cookie (t). 

    You eat the fortune cookie. --more--

    This cookie has a scrap of paper inside. --more--

    The paper reads "You should investigate polar coordinates."

      That would be a great suggestion, except we that we seem to be constrained to integer coordinates.

      I can't think of any way to avoid dealing with the four sides of the square separately. You might try replacing the range loop body with something like the fragment below. I think it's somewhat easier to understand, and it doesn't print each corner of the square twice (though it does miss the origin).

      my ($x, $y) = ($range, $range); while ($x > -$range) { print "$x,$y\n"; $x-- } while ($y > -$range) { print "$x,$y\n"; $y-- } while ($x < $range) { print "$x,$y\n"; $x++ } while ($y < $range) { print "$x,$y\n"; $y++ }

      This shows why it's nice that perl lets you do what you want with whitespace, unlike some other languages.

Re: 2D coords circling outwards
by Albannach (Monsignor) on Jun 09, 2001 at 09:30 UTC
    I'm not entirely clear on what you mean by "circling outwards" - does that imply a particular order to the points? If you just want the list of coordinates of all the points in the square, then this was my first thought (though it's shorter without the nicely arranged output):
    my ($min, $max) = (-$range, $range); for(my $y=$max; $y>=$min; $y--) { for my $x ($min..$max) { print "$x,$y\t"; } print "\n"; }

    --
    I'd like to be able to assign to an luser

Re: 2D coords circling outwards
by bikeNomad (Priest) on Jun 09, 2001 at 21:37 UTC
    This gives a nice order and doesn't repeat like your example does:
    #!/usr/bin/perl -w use strict; my @dx = ( -1, 0, 1, 0 ); my @dy = ( 0, -1, 0, 1 ); my ($centerX, $centerY) = (0, 0); my @range = (1 .. 3); foreach my $r (@range) { my ($px, $py) = ($r, $r); # starting point foreach my $d (0..3) { foreach (1..$r*2) { $px += $dx[$d]; $py += $dy[$d]; printf "%d,%d\n", $px+$centerX, $py+$centerY; } } }