Snake and Ladder is a popular game that originated in India and later spread to other parts of the world. Even now it is a hit among kids in South India, where people use the traditional game board, coins and dice.
Last week, I had a chance to play this game with my 5-year-old granddaughter, who was visiting us, and it was great fun! A wonderful way to relax in the present stressful Covid situation!
After she left, I decided to implement the game in Prolog. Today’s article is about the implementation. I will share the source code at the end of the article.
Here is the game board.
There are 100 “Cells” numbered 1 to 100. There are a few Snakes and Ladders that connect cell pairs. When a player reaches a cell that has the head of a snake, he will have to slide down the snake and move to the cell that has the tip of the tail. On the other hand, if a player reaches the bottom of a ladder, he has to climb up the ladder and reach the cell at the top of the ladder.
Usually 3 or 4 players play the game, but 2 is the minimum. At the start of the game, players agree upon the order in which they will play. The game board we used came with two traditional metal dice. In order to “open” the game, a player must get “1” when rolling the dice. If he gets 5, 6 or 12, then he will roll the dice again. Any other value (2, 3, 4) will transfer control to the next player in the agreed order.
The first player to reach 100, or cross it, is the winner (by the way, there are minor variations of the game, but what I present is what I played).
Here is the code that defines the board:
I could have hard-coded the start and end positions as 1 and 100 respectively, but I chose to keep it flexible.
How to model the dice and rolling the dice? Here is the code fragment:
Deciding the order in which the players will play and choosing the “next” player at any point in time are handled by the following clauses:
Initialization and the main “play” loop are given below:
The logic to handle specific dice values when a player rolls the dice is implemented in these clauses:
Moving the coin and associated special handling for snakes and ladders is shown below:
I have covered the core logic. Let us run the program and see how it performs. I have implemented this program in Sicstus prolog 4.6.0 on my Windows 10 machine. Here is the output generted when I run the game in the IDE:
What is weird in this case is that only “p2” managed to open the game. The other two did not get the mandatory “1” to open the game. Because of randomness in selecting players and rolling the dice, the output is likely to change each time we run the program. Here is another run:
Fortunately, in this run, all three players managed to open the game, but “p1” won finally.
Well, it was interesting to implement the game in Prolog! You can download the source here.
Have a nice weekend!
Recent Comments