Skip to content

Instantly share code, notes, and snippets.

Created October 29, 2015 17:42
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 anonymous/c3303e1f975c607ab2bb to your computer and use it in GitHub Desktop.
Save anonymous/c3303e1f975c607ab2bb to your computer and use it in GitHub Desktop.
my $RED = "\e[1;31m";
my $GREEN = "\e[0;32m";
my $CLEAR = "\e[0m";
enum Cell-State <Empty Tree Burning>;
my @show = (' ', $GREEN ~ '木' ~ $CLEAR, $RED ~ '火' ~ $CLEAR);
class Forest {
has @!grid;
has @!neighbors;
has Int $.height;
has Int $.width;
has $.p;
has $.f;
method new(Int $height, Int $width, $p=0.01, $f=0.001) {
my $c = self.bless(:$height, :$width, :$p, :$f);
$c!init-grid;
$c!init-neighbors;
return $c;
}
method !init-grid {
@!grid = [ flat (Bool.pick ?? Tree !! Empty) xx $!width ] xx $!height;
}
method !init-neighbors {
@!neighbors = [ [] xx $!width ] xx $!height; # XXX rakudo doesn't autoviv yet
for flat(^$!height X ^$!width) -> $i, $j {
my $k = 0;
for
[-1,-1],[+0,-1],[+1,-1],
[-1,+0], [+1,+0],
[-1,+1],[+0,+1],[+1,+1]
{
my $n := @!grid[$i + .[0]][$j + .[1]];
@!neighbors[$i][$j][$k++] := $n if $n;
}
}
}
method step {
my @new;
@new = [] xx $!height; # XXX rakudo doesn't autoviv yet
for flat (^$!height X ^$!width) -> $i, $j {
given @!grid[$i][$j] {
when Empty { @new[$i][$j] = rand < $!p ?? Tree !! Empty }
when Tree { @new[$i][$j] =
(@!neighbors[$i][$j].any === Burning or rand < $!f) ?? Burning !! Tree;
}
when Burning { @new[$i][$j] = Empty }
}
}
for flat(^$!height X ^$!width) -> $i, $j {
@!grid[$i][$j] = @new[$i][$j];
}
}
method Str {
join '', gather for ^$!height -> $i {
take @show[@!grid[$i].list], "\n";
}
}
}
sub MAIN ($w, $h, $steps) {
my Forest $f .= new($h, $w);
print "\e[2J$CLEAR"; # ANSI clear screen
my $i = 0;
until $i >= $steps {
print "\e[H"; # ANSI home
say $i++;
say $f.Str;
$f.step;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment