SyntaxPilot
Courses/Low-Level Design/Lesson 58
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 58 of 90

Design Snake and Ladder

BoardSnakeLadderDicemultiple dicePlayerGame loopposition jumpsboard configurationrandom seeding for testsgame rules extensibilitywinning conditions

These are the notes for Low-Level Design (LLD) episode 58. Last episode we designed Tic-Tac-Toe, our first full machine-coding problem. Snake and Ladder adds two things Tic-Tac-Toe never had: a board that comes from configuration (data, not code), and dice, which means randomness. Randomness raises a hard question: how do you test a game that never plays the same way twice? We start with the obvious code and watch it break, then build the design: Board, Snake, Ladder, Dice, Player and Game, position jumps in O(1) with a map, a board that validates its configuration, random seeding for tests, multiple dice, the game loop with a queue of players, winning conditions, and game rules extensibility with swappable move rules.

How the code was run: every program with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly as printed (exceptions and stack traces included). Programs that use an unseeded new Random() give different numbers on every run; for those we show one real run and say so.

1. The problem (the brief)

Snake and Ladder is a board game for two or more players.

  • The board has cells numbered 1 to 100. Every player starts outside the board, at position 0.
  • On your turn you roll the dice and move forward that many cells.
  • Land on the bottom of a ladder and you climb to its top. Land on the head of a snake and you slide down to its tail.
  • The first player to reach cell 100 wins.

As in every machine-coding round (episode 55), we clarify before we code:

Question Our assumption
Is the board always 100 cells? No: any size (we will use 30 cells so a whole game fits on screen)
Where are the snakes and ladders? Given as data (a board configuration), not fixed in code
How many dice? k dice (one by default, two is a common follow-up)
What if you are on 98 and roll a 5 (an overshoot: a roll that goes past the last cell)? Exact landing: you need the exact number to finish, otherwise you stay. But this rule must be easy to change
How many players? Two or more, taking turns in a fixed order
Do we need a screen? No: a console demo with a main method

2. The real-life idea: a Sunday game

Picture a Sunday afternoon. Asha and Ravi play Snake and Ladder on a cardboard board, with one dice and two coins as their pieces.

  1. Ravi lands on 99, right on a snake's head, and just sits there: "I didn't see any snake there!" Nobody checked the rules.
  2. Next turn he is on 99 and rolls a 5: 104. "That's past 100, so I win!" Is that allowed? Nobody wrote the overshoot rule down.
  3. Asha wants the game replayed to check. Nobody can: real dice never fall the same way twice. The game can't be replayed.

Three real problems. Each will show up as a real bug in the obvious code, and the fix for each comes from the cardboard game too:

On the table In the design
The printed board: its cells, and where each snake and ladder is Board: a size plus a map from start cell to end cell
A snake (head → tail) and a ladder (bottom → top), each joining two cells Snake and Ladder: tiny records, both a kind of Jump
The dice, which gives a number from 1 to 6 Dice: an interface with one method, int roll()
Each coin, sitting on a cell Player: a name and a position
"Whose turn is it?" going round the table, and the rules Game: a queue of players, the dice, the rules, the winner
The house rule for rolling past 100 MoveRule: an interface, so the rule can be swapped

3. The obvious way, and how it breaks

Everything in main: two ints for the positions, an array of rolls (typed in by hand), and a chain of ifs for the snakes and ladders, copied once per player. This is a saved game: Asha starts at 0 and Ravi is already on 93.

public class Main {
    public static void main(String[] args) {
        int asha = 0, ravi = 93;                       // a saved game: Ravi is near the end
        int[] rolls = {4, 6, 3, 5};                    // Asha, Ravi, Asha, Ravi
        for (int i = 0; i < rolls.length; i++) {
            if (i % 2 == 0) {                          // Asha's turn
                asha += rolls[i];
                if (asha == 4) asha = 14;              // ladders
                if (asha == 28) asha = 84;
                if (asha == 17) asha = 7;              // snakes
                if (asha == 99) asha = 54;
                System.out.println("Asha rolls " + rolls[i] + " -> " + asha);
                if (asha >= 100) { System.out.println("Asha wins at " + asha); break; }
            } else {                                   // Ravi's turn (copy-pasted)
                ravi += rolls[i];
                if (ravi == 4) ravi = 14;              // ladders
                if (ravi == 28) ravi = 84;
                if (ravi == 17) ravi = 7;              // snakes
                System.out.println("Ravi rolls " + rolls[i] + " -> " + ravi);
                if (ravi >= 100) { System.out.println("Ravi wins at " + ravi); break; }
            }
        }
    }
}

Output:

Asha rolls 4 -> 14
Ravi rolls 6 -> 99
Asha rolls 3 -> 7
Ravi rolls 5 -> 104
Ravi wins at 104

Reading it line by line:

  • i % 2 == 0: % is the remainder operator. i % 2 is 0 for even i (0, 2: Asha's turns) and 1 for odd i (1, 3: Ravi's turns).
  • Asha rolls 4 and lands on 4, a ladder bottom: she climbs to 14. Correct.
  • Ravi rolls 6: 93 + 6 = 99, a snake's head. He should slide to 54, but he stays on 99. In Ravi's copy of the if chain, the line if (ravi == 99) ravi = 54; was never pasted. A copy-paste bug.
  • Asha rolls 3: 14 + 3 = 17, a snake: down to 7. Correct.
  • Ravi rolls 5: 99 + 5 = 104, and ravi >= 100 says he won. "Ravi wins at 104": a cell that doesn't even exist. There is no overshoot rule.

Why it failed

  1. The snakes and ladders are hard-coded as if statements (written straight into the code), and duplicated once per player, so one copy went wrong.
  2. There is no rule for rolling past the last cell; >= 100 silently treats an overshoot as a win.
  3. Players, turns, the board and the dice are all tangled inside main. A third player means a third copy.
  4. The rolls were typed in by hand. With real dice, every run would be different, so you could not even repeat a bug to fix it: the code is untestable.

The fix starts the same way as last episode: the nouns in the brief become classes (noun analysis, episode 20: board, snake, ladder, dice, player, game). And one big idea: the snakes and ladders become data that the board reads, not code that someone copies.

4. The model: six classes, each owns one job

Class Kind Owns
Jump interface "Move from one cell to another": from() and to()
Snake record, a Jump A head and a tail; must go down
Ladder record, a Jump A bottom and a top; must go up
Board class Its size, and a map of every jump; checks the configuration
Dice interface "Give me a number": int roll()
MoveRule interface What a roll does to a position, including an overshoot
Player class A name and a position
Game class The board, the dice, the rule, the turn queue; runs the game loop

Why these kinds? (Both came up last episode; here they are again in plain words.)

  • A record is a short class whose only job is to carry values. You write record Snake(int head, int tail) {} and Java writes the constructor, the getter methods head() and tail(), equals, hashCode and toString for you. That's why a ladder prints as Ladder[bottom=90, top=120].
  • An interface is a contract: a list of methods a class promises to have. class Ladder implements Jump means "Ladder promises to have from() and to()". Code that only needs "some jump" can accept any class that implements Jump.

The class diagram

Game ──owns──▶ Board ──holds──▶ Jump (interface)
 │                                 ├─ Snake  (head → tail, down)
 │                                 └─ Ladder (bottom → top, up)
 ├──uses──▶ Dice (interface)      ── RandomDice · FixedDice
 ├──uses──▶ MoveRule (interface)  ── ExactLanding · BounceBack
 └──turns─▶ Queue of Player (name, position)

Read it as: the Game owns the Board; the Board holds jumps, and a jump is either a Snake (going down) or a Ladder (going up): both are the same kind of thing, "move from one cell to another". The Game uses a Dice, which is an interface: RandomDice for real games, FixedDice for tests. It uses a MoveRule, which decides what an overshoot does: ExactLanding or BounceBack. And the turns are a queue of players, each with a name and a position.

5. Board configuration: snakes and ladders as data

Board configuration means the board's setup given as data instead of code. For our 100-cell board:

