Skip to main content

Design a Snake and Ladder game

Problem Statement

Design a Snake and Ladder game where multiple players move across a board based on dice rolls. The game should support snakes and ladders placed at different positions on the board. If a player lands on the start of a ladder, they should climb up to a higher position. If a player lands on the mouth of a snake, they should slide down to a lower position. The game continues until one of the players reaches the final cell on the board.


Functional Requirements

  • The design should support multiple players
  • The board should contain snakes and ladders
  • Players should move based on dice rolls
  • If a player lands on a ladder, they should move upward
  • If a player lands on a snake, they should move downward
  • The game should continue turn by turn
  • The first player to reach the final cell should win the game

Objects Required

  • Board
  • Snake
  • Ladder
  • Dice
  • Player
  • SnakeAndLadderGame

Snake Class

The Snake class represents a snake placed on the board.


public class Snake {

    private int start;
    private int end;

    public Snake(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public int getStart() {
        return start;
    }

    public int getEnd() {
        return end;
    }
}

The constructor initializes the snake with a starting position and an ending position.

The getStart() method returns the snake head position where the player gets bitten.

The getEnd() method returns the destination position where the player finally lands after sliding down.


Ladder Class

The Ladder class represents a ladder placed on the board.


public class Ladder {

    private int start;
    private int end;

    public Ladder(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public int getStart() {
        return start;
    }

    public int getEnd() {
        return end;
    }
}

The constructor initializes the ladder with a starting point and ending point.

The getStart() method returns the ladder position where the player lands.

The getEnd() method returns the higher position the player climbs to.


Player Class

The Player class stores details about each player participating in the game.


public class Player {

    private String name;
    private int position;

    public Player(String name) {
        this.name = name;
        this.position = 0;
    }

    public String getName() {
        return name;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }
}

The constructor initializes the player name and sets the starting position to 0.

The getPosition() method is used whenever the current player position needs to be checked.

The setPosition() method updates the player's location after dice rolls, snakes, or ladders.


Dice Class

The Dice class handles dice rolling logic.


import java.util.Random;

public class Dice {

    private Random random;

    public Dice() {
        this.random = new Random();
    }

    public int rollDice() {
        return random.nextInt(6) + 1;
    }
}

The constructor initializes the random object used for generating dice values.

The rollDice() method returns a random number between 1 and 6 to simulate a real dice roll.


Board Class

The Board class stores snakes, ladders, and board size information.


import java.util.*;

public class Board {

    private int size;
    private List<Snake> snakes;
    private List<Ladder> ladders;

    public Board(int size,
                 List<Snake> snakes,
                 List<Ladder> ladders) {

        this.size = size;
        this.snakes = snakes;
        this.ladders = ladders;
    }

    public int getSize() {
        return size;
    }

    public int getNewPosition(int position) {

        for (Snake snake : snakes) {
            if (snake.getStart() == position) {
                return snake.getEnd();
            }
        }

        for (Ladder ladder : ladders) {
            if (ladder.getStart() == position) {
                return ladder.getEnd();
            }
        }

        return position;
    }
}

The constructor initializes the board with snakes, ladders, and total board size.

The getNewPosition() method checks whether the player has landed on a snake or ladder.

If the current position matches the start of a snake, the player moves downward.

If the current position matches the start of a ladder, the player moves upward.

If no snake or ladder exists at that position, the original position is returned unchanged.


SnakeAndLadderGame Class

The SnakeAndLadderGame class controls the complete game flow.


import java.util.*;

public class SnakeAndLadderGame {

    private Board board;
    private Queue<Player> players;
    private Dice dice;

    public SnakeAndLadderGame(Board board,
                              List<Player> playerList) {

        this.board = board;
        this.players = new LinkedList<>(playerList);
        this.dice = new Dice();
    }

