Snake and Ladder Game

"All work and No Play makes Jack a dull boy". Yes friends its time to stop programming and have fun, lets play a game with java. Hope you would have heard about the Snake and Ladder game.

Its just a turn-based board game with numbers from 1 to 100. Some numbers may have ladders pointing up to a greater number and some numbers may have snake pointing to lower number.

A player should roll the dice(1 to 6) and based on the dice output should move his pointer to the particular number on the board. Each player's aim is to reach the end of the board(100). Snakes are road blockers which will drop the users pointer to a lower number. Ladder is the stepping stone to reach greater height(number). It can be played as a single or multiple user game.

The following is the java code for a simple simulation of snake and ladder game.

SLGame Class

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.java;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import java.util.HashMap;

import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;

public class SLGame
{
        int                   boardArray[]           = new int[100];
        int                   snakePointers[][]  = null;
        int                   ladderPointers[][]        = null;
        int                   snakePointersSize  = 0;
        Map<String, User>       userList             = new HashMap<String, User>();
        int                   ladderPointersSize        = 0;
        int                   currentUserIndex   = 0;
        boolean           multiUser              = false;

        public SLGame()
        {
                loadGameBoard();
        }

        public void loadGameBoard()
        {
                for (int i = 0; i < 100; i++)
                {
                        boardArray[i] = i + 1;
                }

                Properties prop = new Properties();
                try
                {
                        prop.load(getClass().getClassLoader().getResourceAsStream("game.properties"));
                }
                catch (FileNotFoundException e)
                {
                        e.printStackTrace();
                }
                catch (IOException e)
                {
                        e.printStackTrace();
                }

                snakePointersSize = Integer.parseInt(prop.getProperty("snake.pointers.total"));

                ladderPointersSize = Integer.parseInt(prop.getProperty("ladder.pointers.total"));

                snakePointers = new int[snakePointersSize][2];

                ladderPointers = new int[ladderPointersSize][2];

                for (int i = 0; i < snakePointersSize; i++)
                {
                        String a[] = prop.getProperty("snake.pointers." + (i + 1)).split(",");
                        snakePointers[i][0] = Integer.parseInt(a[0]);
                        snakePointers[i][1] = Integer.parseInt(a[1]);
                }

                for (int i = 0; i < ladderPointersSize; i++)
                {
                        String a[] = prop.getProperty("ladder.pointers." + (i + 1)).split(",");
                        ladderPointers[i][0] = Integer.parseInt(a[0]);
                        ladderPointers[i][1] = Integer.parseInt(a[1]);
                }
        }

        public void displayGameBoard()
        {
                System.out.println();
                for (int i = 99; i >= 0; i--)
                {
                        if (i == 99)
                        {
                                System.out.print("   ");
                        }

                        System.out.print(boardArray[i]);
                        System.out.print("    ");

                        if (i != 99 && (i) % 10 == 0)
                        {
                                int f = i - 10;
                                for (int k = f; k < i; k++)
                                {
                                        if (k == f)
                                        {
                                                System.out.println();
                                                System.out.print("    ");
                                        }
                                        if (boardArray[k] / 10 == 0)
                                        {
                                                System.out.print(" ");
                                                System.out.print(boardArray[k]);
                                        }
                                        else
                                        {
                                                System.out.print(boardArray[k]);
                                        }
                                        System.out.print("    ");
                                }
                                i = f;
                                System.out.println();
                                System.out.print("    ");
                        }
                }
                displaySLPointers();
        }

        public void displaySLPointers()
        {
                System.out.println();
                System.out.print("Snake Pointers  ");
                for (int i = 0; i < snakePointers.length; i++)
                {
                        System.out.print("[" + snakePointers[i][0] + "->" + snakePointers[i][1] + "] ");
                }
                System.out.println();
                System.out.print("Ladder Pointers  ");
                for (int i = 0; i < ladderPointers.length; i++)
                {
                        System.out.print("[" + ladderPointers[i][0] + "->" + ladderPointers[i][1] + "] ");
                }
                System.out.println();
        }

        public void createSingleUser()
        {
                userList.clear();
                int id = 1;
                User usr = new User(id);
                userList.put("user" + id, usr);
                System.out.println("user" + id + " created successfully");
        }

        public void createMultipleUser()
        {
                userList.clear();
                multiUser = true;
                for (int i = 0; i < 2; i++)
                {
                        int id = i + 1;
                        User usr = new User(id);
                        userList.put("user" + id, usr);
                        System.out.println("user" + id + " created successfully");
                }
        }

        public int rollDice()
        {
                Random rn = new Random();
                int op = rn.nextInt(5) + 1;
                System.out.println("Dice Value is...." + op);
                return op;
        }

        public void playGame()
        {
                int i = 0;
                System.out.println("Game Started.....  ");
                do
                {
                        String curName = getCurrentUserName();
                        System.out
                        .println("1. Roll Dice \n2. Show Positions \n3. Display Board \n4. Stop Game");
                        System.out.println("Chance for User..." + curName);
                        System.out.print("Please provide your option : ");

                        Scanner in = new Scanner(System.in);
                        i = in.nextInt();

                        switch (i)
                        {
                                case 1:
                                        int curPos = this.updateUserPositions(curName);
                                        if (curPos >= 100)
                                        {
                                                System.out
                                                .println(curName + " has successfully won the game. \n Game exit");
                                                return;
                                        }
                                        break;

                                case 2:
                                        this.displayUserPositions();
                                        if (multiUser == true)
                                                currentUserIndex = (currentUserIndex == 2) ? 1 : 0;
                                        break;
                               
                                case 3:
                                        this.displayGameBoard();
                                        if (multiUser == true)
                                                currentUserIndex = (currentUserIndex == 2) ? 1 : 0;
                                        break;
                               
                                case 4:
                                        return;
                        }
                        System.out.println();
                } while (i != 0);
        }

