Skip to content

Instantly share code, notes, and snippets.

@masak
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masak/f74ce61b40ea996b9583 to your computer and use it in GitHub Desktop.
Save masak/f74ce61b40ea996b9583 to your computer and use it in GitHub Desktop.
#! /usr/local/bin/perl6
use v6;
# don't need to use warnings or strict
# original code had the class after the .new call; that doesn't work
# because of one-pass parsing
# kinda un-idiomatic to have a class name not start with a capital;
# but it *works*, so I'll keep it
class life {
# original had forgotten to put `is rw` -- might not have existed
# in 2003, though
has Int $.count is rw = 0;
has Int $.dimension;
# originally typed as `Array of Int`; one of the rare cases where
# I think `Array of` is right (but possibly for the wrong reasons).
# I removed the typing because it doesn't tend to work very well.
#
# originally also had `dim ($.dimension, $.dimension)` -- that
# definitely doesn't work yet, and contemporary syntax would be
# just `has @.grid[$.dimension; $.dimension]`
has @.grid;
method new(Int $dimension) {
self.bless(:$dimension);
}
submethod BUILD(Int :$!dimension) {
@!grid = [0 xx $!dimension] xx $!dimension;
my @init = [-1, 0], [-1, +1], [0, 0], [0, -1], [+1, 0];
for @init -> [$dx, $dy] {
@!grid[$!dimension / 2 + $dx][$!dimension / 2 + $dy] = 1;
}
}
method !calculate() {
my @newgrid = [0 xx $.dimension] xx $.dimension;
for ^$.dimension -> $x {
for ^$.dimension -> $y {
my $live = 0;
for $x-1..$x+1 X $y-1..$y+1 -> $nx, $ny {
next unless $nx ~~ 0 ..^$.dimension;
next unless $ny ~~ 0 ..^$.dimension;
$live++ if @.grid[$nx][$ny] == 1;
}
my $oldval = @.grid[$x][$y];
# was (accidentally) sigil-variant $newgrid[$x][$y]
@newgrid[$x][$y] =
$oldval == 0 && $live == 3 ?? 1 !!
$oldval == 1 && $live ~~ 1..4 ?? 1 !! 0;
}
}
@.grid = @newgrid;
}
method display {
# I wouldn't have mapped $x to rows, but original author did, so...
for ^$.dimension -> $x {
# was (accidentally) sigil-variant $.grid in original
say (^$.dimension).map({@.grid[$x][$_]}).join;
}
# original accidentally had a " at the start and a ' at the end of the string
prompt "Turn {++$.count}, press enter for next turn, ctl-c to quit";
self!calculate();
}
}
my $life = life.new(20);
loop {
$life.display();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment