http://qs321.pair.com?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

Replies are listed 'Best First'.
Re^2: My Conway's Game Of Life Attempt
by ikegami (Patriarch) on Jan 05, 2010 at 03:28 UTC
    The intent of the substr pair would be clearer as:
    substr($new_world->[$y], $x, 1) = ( $n == 3 ? '0' : ' ' );

      Wouldn't that kill the cell if its $n == 2 and its alive? Basicaly if its $n==2 then the cell remains alive or dead, whichever it was already, dies if its $n<2 or $n>3, and becomes alive if $n==3.


      ___________
      Eric Hodges
        See what I mean by the original being unclear, I misunderstood what it did :)
Re^2: My Conway's Game Of Life Attempt
by Anonymous Monk on Jan 04, 2010 at 19:18 UTC
    thanks a lot, will try it out!