        public int updateUserPositions(String name)
        {
                Set keyset = userList.keySet();
                if (keyset.contains(name))
                {
                        User ur = userList.get(name);
                        ur.setCurrentPosition(checkSLPointersForCurPos(ur.getCurrentPosition()
                                + this.rollDice()));

                        System.out.println(name + " current position is " + ur.getCurrentPosition());
                        return ur.getCurrentPosition();
                }
                return 0;
        }

        public void displayUserPositions()
        {
                Set keyset = userList.keySet();
                Iterator it = keyset.iterator();
                while (it.hasNext())
                {
                        String key = (String) it.next();
                        User us = userList.get(key);
                        System.out.println(key + "current position is...." + us.getCurrentPosition());
                }
        }

        public String getCurrentUserName()
        {
                if (currentUserIndex == 0)
                {
                        currentUserIndex++;
                        return "user" + (currentUserIndex);
                }
                else if (currentUserIndex == 1)
                {
                        if (multiUser == false)
                                return "user" + currentUserIndex;
                        else
                                currentUserIndex++;
                        return "user" + currentUserIndex;
                }
                else
                {
                        currentUserIndex--;
                        return "user" + (currentUserIndex);
                }
        }

        public int checkSLPointersForCurPos(int curPos)
        {
                for (int i = 0; i < snakePointers.length; i++)
                {
                        if (snakePointers[i][0] == curPos)
                        {
                                System.out.println("OOPs!! you have been dropped down by Snake...");
                                return snakePointers[i][1];
                        }
                }

                for (int i = 0; i < ladderPointers.length; i++)
                {
                        if (ladderPointers[i][0] == curPos)
                        {
                                System.out.println("Wow!! you have climbed up the ladder...");
                                return ladderPointers[i][1];
                        }
                }
                return curPos;
        }

        public static void main(String[] args)
        {
                SLGame sl = new SLGame();

                System.out.println("Snake & Ladder Game \n User Options");
                System.out.println("1. Start Game \n2. "
                + "Sinlge Player \n3. Multi Players(only 2) \n4. Exit Game");
                System.out.print("Please provide your option : ");

                int i = 1;

                while (i != 0)
                {
                        Scanner in = new Scanner(System.in);
                        i = in.nextInt();

                        switch (i)
                        {
                                case 1:
                                        if (sl.userList.size() == 0)
                                        {
                                                System.out.println("Please create users and play the game..");
                                                break;
                                        }
                                        else
                                        {
                                                sl.playGame();
                                        }
                                        break;

                                case 2:
                                        sl.createSingleUser();
                                        break;
                               
                                case 3:
                                        sl.createMultipleUser();
                                        break;
                               
                                case 4:
                                        System.exit(0);
                        }

                        System.out.println();
                        System.out.println("Snake & Ladder Game \n Select User Options");
                        System.out.println("1. Start Game \n2. "
                        + "Sinlge Player \n3. Multi Players(only 2) \n4. Exit Game");
                        System.out.print("Please provide your option : ");
                }
        }
}

User.java

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.java

public class User
{

        int     id;

        int     currentPosition = 0;

        public int getCurrentPosition()
        {
                return currentPosition;
        }

        public void setCurrentPosition(int currentPosition)
        {
                this.currentPosition = currentPosition;
        }

        public User(int uId)
        {
                id = uId;
        }
}

game.properties

snake.pointers.total=4
snake.pointers.1=98,21
snake.pointers.2=72,34
snake.pointers.3=57,25
snake.pointers.4=49,17

ladder.pointers.total=4
ladder.pointers.1=11,28
ladder.pointers.2=36,62
ladder.pointers.3=24,49
ladder.pointers.4=51,87

Here is the sample output

Output:

Snake & Ladder Game
 User Options
1. Start Game
2. Single Player
3. Multi Players(only 2)
4. Exit Game
Please provide your option : 1
Please create users and play the game..

Snake & Ladder Game
 Select User Options
1. Start Game
2. Single Player
3. Multi Players(only 2)
4. Exit Game
Please provide your option : 2
user1 created successfully

Snake & Ladder Game
 Select User Options
1. Start Game
2. Single Player
3. Multi Players(only 2)
4. Exit Game
Please provide your option : 1
Game Started.....  
1. Roll Dice
2. Show Positions
3. Display Board
4. Stop Game
Chance for User...user1
Please provide your option : 1
Dice Value is....2
user1 current position is 2

1. Roll Dice
2. Show Positions
3. Display Board
4. Stop Game
Chance for User...user1
Please provide your option : 1
Dice Value is....1
user1 current position is 3

1. Roll Dice
2. Show Positions
3. Display Board
4. Stop Game
Chance for User...user1
Please provide your option : 3

   100    99    98    97    96    95    94    93    92    91    
    81    82    83    84    85    86    87    88    89    90    
    80    79    78    77    76    75    74    73    72    71    
    61    62    63    64    65    66    67    68    69    70    
    60    59    58    57    56    55    54    53    52    51    
    41    42    43    44    45    46    47    48    49    50    
    40    39    38    37    36    35    34    33    32    31    
    21    22    23    24    25    26    27    28    29    30    
    20    19    18    17    16    15    14    13    12    11    
     1     2     3     4     5     6     7     8     9    10    
   
Snake Pointers  [98->21] [72->34] [57->25] [49->17]
Ladder Pointers  [11->28] [36->62] [24->49] [51->87]

1. Roll Dice
2. Show Positions
3. Display Board
4. Stop Game
Chance for User...user1

Happy Gaming!

Technology: 

Search