size    = 100
ladders = [4 → 14, 28 → 84]
snakes  = [17 → 7, 99 → 54]

A different board is just different data: no code changes. (Later the same data can come from a file; the mini project reads it from text.)

Snake and Ladder are both a Jump

A snake and a ladder do the same thing: take you from one cell to another. So both implement Jump, with a from() and a to(). A snake's to is lower than its from; a ladder's is higher. The board doesn't care which is which.

A map for position jumps: O(1)

A position jump is what happens after you land: if a snake or ladder starts on your cell, you move to its end. The board keeps a Map<Integer, Integer> from start cell to end cell.

  • A Map stores key → value pairs and finds a value by its key: {4=14, 17=7, 28=84, 99=54}. Ask for key 4, you get 14.
  • HashMap is the usual Map class. It uses each key's hash code (a number computed from the key) to go almost straight to the right slot, instead of searching through every entry.
  • getOrDefault(key, fallback) returns the value for key, or fallback if the key isn't in the map.

So the whole jump rule is one line: jumps.getOrDefault(pos, pos). Land on 4: the map has 4, jump to 14. Land on 50: not in the map, stay on 50.

Big-O notation describes how the work grows as the input grows. O(1) ("constant time") means the work stays the same however big the input is; O(n) means it grows in step with n. A HashMap lookup is O(1) on average: one lookup per move, whether the board has 4 jumps or 400. Keeping the jumps in a list and scanning it every move would be O(number of jumps).

Data can be wrong: validate it

