Galton box animation: Difference between revisions

Line 1,265:
=={{header|Perl 6}}==
[[File:Galton_box_perl6.gif|thumb|UPPER HALF BLOCK and LOWER HALF BLOCK alternate to give a somewhat smooth animation.]]
{{works with|rakudo|2015-09-12}}
<lang Perl6>my $row-count = 6;
 
constant $peg = "*";
constant @coin-icons = "\c[UPPER HALF BLOCK]", "\c[LOWER HALF BLOCK]";
 
sub display-board(@positions, @stats is copy, $halfstep) {
my $coin = @coin-icons[$halfstep.Int];
 
state @board-tmpl = {
# precompute a board
my @tmpl;
sub out(*@stuff) {
@tmpl.push: $[@stuff.join>>.ords.itemflat];
}
# three lines of space above
for (1..3) {
out " ", " " x (2 * $row-count);
}
# $row-count lines of pegs
for flat ($row-count...1) Z (1...$row-count) -> $spaces, $pegs {
out " ", " " x $spaces, ($peg xx $pegs).join(" "), " " x $spaces;
}
# four lines of space below
for (1..4) {
out " ", " " x (2 * $row-count);
}
@tmpl
}();
 
my $midpos = $row-count + 2;
 
my @output;
{
Line 1,305 ⟶ 1,306:
@output.push: $foo;
}
 
# make some space above the picture
say "" for ^10;
 
my @output-lines = map { [map *.clone, @$_].item }, @board-tmpl;
# place the coins
Line 1,319 ⟶ 1,320:
say @line>>.chr.join("");
}
 
# show the statistics
my $padding = 0;
Line 1,347 ⟶ 1,348:
say @output.join("");
}
 
sub simulate($coins is copy) {
my $alive = True;
 
sub hits-peg($x, $y) {
if 3 <= $y < 3 + $row-count and -($y - 2) <= $x <= $y - 2 {
Line 1,357 ⟶ 1,358:
return False;
}
 
my @coins = Int xx (3 + $row-count + 4);
my @stats = 0 xx ($row-count * 2);
Line 1,370 ⟶ 1,371:
}
}
 
# move every coin down one row
for ( 3 + $row-count + 3 )...1 -> $line {
my $coinpos = @coins[$line - 1];
 
@coins[$line] = do if not $coinpos.defined {
Nil
Line 1,393 ⟶ 1,394:
@coins[0] = 0
}
 
# smooth out the two halfsteps of the animation
my $start-time;
ENTER { $start-time = now }
my $wait-time = now - $start-time;
 
sleep 0.1 - $wait-time if $wait-time < 0.1;
for @coin-icons.keys {
Line 1,406 ⟶ 1,407:
}
}
 
sub MAIN($coins = 20, $peg-lines = 6) {
$row-count = $peg-lines;
Anonymous user