    public void startGame() {

        while (true) {

            Player currentPlayer = players.poll();

            int diceValue = dice.rollDice();

            int newPosition =
                    currentPlayer.getPosition() + diceValue;

            if (newPosition > board.getSize()) {

                players.offer(currentPlayer);
                continue;
            }

            newPosition =
                    board.getNewPosition(newPosition);

            currentPlayer.setPosition(newPosition);

            System.out.println(
                    currentPlayer.getName()
                    + " moved to "
                    + newPosition
            );

            if (newPosition == board.getSize()) {

                System.out.println(
                        currentPlayer.getName()
                        + " won the game"
                );

                break;
            }

            players.offer(currentPlayer);
        }
    }
}

The constructor initializes the board, players, and dice required for the game.

A queue is used to manage player turns in circular order. Once a player's turn is completed, the player is added back to the queue.

The startGame() method contains the main game loop.

Each turn begins by selecting the current player and rolling the dice.

The new position is calculated using the dice value.

If the position exceeds the board size, the move is ignored because the player cannot cross the final cell.

The board is then asked whether the player landed on a snake or ladder, and the final position is updated accordingly.

If the player reaches the last cell, the game ends and the player is declared as the winner.


Main Class

The Main class is used to simulate the Snake and Ladder game.


import java.util.*;

public class Main {

    public static void main(String[] args) {

        List<Snake> snakes = Arrays.asList(
                new Snake(99, 54),
                new Snake(70, 55),
                new Snake(52, 42)
        );

        List<Ladder> ladders = Arrays.asList(
                new Ladder(25, 95),
                new Ladder(6, 45),
                new Ladder(20, 59)
        );

        Board board =
                new Board(100, snakes, ladders);

        List<Player> players = Arrays.asList(
                new Player("Prasanna"),
                new Player("Rahul")
        );

        SnakeAndLadderGame game =
                new SnakeAndLadderGame(board, players);

        game.startGame();
    }
}

The main() method starts by creating snakes and ladders with their respective positions.

The board is then initialized with a size of 100 cells.

Players are added to the game, and finally the game starts using the startGame() method.


Class Diagram

Snakestart : intend : intgetStart() : intgetEnd() : intLadderstart : intend : intgetStart() : intgetEnd() : intPlayername : Stringposition : intgetName() : StringgetPosition() : intsetPosition(position : int) : voidDicerollDice() : intBoardsize : intsnakes : List<Snake>ladders : List<Ladder>getSize() : intgetNewPosition(position : int) : intSnakeAndLadderGameboard : Boardplayers : Queue<Player>dice : DicestartGame() : voidMainmain(args : String[]) : void

Also See

Comments

Popular posts from this blog

Designing a Parking Lot - Low Level Design

Problem Statement Design a parking lot that can handle vehicles entering and leaving while managing parking across multiple floors. Each vehicle should be assigned a suitable parking spot based on its type, and the spot should be freed once the vehicle exits. The design should also support generating a ticket at entry and optionally calculating the parking fee based on the duration of stay. Asked In Companies Amazon Google Microsoft Uber Walmart Flipkart Meta PayPal Oracle Salesforce Adobe Apple Intuit LinkedIn Atlassian Functional Requirements The design should support multiple vehicle types such as bikes, cars, and trucks A vehicle must be assigned a parking spot compatible with its type A parking spot cannot be assigned to more than one vehicle at a time The parking lot should support multiple levels (floors) The design should search and allocate an availa...

Most Frequently Asked Low Level Design(LLD) Interview Questions

Below are the curated list of most commonly asked Low Level Design (LLD) interview problems. Each problem includes a short description and a link to the complete solution with code and class diagrams. Design Parking Lot System The system should handle parking for different vehicle types such as bikes, cars, and trucks. It should manage slot allocation, availability tracking, and entry/exit flow. The design also ensures efficient usage of parking space under varying load conditions. View Solution Design Elevator / Lift System The system should support multiple elevators operating across floors with request handling logic. It focuses on scheduling algorithms to minimize wait time and optimize movement. It also manages direction control and concurrent floor requests. View Solution Design Movie Ticket Booking System The system should allow users to browse movies, select shows, and book seats. It handles seat ...

Software Design Patterns for LLD Interviews: A Complete Guide

Software Design Patterns for LLD Interviews: A Complete Guide In Software Development Engineer (SDE) interviews—especially for mid-level and senior roles—low-level design (LLD) rounds assess your ability to write clean, reusable, maintainable, and extensible code. The foundation of resolving these architectural challenges lies in the standard Gang of Four (GoF) Design Patterns. Rather than memorizing theoretical definitions, interviewers expect you to apply these patterns to real-world scenarios, identifying the trade-offs of each. Below is a comprehensive guide to the 12 most frequently asked design patterns in LLD interviews, categorized by their classification (Creational, Structural, and Behavioral). Each pattern contains a concrete, real-world Java implementation and a detailed breakdown of design decisions. Creational Design Patterns Creational design patterns deal with object creation mechanisms. They abstract the instantiation process, making a system independent of how...