Bad setups the board must refuse before the game starts:

  • a snake that goes up, or a ladder that goes down,
  • a jump off the board (starting on cell 1 or below, starting on the last cell or beyond, or ending past the last cell),
  • two jumps on one cell (which one wins?),
  • a chain: a jump that ends exactly where another starts (a ladder from 4 up to 17 where a snake's head is: do you then slide? Chains make the result depend on how the code is written, so we forbid them).

6. A board that checks itself (the video's program)

import java.util.*;   interface Jump { int from(); int to(); }            // a snake or a ladder
record Snake(int head, int tail) implements Jump {
    Snake { if (tail >= head) throw new IllegalArgumentException("snake must go down: " + head + "->" + tail); }
    public int from() { return head; }   public int to() { return tail; } }
record Ladder(int bottom, int top) implements Jump {
    Ladder { if (top <= bottom) throw new IllegalArgumentException("ladder must go up: " + bottom + "->" + top); }
    public int from() { return bottom; }   public int to() { return top; } }
class Board {
    final int size;  private final Map<Integer, Integer> jumps = new HashMap<>();    // start cell -> end cell
    Board(int size, List<Jump> list) {
        this.size = size;
        for (Jump j : list) {
            if (j.from() <= 1 || j.from() >= size || j.to() > size) fail("off the board: " + j);
            if (jumps.containsKey(j.from())) fail("two jumps start at " + j.from());
            jumps.put(j.from(), j.to());
        }
        for (int end : jumps.values())                        // no chains: an end is never a start
            if (jumps.containsKey(end)) fail("a jump ends on " + end + ", where another jump starts");
    }
    int jump(int pos) { return jumps.getOrDefault(pos, pos); }            // O(1): one map lookup
    static void fail(String why) { throw new IllegalArgumentException(why); }
}
public class Main { public static void main(String[] args) {
    Board b = new Board(100, List.of(new Ladder(4, 14), new Ladder(28, 84), new Snake(17, 7), new Snake(99, 54)));
    System.out.println("land on 4 -> " + b.jump(4) + ",  on 99 -> " + b.jump(99) + ",  on 50 -> " + b.jump(50));
    new Board(100, List.of(new Ladder(4, 17), new Snake(17, 7)));          // a ladder up to a snake's head
}}

Output:

land on 4 -> 14,  on 99 -> 54,  on 50 -> 50
Exception in thread "main" java.lang.IllegalArgumentException: a jump ends on 17, where another jump starts
    at Board.fail(Main.java:21)
    at Board.<init>(Main.java:18)
    at Main.main(Main.java:26)

What every part does:

  • Snake { ... } with no brackets after the name is a compact constructor: a record's constructor in short form. It runs before the fields are set, so it can check the values and refuse them. Here, a snake whose tail isn't below its head throws an exception. Ladder does the same check the other way round.
  • public int from() { return head; }: methods that implement an interface must be public.
  • throw new IllegalArgumentException(...): an exception is Java's way of stopping normal flow and saying "this should not happen". IllegalArgumentException is the standard one for "you passed a bad argument". If nobody catches it, Java prints its message and the stack trace: the chain of method calls that led there, newest first, with line numbers. Board.<init> means "the Board constructor" (<init> is how Java names a constructor in a stack trace).
  • List.of(a, b, c) makes a small fixed list. for (Jump j : list) visits each item.
  • jumps.containsKey(k) asks "is k a key?"; jumps.put(k, v) adds a pair; jumps.values() gives every value (every end cell).
  • fail is a tiny helper so each check is one short line.

The good board answers: land on 4 → 14 (ladder), on 99 → 54 (snake), on 50 → 50 (no jump). The bad board is refused: the ladder 4 → 17 ends on 17, where the snake starts. The broken board never reaches a player.

Every validation, one at a time

This extra program keeps the same Jump, Snake, Ladder and Board (unchanged, above) and tries five boards, catching each refusal with try/catch so they all print. e.getMessage() is the text the exception was created with.

import java.util.*;   interface Jump { int from(); int to(); }            // a snake or a ladder
record Snake(int head, int tail) implements Jump {
    Snake { if (tail >= head) throw new IllegalArgumentException("snake must go down: " + head + "->" + tail); }
    public int from() { return head; }   public int to() { return tail; } }
record Ladder(int bottom, int top) implements Jump {
    Ladder { if (top <= bottom) throw new IllegalArgumentException("ladder must go up: " + bottom + "->" + top); }
    public int from() { return bottom; }   public int to() { return top; } }
class Board {
    final int size;  private final Map<Integer, Integer> jumps = new HashMap<>();    // start cell -> end cell
    Board(int size, List<Jump> list) {
        this.size = size;
        for (Jump j : list) {
            if (j.from() <= 1 || j.from() >= size || j.to() > size) fail("off the board: " + j);
            if (jumps.containsKey(j.from())) fail("two jumps start at " + j.from());
            jumps.put(j.from(), j.to());
        }
        for (int end : jumps.values())                        // no chains: an end is never a start
            if (jumps.containsKey(end)) fail("a jump ends on " + end + ", where another jump starts");
    }
    int jump(int pos) { return jumps.getOrDefault(pos, pos); }            // O(1): one map lookup
    static void fail(String why) { throw new IllegalArgumentException(why); }
}
public class Main {
    static void tryBoard(String label, List<Jump> jumps) {
        try { new Board(100, jumps); System.out.println(label + ": OK"); }
        catch (IllegalArgumentException e) { System.out.println(label + ": " + e.getMessage()); }
    }
    public static void main(String[] args) {
        tryBoard("good board     ", List.of(new Ladder(4, 14), new Snake(17, 7)));
        tryBoard("off the board  ", List.of(new Ladder(90, 120)));
        tryBoard("two on one cell", List.of(new Ladder(4, 14), new Snake(4, 2)));
        tryBoard("chain          ", List.of(new Ladder(4, 17), new Snake(17, 7)));
        tryBoard("snake going up ", List.of(new Snake(10, 60)));
    }
}

Output:

good board     : OK
off the board  : off the board: Ladder[bottom=90, top=120]
two on one cell: two jumps start at 4
chain          : a jump ends on 17, where another jump starts
Exception in thread "main" java.lang.IllegalArgumentException: snake must go down: 10->60
    at Snake.<init>(Main.java:3)
    at Main.main(Main.java:33)

Look at the last line. The "snake going up" was not caught by tryBoard: the stack trace shows it was thrown in Snake.<init> called straight from main. That's because new Snake(10, 60) runs while building the list, before tryBoard (and its try) is even called. The record's compact constructor refuses a bad snake the moment it is created: a bad Snake object can never exist at all.

7. Dice a computer can roll: pseudo-random numbers and seeds

Now Ravi's last complaint: you can't replay a dice game. A computer rolls dice with java.util.Random, a pseudo-random number generator.

  • Random (as in real dice): nobody can predict the next number.
  • Pseudo-random: looks random but isn't. It's a formula: each number is calculated from the one before. The numbers only look random. (java.util.Random's formula is written down in Java's own documentation, so it gives the same numbers on every Java installation.)
  • The seed is the starting number the formula begins from. Same seed → same sequence, every time.
  • new Random() with nothing inside: Java picks a different seed for you each time (from the clock and a counter), so every run gives different numbers.
  • new Random(42): you chose the seed, so you get the exact same sequence on every run.
  • rnd.nextInt(6) gives a whole number from 0 to 5. So 1 + rnd.nextInt(6) gives 1 to 6: one dice.

Random seeding for tests means giving the random generator a fixed seed so a "random" run can be repeated exactly: to reproduce a bug, to check a fix, or to replay a game.

import java.util.Random;
public class Main {
    static String eightRolls(Random r) {                     // eight throws of one dice
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < 8; i++) s.append(1 + r.nextInt(6)).append(' ');
        return s.toString();
    }
    public static void main(String[] args) {
        System.out.println("new Random():    " + eightRolls(new Random()));     // seed from the clock
        System.out.println("new Random(42):  " + eightRolls(new Random(42)));   // a fixed seed
        System.out.println("new Random(42):  " + eightRolls(new Random(42)));   // same seed again
    }
}

Output, first run (the first line is unseeded, so yours will be different, and it changes every run):

new Random():    2 2 4 3 3 1 6 6 
new Random(42):  3 4 1 3 1 2 6 3 
new Random(42):  3 4 1 3 1 2 6 3 

Output, second run of the same program:

new Random():    3 4 3 3 1 2 3 4 
new Random(42):  3 4 1 3 1 2 6 3 
new Random(42):  3 4 1 3 1 2 6 3 

The first line changed. The two seed-42 lines never change: 3 4 1 3 1 2 6 3, on every run, on every machine. Seed it, and a dice game becomes a game you can replay.

(StringBuilder is Java's class for building a string piece by piece with append; toString() gives the finished string. Each line ends with a space because append(' ') runs after every roll.)

8. Multiple dice: two dice are not one big dice

A classic follow-up: "Now play with two dice." The total is 2 to 12. Is that just a random number from 2 to 12? No.

Two dice have 6 × 6 = 36 equally likely results (first dice, second dice):

Total Ways Chance
2 1+1 1 of 36
3 1+2, 2+1 2 of 36
4 1+3, 2+2, 3+1 3 of 36
5 4 ways 4 of 36
6 5 ways 5 of 36
7 1+6, 2+5, 3+4, 4+3, 5+2, 6+1 6 of 36 = 1 in 6
8 5 ways 5 of 36
9 4 ways 4 of 36
10 3 ways 3 of 36
11 2 ways 2 of 36
12 6+6 1 of 36

Picking one random number from 2 to 12 would make 2 exactly as common as 7. That's not how dice behave. Multiple dice means: roll each dice and add them up. Let's prove it with 36,000 throws.

import java.util.Random;
public class Main {
    public static void main(String[] args) {
        Random rnd = new Random(1);                              // seeded: the same counts on every run
        int[] count = new int[13];                               // count[s] = how often the total was s
        for (int i = 0; i < 36000; i++) count[(1 + rnd.nextInt(6)) + (1 + rnd.nextInt(6))]++;   // two dice
        for (int sum = 2; sum <= 12; sum++)
            System.out.printf("%2d: %5d  %s%n", sum, count[sum], "#".repeat(count[sum] / 200));
    }
}

Output:

 2:  1060  #####
 3:  2036  ##########
 4:  3033  ###############
 5:  3871  ###################
 6:  5032  #########################
 7:  5898  #############################
 8:  4923  ########################
 9:  4046  ####################
10:  3034  ###############
11:  2062  ##########
12:  1005  #####
  • int[] count = new int[13]: slots 0 to 12; we use 2 to 12 so that count[total] is the slot for that total. count[...]++ adds 1 to that slot.
  • printf prints with a format string: %2d is a number padded to 2 characters, %5d to 5, %s a string, %n a new line.
  • "#".repeat(n) makes a string of n # characters: one # per 200 throws, a little bar chart.

Seven is the tallest: 5,898, close to the expected 6,000 (one sixth of 36,000). Two and twelve are the shortest, about 1,000 each (one in 36). A triangle, exactly what the table said. Because the generator is seeded with 1, you get these same counts on every run.

9. The game loop and winning conditions

The game loop is the heart of every game: one turn, repeated until somebody wins. One turn is:

next player ─▶ roll ─▶ move ─▶ jump ─▶ won?
(front of queue) (Dice) (MoveRule) (Board) (pos == size)
  • Turn order is a queue. A queue is a line where you take from the front and add at the back ("first in, first out", like a ticket counter). Take the player at the front; after their turn, put them at the back. With a queue, three or four players work with no extra code.
  • Java's queue here is a Deque ("double-ended queue": you can add or remove at both ends), using the class ArrayDeque. poll() removes and returns the front; offer(p) adds p at the back; addFirst(p) puts p back at the front (the mini project uses it for "a six gives another turn").
  • The overshoot rule gets its own owner: a MoveRule interface, int next(int pos, int roll, int size). Our first rule is ExactLanding: if the roll would take you past the end, you stay where you are.
  • Winning condition: the rule that decides when a player has won. Ours: you win when you are exactly on the last cell (p.pos == board.size()), never "at or past" it.

10. The full game (the video's program)

import java.util.*;
interface Dice { int roll(); }                                         // anything that gives a number
class RandomDice implements Dice {                                     // k dice, each 1..6, added up
    private final int k; private final Random rnd;
    RandomDice(int k, Random rnd) { this.k = k; this.rnd = rnd; }
    public int roll() { int s = 0; for (int i = 0; i < k; i++) s += 1 + rnd.nextInt(6); return s; } }
interface MoveRule { int next(int pos, int roll, int size); }          // what to do with a roll
class ExactLanding implements MoveRule { public int next(int p, int r, int n) { return p + r > n ? p : p + r; } }
class Player { final String name; int pos = 0; Player(String name) { this.name = name; } }
record Board(int size, Map<Integer, Integer> jumps) { int jump(int pos) { return jumps.getOrDefault(pos, pos); } }
class Game { final Board board; final Dice dice; final MoveRule rule; final Deque<Player> turns;  // turns: a queue
    Game(Board b, Dice d, MoveRule r, List<Player> ps) {
        board = b; dice = d; rule = r; turns = new ArrayDeque<>(ps); }
    Player playTurn() {                                                // one turn of one player
        Player p = turns.poll();  int roll = dice.roll();
        int landed = rule.next(p.pos, roll, board.size()), end = board.jump(landed);
        String note = end > landed ? "  ladder!" : end < landed ? "  snake!" : "";
        System.out.printf("%-4s rolls %d: %2d -> %2d%s%n", p.name, roll, p.pos, end, note);
        p.pos = end;  turns.offer(p);  return p;                       // back of the queue: next player's turn
    }
    Player play() { while (true) { Player p = playTurn(); if (p.pos == board.size()) return p; } }  // game loop
}
public class Main { public static void main(String[] args) {
    Board board = new Board(30, Map.of(3, 22, 5, 8, 11, 26, 20, 29, 17, 4, 19, 7, 21, 9, 27, 1));   // 30 cells
    Game game = new Game(board, new RandomDice(1, new Random(19)), new ExactLanding(),
                         List.of(new Player("Asha"), new Player("Ravi")));
    System.out.println("Winner: " + game.play().name);
}}

Output (seeded with 19, so it is the same on every run):

Asha rolls 6:  0 ->  6
Ravi rolls 3:  0 -> 22  ladder!
Asha rolls 3:  6 ->  9
Ravi rolls 1: 22 -> 23
Asha rolls 5:  9 -> 14
Ravi rolls 6: 23 -> 29
Asha rolls 3: 14 ->  4  snake!
Ravi rolls 4: 29 -> 29
Asha rolls 3:  4 ->  7
Ravi rolls 5: 29 -> 29
Asha rolls 5:  7 -> 12
Ravi rolls 1: 29 -> 30
Winner: Ravi

The parts:

  • Dice has one method, roll(). RandomDice(k, rnd) rolls k dice, each 1 to 6, and adds them up. It is given its Random from outside, so whoever creates it chooses the seed.
  • ExactLanding.next uses the ternary operator condition ? a : b ("if condition then a, else b"): if p + r > n (past the end) stay on p, else move to p + r.
  • Player is a name (final: set once, never changed) and a position that starts at 0.
  • Board is now a short record holding the size and the jumps map. To keep the screen short it skips the checks from section 6; in a real solution you keep them (the mini project does).
  • Map.of(3, 22, 5, 8, ...) builds a fixed map from pairs: key 3 → 22, key 5 → 8, and so on. The 30-cell board has ladders 3→22, 5→8, 11→26, 20→29 and snakes 17→4, 19→7, 21→9, 27→1.
  • Game is given its board, dice, rule and players in its constructor. new ArrayDeque<>(ps) puts the players in a queue in that order.
  • playTurn is one turn: take the front player (poll), roll, apply the rule (landed), apply any jump (end), print (with "ladder!" if end went up, "snake!" if down), update the position, put the player at the back (offer). %-4s pads the name to 4 characters, left-aligned.
  • play is the game loop: while (true) (repeat forever) one turn after another, and return the player as soon as one is exactly on the last cell.

Following the game: Ravi rolls 3, lands on 3 and climbs to 22. Asha goes 9 → 14, then rolls 3: 17 is a snake, down to 4. Ravi reaches 29, then rolls 4 (33, past 30) and stays, then 5, and stays again: exact landing. Finally he rolls a 1: exactly 30. Winner, Ravi. And because of seed 19, this exact game replays on every run.

11. How do you test a dice game?

The interviewer says: "Prove that a roll past the end is handled right."

  • A seed gives you a repeatable game, but you must hunt for a seed that happens to hit that exact case, and if anyone changes how the dice are used, the seed stops hitting it.
  • Better: a FixedDice, a fake dice for tests that plays a script of rolls you choose: 3, then 2, then 6. Your test decides exactly what happens. (A fake object like this, used in place of the real one in a test, is often called a test double.)
  • This works only because the Game takes any Dice through its constructor, instead of creating a new Random() inside itself. That's dependency injection (episode 16): an object is given the things it depends on, from outside, instead of creating them itself. Here it is what makes the game testable.

Game rules extensibility

Game rules extensibility means adding or changing a rule by adding a new class, without editing the game's code. Want a different overshoot rule? Write a new MoveRule. BounceBack: if you roll past the end, walk back the extra steps. On a 30-cell board, 28 + 5 = 33 is 3 past 30, so you end on 30 − 3 = 27. The Game class doesn't change at all.

Dice and MoveRule are both the Strategy pattern (episode 34): a family of interchangeable algorithms (ways to roll, ways to move) behind one interface, chosen when the object is built.

12. Tests: a fixed dice and two rules (the video's program)

The top of the file is everything from before, folded into fewer lines (the same classes; Game's fields are just named shorter).

import java.util.*;            // Dice, MoveRule, ExactLanding, Player, Board and Game: as before, folded up
interface Dice { int roll(); }   interface MoveRule { int next(int pos, int roll, int size); }
class ExactLanding implements MoveRule { public int next(int p, int r, int n) { return p + r > n ? p : p + r; } }
class Player { final String name; int pos = 0; Player(String name) { this.name = name; } }
record Board(int size, Map<Integer, Integer> jumps) { int jump(int pos) { return jumps.getOrDefault(pos, pos); } }
class Game { final Board b; final Dice d; final MoveRule rule; final Deque<Player> q;
    Game(Board b, Dice d, MoveRule r, List<Player> ps) {
        this.b = b; this.d = d; rule = r; q = new ArrayDeque<>(ps); }
    Player playTurn() { Player p = q.poll(); int roll = d.roll(), end = b.jump(rule.next(p.pos, roll, b.size()));
        System.out.printf("%-4s rolls %d: %2d -> %2d%n", p.name, roll, p.pos, end);
        p.pos = end; q.offer(p); return p; }
    Player play() { while (true) { Player p = playTurn(); if (p.pos == b.size()) return p; } } }
class FixedDice implements Dice {                                     // a dice for tests: plays a script
    private final int[] script; private int i = 0;   FixedDice(int... script) { this.script = script; }
    public int roll() { return script[i++ % script.length]; } }
class BounceBack implements MoveRule {                                // past the end? bounce back the extra steps
    public int next(int pos, int roll, int size) { int t = pos + roll; return t > size ? size - (t - size) : t; } }
public class Main { static void check(boolean ok, String t) { System.out.println((ok ? "PASS  " : "FAIL  ") + t); }
    public static void main(String[] args) {
        Board board = new Board(30, Map.of(3, 22, 5, 8, 11, 26, 20, 29, 17, 4, 19, 7, 21, 9, 27, 1));
        Player asha = new Player("Asha"), ravi = new Player("Ravi");
        Game g1 = new Game(board, new FixedDice(3, 2, 6, 2, 2), new ExactLanding(), List.of(asha, ravi));
        check(g1.play() == asha, "exact landing: Asha wins with 3, 6, 2");
        Player a = new Player("Asha"), r = new Player("Ravi");
        Game g2 = new Game(board, new FixedDice(3, 2, 6, 2, 5), new BounceBack(), List.of(a, r));
        for (int t = 0; t < 5; t++) g2.playTurn();
        check(a.pos == 1, "bounce back: 28 + 5 = 33, back to 27, snake to 1");
}}

Output:

Asha rolls 3:  0 -> 22
Ravi rolls 2:  0 ->  2
Asha rolls 6: 22 -> 28
Ravi rolls 2:  2 ->  4
Asha rolls 2: 28 -> 30
PASS  exact landing: Asha wins with 3, 6, 2
Asha rolls 3:  0 -> 22
Ravi rolls 2:  0 ->  2
Asha rolls 6: 22 -> 28
Ravi rolls 2:  2 ->  4
Asha rolls 5: 28 ->  1
PASS  bounce back: 28 + 5 = 33, back to 27, snake to 1
  • FixedDice(int... script): int... is a varargs parameter: the caller can pass any number of ints (new FixedDice(3, 2, 6, 2, 2)) and the method receives them as an array.
  • script[i++ % script.length]: return the next roll, then move i on (i++ uses i, then adds 1). % script.length wraps round to the start if the script runs out.
  • BounceBack.next: t is the target. If t > size, the extra is t - size, so go back that much from the end: size - (t - size).
  • check prints PASS or FAIL with a description: a tiny unit test (a small automatic check of one piece of behaviour, with a known expected answer).
  • g1.play() == asha: with objects, == asks "is it the same object?", which is exactly what we want: the winner is the very Player object we called asha.

Test one: Asha rolls 3 (ladder to 22), then 6 to 28, then 2: exactly 30. PASS. Test two: the same start, then a 5 from 28 would be 33; bounce back 3 steps to 27, which is a snake, down to 1. PASS. (Notice the printed line shows the final cell, 1, after the rule and the jump.) A dice game you can test, and a rule you swapped without touching Game.

13. Interview follow-ups

Follow-up Answer
A six gives another turn A turn rule: after a 6, don't put the player at the back; put them at the front again (addFirst). The mini project does this
Play until the last player Keep a list of winners; a player who finishes leaves the queue; stop when one player is left (mini project)
Two dice + exact landing A trap: on 99 you need a 1, which two dice can never roll, so the game can never end. Validate that the rules fit the dice (next section)
Load the board from a file That's why the board is data: read lines like ladder 3 22 and build the same Board (mini project reads it from text)
Special cells (skip a turn, teleport) Generalise Jump into a cell effect: an interface apply(player, game); a snake and a ladder become two effects among many
Replay a finished game Store its seed, or the list of rolls (wrap the dice in a recording dice, then replay with FixedDice: practice question 4)
Three or four players Already works: the queue takes any number of players
Many games at once on a server A Game per match, each with its own Dice; never one shared static game

14. The two-dice + exact-landing trap

With two dice the smallest roll is 2. Under exact landing, a player on cell 99 of 100 (or 29 of 30) needs exactly a 1, which two dice can never roll. Every roll overshoots, the player stays on 99 for ever, and if every player gets stuck, the game loop while (true) never ends: an infinite loop (a loop with no way out). The narration admits this exact infinite loop happened while the episode was being prepared.

To show it safely, this program puts a turn cap on the loop (a maximum number of turns, a safety net so the program always stops). It's a saved game where both players are already on 29 of 30, with two dice seeded with 5. There are no snakes or ladders, to keep it small. Only the first 6 turns are printed.

import java.util.*;
interface Dice { int roll(); int min(); }                              // min(): the smallest possible roll
class RandomDice implements Dice {
    private final int k; private final Random rnd;
    RandomDice(int k, Random rnd) { this.k = k; this.rnd = rnd; }
    public int roll() { int s = 0; for (int i = 0; i < k; i++) s += 1 + rnd.nextInt(6); return s; }
    public int min() { return k; }                                     // k dice: at least 1 each
}
interface MoveRule { int next(int pos, int roll, int size); }
class ExactLanding implements MoveRule { public int next(int p, int r, int n) { return p + r > n ? p : p + r; } }
class BounceBack implements MoveRule {
    public int next(int p, int r, int n) { int t = p + r; return t > n ? n - (t - n) : t; } }
class Player { final String name; int pos; Player(String name, int pos) { this.name = name; this.pos = pos; } }

public class Main {
    static final int SIZE = 30, MAX_TURNS = 40;                        // the turn cap: a safety net
    static void play(String title, MoveRule rule) {
        System.out.println("--- " + title);
        Dice dice = new RandomDice(2, new Random(5));                  // two dice, seeded
        Deque<Player> turns = new ArrayDeque<>(List.of(new Player("Asha", 29), new Player("Ravi", 29)));  // a saved game
        for (int t = 1; t <= MAX_TURNS; t++) {
            Player p = turns.poll(); int roll = dice.roll(), before = p.pos;
            p.pos = rule.next(p.pos, roll, SIZE);
            if (t <= 6) System.out.printf("%-4s rolls %2d: %2d -> %2d%n", p.name, roll, before, p.pos);
            if (p.pos == SIZE) { System.out.println("Winner: " + p.name + " after " + t + " turns"); return; }
            turns.offer(p);
        }
        System.out.println("No winner after " + MAX_TURNS + " turns: the loop would run forever");
    }
    static List<Integer> trapCells(int size, Dice d, Set<Integer> jumpStarts) {   // cells you can never leave
        List<Integer> traps = new ArrayList<>();
        for (int p = size - d.min() + 1; p < size; p++) if (!jumpStarts.contains(p)) traps.add(p);
        return traps;
    }
    public static void main(String[] args) {
        play("two dice + ExactLanding", new ExactLanding());
        play("two dice + BounceBack", new BounceBack());
        System.out.println("--- the check that refuses the setup");
        System.out.println("1 dice,  traps: " + trapCells(SIZE, new RandomDice(1, new Random()), Set.of(27)));
        System.out.println("2 dice,  traps: " + trapCells(SIZE, new RandomDice(2, new Random()), Set.of(27)));
        System.out.println("3 dice,  traps: " + trapCells(SIZE, new RandomDice(3, new Random()), Set.of(27)));
    }
}

Output:

--- two dice + ExactLanding
Asha rolls 11: 29 -> 29
Ravi rolls  6: 29 -> 29
Asha rolls  7: 29 -> 29
Ravi rolls 11: 29 -> 29
Asha rolls  7: 29 -> 29
Ravi rolls 10: 29 -> 29
No winner after 40 turns: the loop would run forever
--- two dice + BounceBack
Asha rolls 11: 29 -> 20
Ravi rolls  6: 29 -> 25
Asha rolls  7: 20 -> 27
Ravi rolls 11: 25 -> 24
Asha rolls  7: 27 -> 26
Ravi rolls 10: 24 -> 26
Winner: Ravi after 16 turns
--- the check that refuses the setup
1 dice,  traps: []
2 dice,  traps: [29]
3 dice,  traps: [28, 29]

(That is one run's output, split in two blocks only for reading. The new Random() in the last three lines is never rolled, so those lines don't change between runs.)

What it shows:

  • ExactLanding + two dice: every roll (11, 6, 7, ...) overshoots 30, both players stay on 29, and only the cap stops the program. Without the cap, play() would loop for ever.
  • BounceBack + the same dice (same seed, same rolls): the overshoot moves the player back, off the trap cell, and the game ends after 16 turns. (Even BounceBack can't finish from 29 with two dice; it only works because it moves you somewhere else first.)
  • The fix: validate that the rules fit the dice. With exact landing and dice whose smallest roll is min, a player on any cell from size - min + 1 to size - 1 can never move again. That cell is a trap unless a jump starts there (a snake's head on 29 sends you away). With one dice there is no trap, with two dice cell 29, with three dice 28 and 29. The Game should refuse such a setup before it starts, exactly like the board refuses a chain. The mini project does this.
  • A Set is a collection with no duplicates that answers "is this in it?" quickly; Set.of(27) says "a jump starts on 27".

Common mistakes

Mistake What you see Why Fix
Copy-pasted if-chains per player Ravi rolls 6 -> 99 (the snake on 99 is missed) Rules duplicated; one copy is incomplete One Board, jumps as a Map
No overshoot rule Ravi wins at 104 pos >= 100 counts an overshoot as a win A MoveRule; win when pos == size
Ladder ending on a snake's head java.lang.IllegalArgumentException: a jump ends on 17, where another jump starts Chained jumps Validate the configuration
Two jumps on one cell two jumps start at 4 Which one applies? Refuse duplicate starts
A jump past the end off the board: Ladder[bottom=90, top=120] Bad data Check every jump is inside the board
A snake going up java.lang.IllegalArgumentException: snake must go down: 10->60 Head and tail swapped The record's compact constructor checks it
new Random() inside Game A different game on every run (see the unseeded line in section 7) Randomness wired in Inject Dice; seed it, or use FixedDice in tests
A random number 2..12 for two dice 2 as common as 7 (see practice question 6: about 3,200 each) Not how dice add up Roll each dice and sum them
Two dice + exact landing No winner after 40 turns: the loop would run forever (with a cap; without one, the program hangs) The smallest roll is 2, cell 29 needs a 1 Refuse the setup, or use BounceBack
Catching a bad Snake inside the board's try The exception escapes: at Snake.<init>(Main.java:3) The snake was built (and refused) before the try Build jumps inside the try, or let it fail fast

Mini project: a configurable 3-player game

Goal: put everything together, fully expanded (nothing folded):

  • the board configuration is read from text (size 30, ladder 3 22, snake 27 1) and validated;
  • three players; a six gives another turn; play on until one player is left, printing the finishing places;
  • the game refuses two dice with exact landing (the trap from section 14), and has a turn cap as a safety net.

New Java pieces used: a text block (""" ... """: a multi-line string literal), strip() (remove spaces and blank lines at both ends), split("\\s+") (split on any run of spaces), Integer.parseInt (turn "22" into the number 22), and the arrow switch (case "size" -> ...), which runs exactly one branch with no break needed.

import java.util.*;

interface Jump { int from(); int to(); }
record Snake(int head, int tail) implements Jump {
    Snake { if (tail >= head) throw new IllegalArgumentException("snake must go down: " + head + "->" + tail); }
    public int from() { return head; }
    public int to() { return tail; }
}
record Ladder(int bottom, int top) implements Jump {
    Ladder { if (top <= bottom) throw new IllegalArgumentException("ladder must go up: " + bottom + "->" + top); }
    public int from() { return bottom; }
    public int to() { return top; }
}

class Board {
    final int size;
    private final Map<Integer, Integer> jumps = new HashMap<>();
    Board(int size, List<Jump> list) {
        this.size = size;
        for (Jump j : list) {
            if (j.from() <= 1 || j.from() >= size || j.to() > size) fail("off the board: " + j);
            if (jumps.containsKey(j.from())) fail("two jumps start at " + j.from());
            jumps.put(j.from(), j.to());
        }
        for (int end : jumps.values())
            if (jumps.containsKey(end)) fail("a jump ends on " + end + ", where another jump starts");
    }
    int jump(int pos) { return jumps.getOrDefault(pos, pos); }
    boolean isJumpStart(int pos) { return jumps.containsKey(pos); }
    static void fail(String why) { throw new IllegalArgumentException(why); }

    // board configuration as text: "size 30", "ladder 3 22", "snake 27 1"
    static Board parse(String text) {
        int size = 0; List<Jump> list = new ArrayList<>();
        for (String line : text.strip().split("\n")) {
            String[] w = line.trim().split("\\s+");
            switch (w[0]) {
                case "size"   -> size = Integer.parseInt(w[1]);
                case "ladder" -> list.add(new Ladder(Integer.parseInt(w[1]), Integer.parseInt(w[2])));
                case "snake"  -> list.add(new Snake(Integer.parseInt(w[1]), Integer.parseInt(w[2])));
                default       -> fail("unknown line: " + line);
            }
        }
        return new Board(size, list);
    }
}

interface Dice { int roll(); int min(); }
class RandomDice implements Dice {
    private final int k; private final Random rnd;
    RandomDice(int k, Random rnd) { this.k = k; this.rnd = rnd; }
    public int roll() { int s = 0; for (int i = 0; i < k; i++) s += 1 + rnd.nextInt(6); return s; }
    public int min() { return k; }
}

interface MoveRule { int next(int pos, int roll, int size); boolean exact(); }
class ExactLanding implements MoveRule {
    public int next(int p, int r, int n) { return p + r > n ? p : p + r; }
    public boolean exact() { return true; }
}

class Player {
    final String name; int pos = 0;
    Player(String name) { this.name = name; }
}

class Game {
    private final Board board; private final Dice dice; private final MoveRule rule;
    private final Deque<Player> turns;
    final List<Player> winners = new ArrayList<>();
    Game(Board board, Dice dice, MoveRule rule, List<Player> players) {
        // refuse a setup that can trap a player forever (two dice + exact landing)
        if (rule.exact())
            for (int p = board.size - dice.min() + 1; p < board.size; p++)
                if (!board.isJumpStart(p))
                    throw new IllegalArgumentException("cell " + p + " can never finish with these dice");
        this.board = board; this.dice = dice; this.rule = rule; this.turns = new ArrayDeque<>(players);
    }
    void playTurn() {
        Player p = turns.poll();
        int roll = dice.roll();
        int landed = rule.next(p.pos, roll, board.size), end = board.jump(landed);
        String note = end > landed ? "  ladder!" : end < landed ? "  snake!" : "";
        System.out.printf("%-5s rolls %d: %2d -> %2d%s%n", p.name, roll, p.pos, end, note);
        p.pos = end;
        if (p.pos == board.size) {                       // winning condition: exactly the last cell
            winners.add(p);
            System.out.println("      " + p.name + " finishes, place " + winners.size());
        } else if (roll == 6) {
            turns.addFirst(p);                           // a six: same player again (front of the queue)
        } else {
            turns.offer(p);                              // back of the queue
        }
    }
    List<Player> play(int maxTurns) {
        for (int t = 0; t < maxTurns && turns.size() > 1; t++) playTurn();   // until one player is left
        if (turns.size() > 1) throw new IllegalStateException("no result after " + maxTurns + " turns");
        winners.add(turns.poll());                       // the last one left takes the last place
        return winners;
    }
}

public class Main {
    public static void main(String[] args) {
        String config = """
            size 30
            ladder 3 22
            ladder 5 8
            ladder 11 26
            ladder 20 29
            snake 17 4
            snake 19 7
            snake 21 9
            snake 27 1
            """;
        Board board = Board.parse(config);
        Game game = new Game(board, new RandomDice(1, new Random(7)), new ExactLanding(),
                             List.of(new Player("Asha"), new Player("Ravi"), new Player("Neha")));
        List<Player> result = game.play(500);
        for (int i = 0; i < result.size(); i++) System.out.println((i + 1) + ". " + result.get(i).name);

        try {
            new Game(board, new RandomDice(2, new Random(7)), new ExactLanding(), List.of(new Player("Asha")));
        } catch (IllegalArgumentException e) {
            System.out.println("two dice refused: " + e.getMessage());
        }
    }
}

Output (seed 7, the same on every run):

Asha  rolls 5:  0 ->  8  ladder!
Ravi  rolls 3:  0 -> 22  ladder!
Neha  rolls 4:  0 ->  4
Asha  rolls 5:  8 -> 13
Ravi  rolls 5: 22 ->  1  snake!
Neha  rolls 5:  4 ->  9
Asha  rolls 5: 13 -> 18
Ravi  rolls 6:  1 ->  7
Ravi  rolls 1:  7 ->  8
Neha  rolls 1:  9 -> 10
Asha  rolls 1: 18 ->  7  snake!
Ravi  rolls 1:  8 ->  9
Neha  rolls 1: 10 -> 26  ladder!
Asha  rolls 2:  7 ->  9
Ravi  rolls 2:  9 -> 26  ladder!
Neha  rolls 5: 26 -> 26
Asha  rolls 4:  9 -> 13
Ravi  rolls 1: 26 ->  1  snake!
Neha  rolls 4: 26 -> 30
      Neha finishes, place 1
Asha  rolls 4: 13 ->  4  snake!
Ravi  rolls 5:  1 ->  6
Asha  rolls 3:  4 ->  7
Ravi  rolls 4:  6 -> 10
Asha  rolls 2:  7 ->  9
Ravi  rolls 3: 10 -> 13
Asha  rolls 3:  9 -> 12
Ravi  rolls 4: 13 ->  4  snake!
Asha  rolls 5: 12 ->  4  snake!
Ravi  rolls 1:  4 ->  8  ladder!
Asha  rolls 6:  4 -> 10
Asha  rolls 4: 10 -> 14
Ravi  rolls 4:  8 -> 12
Asha  rolls 2: 14 -> 16
Ravi  rolls 4: 12 -> 16
Asha  rolls 4: 16 -> 29  ladder!
Ravi  rolls 3: 16 ->  7  snake!
Asha  rolls 5: 29 -> 29
Ravi  rolls 1:  7 ->  8
Asha  rolls 1: 29 -> 30
      Asha finishes, place 2
1. Neha
2. Asha
3. Ravi
two dice refused: cell 29 can never finish with these dice

(One run's output, split in two blocks only for reading.)

Things to check in the output:

  • A six gives another turn: "Ravi rolls 6: 1 -> 7" is followed straight away by "Ravi rolls 1" (and later Asha's 6 is followed by another Asha turn).
  • Snakes and ladders from the text: 22 + 5 = 27 is the snake 27 → 1; 4 + 1 = 5 is the ladder 5 → 8; 10 + 1 = 11 is the ladder 11 → 26.
  • Exact landing: Neha on 26 rolls 5 (31) and stays; Asha on 29 rolls 5 and stays, then a 1 finishes.
  • Play until one is left: Neha finishes first and leaves the queue; the game goes on until Asha finishes, and Ravi, the last one left, takes third place.
  • The trap is refused before any turn is played: with two dice and exact landing, cell 29 can never finish.

Practice

1. Why does the board use a Map with getOrDefault(pos, pos) instead of a list of jumps?

Answer

Each move needs exactly one question: "does a jump start on this cell, and where does it end?" A HashMap answers that with one lookup, O(1) on average, however many snakes and ladders there are. A list would have to be scanned every move: O(number of jumps). getOrDefault(pos, pos) also removes the if: if no jump starts on pos, you simply get pos back, so "no jump" and "a jump" are the same line of code.

2. A 100-cell board has these jumps: ladder 2 → 38, snake 38 → 10, ladder 70 → 120, snake 50 → 50. Which checks refuse it, and with which message?

Answer
  • new Snake(50, 50) is refused first, while the list is built: the compact constructor sees tail >= head and throws snake must go down: 50->50 (a snake must strictly go down).
  • Without that snake, the board would refuse Ladder[bottom=70, top=120] with off the board: Ladder[bottom=70, top=120] (the checks run in list order, and the off-board check comes in the first loop).
  • Without that ladder too, it would refuse the chain: a jump ends on 38, where another jump starts.

The real messages for each kind of refusal are in the program in section 6 ("Every validation, one at a time").

3. With two dice, how many of the 36,000 throws should total 4? Compare with the real count in section 8.

Answer

A total of 4 happens 3 ways (1+3, 2+2, 3+1), so 3 of 36 = 1 in 12. 36,000 / 12 = 3,000. The seeded run counted 3,033: close, as expected from random throws (never exactly the expected value).

4. Follow-up: "Replay a finished game." The game used an unseeded new Random(), so the seed is unknown. How can you still replay it?

Answer

Record every roll while playing, then replay with a FixedDice that plays those rolls. A RecordingDice wraps any dice (it holds another Dice and passes each call on), so the game code doesn't change: dependency injection again.

import java.util.*;
interface Dice { int roll(); }
class RandomDice implements Dice {
    private final Random rnd; RandomDice(Random rnd) { this.rnd = rnd; }
    public int roll() { return 1 + rnd.nextInt(6); } }
class FixedDice implements Dice {
    private final int[] script; private int i = 0; FixedDice(int... script) { this.script = script; }
    public int roll() { return script[i++ % script.length]; } }
class RecordingDice implements Dice {                       // wraps ANY dice and remembers every roll
    private final Dice inner; final List<Integer> rolls = new ArrayList<>();
    RecordingDice(Dice inner) { this.inner = inner; }
    public int roll() { int r = inner.roll(); rolls.add(r); return r; } }
public class Main {
    static String game(Dice d) {                            // a tiny 30-cell race, no jumps, exact landing
        int[] pos = new int[2]; String[] names = {"Asha", "Ravi"};
        for (int t = 0; ; t++) {
            int p = t % 2, r = d.roll();
            if (pos[p] + r <= 30) pos[p] += r;
            if (pos[p] == 30) return names[p] + " wins on turn " + (t + 1);
        }
    }
    public static void main(String[] args) {
        RecordingDice rec = new RecordingDice(new RandomDice(new Random()));   // unseeded: a new game each run
        System.out.println("played:   " + game(rec));
        System.out.println("rolls:    " + rec.rolls);
        int[] script = rec.rolls.stream().mapToInt(Integer::intValue).toArray();
        System.out.println("replayed: " + game(new FixedDice(script)));
    }
}

Output of one real run (unseeded, so your rolls will differ; the "replayed" line always matches the "played" line):

played:   Asha wins on turn 11
rolls:    [6, 3, 6, 4, 5, 2, 5, 1, 3, 4, 5]
replayed: Asha wins on turn 11

rec.rolls.stream().mapToInt(Integer::intValue).toArray() turns the List<Integer> into an int[] for FixedDice. (A second run gave Asha wins on turn 17 with 17 different rolls, and again replayed exactly.)

5. The interviewer asks for four players. What do you change?

Answer

Nothing in Game. Pass four players: List.of(new Player("Asha"), new Player("Ravi"), new Player("Neha"), new Player("Kabir")). The turn queue takes the front player and puts them at the back, so any number of players goes round in order. The mini project already plays three.

6. Show with real counts why "a random number from 2 to 12" is the wrong way to roll two dice.

Answer

2 + rnd.nextInt(11) gives 2 to 12 with every total equally likely. Compare it with rolling two dice and adding:

import java.util.Random;
public class Main {
    public static void main(String[] args) {
        Random rnd = new Random(1);
        int[] wrong = new int[13], right = new int[13];
        for (int i = 0; i < 36000; i++) wrong[2 + rnd.nextInt(11)]++;                       // WRONG: one number 2..12
        for (int i = 0; i < 36000; i++) right[(1 + rnd.nextInt(6)) + (1 + rnd.nextInt(6))]++; // RIGHT: two dice, added
        System.out.println("total  wrong  right");
        for (int s = 2; s <= 12; s++) System.out.printf("%5d  %5d  %5d%n", s, wrong[s], right[s]);
    }
}

Output:

total  wrong  right
    2   3171   1080
    3   3278   2052
    4   3406   2976
    5   3323   4048
    6   3380   4888
    7   3269   5951
    8   3190   4878
    9   3154   3987
   10   3380   3053
   11   3226   2092
   12   3223    995

The wrong way gives every total about 36,000 / 11 ≈ 3,273: a 2 is as common as a 7. Real dice give the triangle: about 1,000 twos and 6,000 sevens. (The "right" column differs a little from section 8 because the same Random was used first for the wrong loop, so the two dice got different numbers.)

7. Where does the rule "you win only on the exact last cell" live, and where would "a six gives another turn" live?

Answer

The winning condition lives in Game (p.pos == board.size), and the move that makes it possible lives in the MoveRule (ExactLanding never moves you past the end). "A six gives another turn" is about turn order, which Game owns: after a 6 it puts the player back at the front of the queue instead of the back. For full extensibility, give it its own interface (a TurnRule) so it can be swapped like MoveRule. Board and Dice should know neither rule.

Quick quiz

A 30-cell board with BounceBack (walk back the extra steps). Asha is on 26 and rolls a 6. Jumps: 27 → 1 (a snake); 29 is a ladder's top (the ladder 20 → 29). Where does Asha end up?

A) 32 B) 30, she wins C) 28 D) 1

Answer

C) 28. 26 + 6 = 32, which is 2 past 30, so she walks back 2 to 28. No jump starts on 28 (29 is only where a ladder ends, and the snake starts on 27, which she passes but doesn't land on), so she stays on 28.

Interview questions

  1. What are the classes in Snake and Ladder? Board (size + map of jumps), Snake and Ladder (records, both a Jump), Dice (interface), MoveRule (interface), Player (name + position), Game (owns the board, dice, rule and turn queue; runs the game loop).
  2. How do you store snakes and ladders, and how fast is a move? As data: a Map<Integer, Integer> from start cell to end cell. A position jump is getOrDefault(pos, pos): one O(1) lookup on average.
  3. What would you validate on the board? Snakes go down and ladders go up; every jump is inside the board; no two jumps start on one cell; no chains (a jump never ends where another starts); and the rules fit the dice (no cell that can never finish).
  4. How do you test a game with dice? Inject the dice. In tests, pass a FixedDice that plays a script you choose (or a RandomDice with a fixed seed). Never create new Random() inside Game.
  5. What does a seed do? It is the starting value of the pseudo-random formula: the same seed always gives the same sequence, so a run can be repeated exactly.
  6. How do you roll two dice? Roll each dice (1 to 6) and add them; never pick one number from 2 to 12, because 7 must be six times as likely as 2.
  7. How do you support a different overshoot rule? A MoveRule interface (Strategy pattern): ExactLanding, BounceBack, ... The Game code doesn't change: game rules extensibility.
  8. Why a queue for the turns? Take the front player, put them at the back after their turn: any number of players with no extra code, and "another turn" is just putting them back at the front.
  9. What's the trap with two dice and exact landing? The smallest roll is 2, so a player on the second-last cell can never finish; if everyone gets stuck the game loop runs for ever. Refuse the setup (or use BounceBack), and keep a turn cap as a safety net.
  10. How would you replay a finished game? Store the seed, or record the list of rolls and replay them with a FixedDice.

Glossary

Term Meaning, with an example
Snake and Ladder A board game: roll dice, move forward, ladders take you up, snakes take you down; first to the last cell wins
Machine-coding round An interview round where you design and code a small working system in about 60-120 minutes
Clarifying question A question you ask before coding to fix the rules: "what happens on an overshoot?"
Cell One numbered square of the board: cells 1 to 100 (players start at 0, outside the board)
Board The class that knows the board's size and every jump, refuses a broken setup, and answers jump(pos)
Snake A jump that goes down, from its head to its tail: new Snake(17, 7)
Ladder A jump that goes up, from its bottom to its top: new Ladder(4, 14)
Jump Our interface for "move from one cell to another": from() and to(). Snake and Ladder both implement it
Dice The interface for "anything that gives a number": int roll(). One dice gives 1 to 6
Multiple dice Rolling k dice and adding them: two dice give 2 to 12, with 7 the most common (6 of 36)
RandomDice Our real dice: new RandomDice(2, new Random(19)) rolls two seeded dice and adds them
FixedDice A fake dice for tests that plays a script: new FixedDice(3, 2, 6) rolls 3, then 2, then 6
Test double A fake object used in place of the real one in a test, like FixedDice for RandomDice
Player A name and a position: new Player("Asha"), position 0
Game The class that owns the board, dice, move rule and turn queue, and runs the game loop
Game loop One turn repeated until someone wins: next player → roll → move → jump → won?
Turn One player's go: roll, move, apply any jump
Turn order Who plays next; here a queue: front player plays, then goes to the back
Position jump Moving from where you landed to the end of the snake or ladder that starts there: land on 4, jump to 14
Board configuration The board's setup given as data, not code: size 30, ladder 3 22, snake 27 1
Hard-coded Written straight into the code, so changing it means editing code: if (asha == 4) asha = 14;
Copy-paste bug A bug from duplicated code where one copy is different: Ravi's copy missed the snake on 99
Validation Checking data is sensible before using it, and refusing it if not: "two jumps start at 4"
Chain (of jumps) A jump that ends where another starts: ladder 4 → 17 and snake 17 → 7. We forbid it
Overshoot A roll that would go past the last cell: on 98, rolling 5
Exact landing The rule that you must land exactly on the last cell; too far, and you stay where you are
BounceBack The rule that a roll past the end walks back the extra steps: 28 + 5 = 33 → 27
MoveRule Our interface for "what a roll does to a position": int next(int pos, int roll, int size)
Winning conditions The rule for when a player has won: here, exactly on the last cell (pos == size)
Game rules extensibility Adding or changing a rule by adding a class, without editing the game: BounceBack
Random seeding for tests Giving the random generator a fixed seed so a run repeats exactly: new Random(42)
Random (truly) Impossible to predict, like real dice
Pseudo-random Looks random but comes from a formula, each number from the one before
Pseudo-random number generator Code that produces pseudo-random numbers: java.util.Random
java.util.Random Java's pseudo-random generator class: new Random(42).nextInt(6)
Seed The starting number the pseudo-random formula begins from; same seed, same numbers
nextInt(n) A Random method giving a whole number from 0 to n - 1: nextInt(6) is 0 to 5, so 1 + nextInt(6) is a dice
Turn cap A maximum number of turns, so a game loop always stops: MAX_TURNS = 40
Infinite loop A loop with no way out: while (true) when nobody can ever win
Record A short class that only carries values; Java writes its constructor, getters, equals, hashCode, toString: record Snake(int head, int tail)
Compact constructor A record's constructor written without the parameter list, Snake { ... }, that runs before the fields are set, so it can check or refuse the values
Interface A contract listing methods a class promises to have: class Ladder implements Jump
implements The keyword that says a class keeps an interface's promise: class RandomDice implements Dice
final Set once and never changed: final String name
Exception Java's way of stopping normal flow because something should not happen
IllegalArgumentException The standard exception for a bad argument: snake must go down: 10->60
IllegalStateException The standard exception for "the object is in the wrong state for this": no result after 500 turns
Stack trace The chain of method calls (with line numbers) printed with an uncaught exception
<init> How a stack trace names a constructor: Board.<init> is the Board constructor
try / catch Run code in try; if it throws, the catch block handles it instead of crashing
getMessage() The text an exception was created with: "two jumps start at 4"
Map A collection of key → value pairs, found by key: {4=14, 17=7}
HashMap The usual Map class; it uses each key's hash code to find entries in O(1) on average
Hash code A number computed from a value, used by a HashMap to find its slot quickly
Map.of Builds a small fixed map from pairs: Map.of(3, 22, 5, 8) is {3=22, 5=8}
getOrDefault map.getOrDefault(k, d): the value for k, or d if k isn't there: jumps.getOrDefault(50, 50) is 50
containsKey map.containsKey(k): is k one of the keys?
Set A collection with no duplicates that answers "is this in it?": Set.of(27)
List.of Builds a small fixed list: List.of(new Ladder(4, 14), new Snake(17, 7))
Queue A line: take from the front, add at the back (first in, first out)
Deque A "double-ended queue": add or remove at both ends. poll() takes the front, offer() adds at the back, addFirst() adds at the front
ArrayDeque Java's usual Deque class: new ArrayDeque<>(players)
Dependency injection Giving an object what it depends on from outside instead of creating it inside: new Game(board, dice, rule, players) (episode 16)
Strategy pattern A family of interchangeable algorithms behind one interface: ExactLanding and BounceBack are both a MoveRule (episode 34)
Unit test A small automatic check of one behaviour with a known answer: check(a.pos == 1, ...) prints PASS or FAIL
Big-O notation How the work grows with the input size: O(1), O(n)
O(1), constant time Work that doesn't grow with the input: one map lookup per move
O(n) Work that grows in step with n: scanning a list of n jumps
Remainder (%) What's left after division: 5 % 2 is 1; i % 2 == 0 means i is even
Ternary operator cond ? a : b, "if cond then a else b": p + r > n ? p : p + r
Varargs (int...) A parameter that takes any number of values as an array: FixedDice(int... script)
printf / format string Printing with placeholders: %d a number, %2d padded to 2, %-4s a string left-aligned in 4, %n a new line
StringBuilder Builds a string piece by piece: s.append(3).append(' ')
repeat "#".repeat(5) is #####
Text block A multi-line string between """ and """ (the mini project's board configuration)
Arrow switch switch (w) { case "size" -> ...; }: runs exactly one branch, no break needed
Integer.parseInt Turns text into a number: Integer.parseInt("22") is 22
Noun analysis Picking candidate classes from the nouns of the brief: board, snake, ladder, dice, player, game (episode 20)
Saved game A game that starts from given positions instead of 0: Ravi already on 93

Summary

  • The obvious code (positions as ints, if chains copied per player) missed the snake on 99 and declared "Ravi wins at 104".
  • The fix: nouns became classes, Board, Snake, Ladder, Dice, Player, Game, and the snakes and ladders became data.
  • Board configuration is a Map from start cell to end cell: a position jump is one O(1) getOrDefault. The board validates itself: no off-board jumps, no two jumps on one cell, no chains; records' compact constructors refuse a snake going up.
  • java.util.Random is pseudo-random: a seed fixes the sequence (new Random(42) always gives 3 4 1 3 1 2 6 3), so a game can be replayed: random seeding for tests.
  • Multiple dice are a sum: in 36,000 seeded throws of two dice, 7 came up 5,898 times and 2 only 1,060.
  • The game loop repeats one turn (queue → roll → move rule → jump → won?); the winning condition is exactly the last cell.
  • Because Game is given its Dice and MoveRule (dependency injection, Strategy pattern), a FixedDice can test it (PASS PASS) and a new rule like BounceBack is just a new class: game rules extensibility.
  • Two dice + exact landing can never finish from the second-last cell: refuse that setup, and keep a turn cap.

Next episode: Design a Parking Lot, part 1: requirements, floors, spots, vehicles, tickets, gates, and the singleton debate.