Snake and ladder: Difference between revisions

Added Perl example
m (→‎{{header|REXX}}: used an idiomatic method to leave the DO loops, fixed a comment.)
(Added Perl example)
Line 799:
Player 3 wins!
</pre>
 
=={{header|Perl}}==
{{trans|Perl 6}}
<lang># board layout
my %snl =( 4, 14, 9, 31, 17, 7, 20, 38, 28, 84, 40, 59, 51, 67, 54, 34,
62, 19, 63, 81, 64, 60, 71, 91, 87, 24, 93, 73, 95, 75, 99, 78);
 
@players = (1, 1, 1, 1); # 4 players, starting on square 1 (last player is human)
 
while () {
for $player (0..$#players) {
$turn_count++;
turn(\$players[$player], $player + 1, $turn_count);
}
}
 
sub turn {
my($square, $player) = @_;
if ($player == @players) { print "You are on square $$square. Hit enter to roll the die:"; <> }
my $roll = 1 + int rand 6;
my $turn = $$square + $roll;
print "Player $player on square %2d rolls a $roll", $$square;
if ($turn > 100) {
print " but cannot move. Next players turn.\n";
return
}
if ($snl{$turn}) {
$$square = $snl{$turn};
if ($turn > $$square) {
print ". Oops! Landed on a snake. Slither down to $$square.\n"
} else {
print ". Yay! Landed on a ladder. Climb up to $$square.\n"
}
} else {
$$square = $turn;
print " and moves to square $$square\n";
}
if ($$square == 100) {print "Player $player wins after $turn_count turns.\n"; exit }
return
}</lang>
{{out}}
<pre>Player 1 on square 1 rolls a 3. Yay! Landed on a ladder. Climb up to 14.
Player 2 on square 1 rolls a 1 and moves to square 2
Player 3 on square 1 rolls a 5 and moves to square 6
Player 4 on square 1 rolls a 4 and moves to square 5
Player 1 on square 14 rolls a 6. Yay! Landed on a ladder. Climb up to 38.
Player 2 on square 2 rolls a 2. Yay! Landed on a ladder. Climb up to 14.
Player 3 on square 6 rolls a 4 and moves to square 10
Player 4 on square 5 rolls a 3 and moves to square 8
... 703 turns omitted ...
Player 1 on square 83 rolls a 1 and moves to square 84
Player 2 on square 98 rolls a 2 and moves to square 100
Player 2 wins after 706 turns.</pre>
 
=={{header|Perl 6}}==
2,392

edits