Skip to content

Instantly share code, notes, and snippets.

@mscha
Last active November 1, 2023 17:00
Show Gist options
  • Save mscha/86cea1130af4332f055707cfe5681c42 to your computer and use it in GitHub Desktop.
Save mscha/86cea1130af4332f055707cfe5681c42 to your computer and use it in GitHub Desktop.
Snakes and ladders simulation based on https://www.youtube.com/watch?v=nlm07asSU0c
#!/usr/bin/env raku
use v6.d;
class SnakesAndLadders
{
enum OvershootRules <StepBack StandStill>;
#constant $START-POS = 1;
#constant $WIN-POS = 64;
#constant %SNAKES = 23=>4, 30=>10, 42=>9, 49=>15, 54=>20, 61=>46;
#constant %LADDERS = 7=>22, 8=>40, 13=>56, 14=>47, 35=>60;
#constant $OVERSHOOT = StepBack;
constant $START-POS = 0;
constant $WIN-POS = 9;
constant %SNAKES = 8=>2;
constant %LADDERS = 4=>7;
constant $OVERSHOOT = StandStill;
has $.pos = $START-POS;
has $.turns = 0;
has $.verbose = False;
method won { $!pos == $WIN-POS }
method turn
{
return if self.won;
print $!pos if $!verbose && $!turns == 0;
my $roll = (1..6).roll;
print " ($roll) " if $!verbose;
$!pos += $roll;
if $!pos > $WIN-POS {
given ($OVERSHOOT) {
when StepBack { $!pos = 2*$WIN-POS - $!pos }
when StandStill { $!pos -= $roll }
}
}
print $!pos if $!verbose;
if %SNAKES{$!pos} {
$!pos = %SNAKES{$!pos};
print "↘$!pos" if $!verbose;
}
elsif %LADDERS{$!pos} {
$!pos = %LADDERS{$!pos};
print "↗$!pos" if $!verbose;
}
print "\n\n" if $!verbose && self.won;
$!turns++;
}
}
sub MAIN(Int $N = 10, Bool :v(:$verbose) = False)
{
my $total = 0;
for ^$N {
my $game = SnakesAndLadders.new(:$verbose);
$game.turn until $game.won;
$total += $game.turns;
}
say "Average: { $total/$N } turns";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment