http://www.perlmonks.org?node_id=815602


in reply to My Conway's Game Of Life Attempt

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.


___________
Eric Hodges