Hey i was reading your post and thought that there might be a clearer way to save that data so i came up with the following. I started with your code then adapted it slowly till it became this. I used strings to hold the rows instead of arrays just because it made printing and inputing a lot easier. It also iterates on key press instead of using a counter, and stops when you enter 'q'.
#!/usr/bin/perl
use strict;
use warnings;
use Clone qw( clone );
$|++;
my $width = 29;
my $height = 29;
my $world = [
#0 1 2 3
#123456789012345678901234567890
' ',#1
' 00 ',#2
' 0 ',#3
' 0 ',#4
' 00 ',#5
' ',#6
' ',#7
' ',#8
' ',#9
' ',#10
' ',#1
' 000 ',#2
' ',#3
' ',#4
' ',#5
' ',#6
' ',#7
' ',#8
' ',#9
' ',#20
' ',#1
' ',#2
' ',#3
' ',#4
' ',#5
' ',#6
' ',#7
' ',#8
' ',#9
' ',#30
]
;
my $i = 0;
print_world($world);
while (<>) {
chomp; exit if $_ eq 'q';
print "iteration:", $i++, "\n";
$world = iterate($world);
print_world($world);
}
sub print_world {
my $world = shift;
for my $row (@$world) {
print "$row\n";
}
};
sub iterate {
my $world = shift;
my $new_world = clone($world);
for my $x (0 .. $width) {
for my $y (0 .. $height) {
my $n = 0;
for my $xc (-1,0,1) {
for my $yc ( -1,0,1) {
next if $xc == 0 and $yc == 0;
my $tx = $x+$xc;
next if $tx > $width or $tx < 0;
my $ty = $y + $yc;
next if $ty > $height or $ty < 0;
#warn "$x + $xc = $tx\t$y + $yc = $ty";
my $tmp = substr($world->[$ty], $tx,1);
$n++ if $tmp eq '0';
}
}
substr($new_world->[$y], $x,1) = ' ' if $n < 2 or $n > 3;
substr($new_world->[$y], $x,1) = '0' if $n == 3;
}
}
return $new_world;
};
I broke out the printing and iterating out into functions so that they can be called independently and you don't have to repeat the code. Hopefully you can use this to figure out what is wrong with your version, plus it gave me a chance to play with substr which i havn't realy done before.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.