Snake and ladder: Difference between revisions

Added Wren
(Added Wren)
Line 2,402:
 
End Module</lang>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<lang ecmascript>import "random" for Random
 
var rand = Random.new()
 
var 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
}
 
var sixThrowsAgain = true
 
var turn = Fn.new { |player, square|
while (true) {
var roll = 1 + rand.int(6)
System.write("Player %(player), on square %(square), rolls a %(roll)")
if (square + roll > 100) {
System.print(" but cannot move.")
} else {
square = square + roll
System.print(" and moves to square %(square).")
if (square == 100) return 100
var next = snl[square]
if (!next) next = square
if (square < next) {
System.print("Yay! Landed on a ladder. Climb up to %(next).")
if (next == 100) return 100
square = next
} else if (square > next) {
System.print("Oops! Landed on a snake. Slither down to %(next).")
square = next
}
}
if (roll < 6 || !sixThrowsAgain) return square
System.print("Rolled a 6 so roll again.")
}
}
 
// three players starting on square one
var players = [1, 1, 1]
while (true) {
var i = 0
for (s in players) {
var ns = turn.call(i + 1, s)
if (ns == 100) {
System.print("Player %(i+1) wins!")
return
}
players[i] = ns
System.print()
i = i + 1
}
}</lang>
 
{{out}}
Sample game (abridged):
<pre>
Player 1, on square 1, rolls a 6 and moves to square 7.
Rolled a 6 so roll again.
Player 1, on square 7, rolls a 6 and moves to square 13.
Rolled a 6 so roll again.
Player 1, on square 13, rolls a 5 and moves to square 18.
 
Player 2, on square 1, rolls a 2 and moves to square 3.
 
Player 3, on square 1, rolls a 5 and moves to square 6.
 
Player 1, on square 18, rolls a 6 and moves to square 24.
Rolled a 6 so roll again.
Player 1, on square 24, rolls a 4 and moves to square 28.
Yay! Landed on a ladder. Climb up to 84.
 
Player 2, on square 3, rolls a 4 and moves to square 7.
 
Player 3, on square 6, rolls a 2 and moves to square 8.
 
Player 1, on square 84, rolls a 6 and moves to square 90.
Rolled a 6 so roll again.
Player 1, on square 90, rolls a 5 and moves to square 95.
Oops! Landed on a snake. Slither down to 75.
 
....
 
Player 2, on square 53, rolls a 3 and moves to square 56.
 
Player 3, on square 92, rolls a 4 and moves to square 96.
 
Player 1, on square 39, rolls a 1 and moves to square 40.
Yay! Landed on a ladder. Climb up to 59.
 
Player 2, on square 56, rolls a 3 and moves to square 59.
 
Player 3, on square 96, rolls a 4 and moves to square 100.
Player 3 wins!
</pre>
9,476

edits