Code Pumpkin

Snakes N Ladders | Java Program Implementation

March 31, 2017
Posted by Abhi Andhariya

Snake N Ladder

Snakes N Ladders is an ancient Indian board game regarded today as a worldwide classic.

It is played between two or more players on a gameboard having numbered, gridded squares. A number of "ladders" and "snakes" are pictured on the board, each connecting two specific board squares.

The object of the game is to navigate one's game piece, according to die rolls, from the start (bottom square) to the finish (top square), helped or hindered by ladders and snakes respectively.

The game is a simple race contest based on sheer luck, and is popular with young children.

The historic version had root in morality lessons, where a player's progression up the board represented a life journey complicated by virtues (ladders) and vices (snakes).

If you are interested in java programs for other board games like Tic Tac ToeSudoku SolverSudoku Checker, and N Queen Problem, you can check out my posts in Board Games section.

How to implement this board game using JAVA ?

In SnakeNLadder Java class, we will define constant WINPOINT with value 100. Each player will start their journey from 0, roll Dice and try to win the race by reaching first at WINPOINT.

snake is a static Hashmap which stores key as a starting point of snake and value as tailing point of snake.

similarly, ladder is a static Hashmap which stores key as a lower point of ladder and value as uppoer point of ladder.

I have initialized vlaues of both the Hashmap in static block.

I have written code considering only two players.


import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;

class SnakeNLadder
{
	
	final static int WINPOINT = 100;
	
	
	static Map < Integer , Integer > snake = new HashMap < Integer , Integer >();
	static Map < Integer , Integer > ladder = new HashMap< Integer , Integer >();
	
	{
		snake.put(99,54);
		snake.put(70,55);
		snake.put(52,42);
		snake.put(25,2);
		snake.put(95,72);
		
		ladder.put(6,25);
		ladder.put(11,40);
		ladder.put(60,85);
		ladder.put(46,90);
		ladder.put(17,69);
	}
	
	
//TO-DO Methods

//public int rollDice(){...}
//public int calculatePlayerValue(int player, int diceValue){...}
//public boolean isWin(int player){...}
//public void startGame(){...}
	
}

public class SnakeNLadderTest {

	public static void main(String[] args) {
		SnakeNLadder s = new SnakeNLadder();
		s.startGame();

	}

}

rollDice() method is used to generate a random number between 1 to 6.


public int rollDice()
{
	int n = 0;
	Random r = new Random();
	n=r.nextInt(7);
	return (n==0?1:n);
}

calculatePlayerValue() method calculates the position of the player based on his current position and generated dice value.

It first checks that if new position value is greater than WINPOINT, then it will again set it to old position. In SnakeNLadder to win the race, your final position value must match the WINPOINT. It can't be less or more.

Then it will check for snake and ladder Hashmap. If it finds any key equals to the current position, then it will change the player value to respective Hashmap value.


public int calculatePlayerValue(int player, int diceValue)
{
    player = player + diceValue;
     
    if(player > WINPOINT)
    {
        player = player - diceValue;
        return player;
    }
     
    if(null!=snake.get(player))
    {
        System.out.println("swallowed by snake");
        player= snake.get(player);
    }
     
    if(null!=ladder.get(player))
    {
        System.out.println("climb up the ladder");
        player= ladder.get(player);
    }
    return player;
}


isWin() returns true, if the player value reaches to WINPOINT.


public boolean isWin(int player)
{
    return WINPOINT == player;
}


startGame() method is used to start the game. This method keeps running until any player reaches to WINPOINT.

Players need to press 'r' key to call rollDice() method. currentPlayer keeps on changing after each rollDice() call.


public void startGame()
{
    int player1 =0, player2=0;
    int currentPlayer=-1;
    Scanner s = new Scanner(System.in);
    String str;
    int diceValue =0;
    do
    {
        System.out.println(currentPlayer==-1?"\n\nFIRST PLAYER TURN":"\n\nSECOND PLAYER TURN");
        System.out.println("Press r to roll Dice");
        str = s.next();
        diceValue = rollDice();
         
         
        if(currentPlayer == -1)
        {
            player1 = calculatePlayerValue(player1,diceValue);
            System.out.println("First Player :: " + player1);
            System.out.println("Second Player :: " + player2);
            System.out.println("------------------");
            if(isWin(player1))
            {
                System.out.println("First player wins");
                return;
            }
        }
        else
        {
            player2 = calculatePlayerValue(player2,diceValue);
            System.out.println("First Player :: " + player1);
            System.out.println("Second Player :: " + player2);
            System.out.println("------------------");
            if(isWin(player2))
            {
                System.out.println("Second player wins");
                return;
            }
        }
         
        currentPlayer= -currentPlayer;
         
         
         
    }while("r".equals(str));
}

Download Complete Java Program »

That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.

Happy Learning 🙂

If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.

We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.



About the Author


Surviving Java Developer, Passionate Blogger, Table Tennis Lover, Bookworm, Occasional illustrator and a big fan of Joey Tribbiani, The Walking Dead and Game of Thrones...!!



Tags: , , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.
Total Posts : 124
follow us in feedly

Like Us On Facebook