AlgoViz

Design snake and ladders

easy 75 min

A small board game that shows judgement: one map for snakes and ladders, a die that is handed in, rules as values, and one object that owns what changes.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:33

Theory

Read or listen first. About 2 min.

What it is

Snake and ladders is a race over numbered squares. A die decides how far you go. Some squares send you up, some send you down. No player ever makes a choice.

In a design round it is a turn machine with an outside source of chance. The board is data, the rules are parameters, and the game is one verb.

The answer is short. What is judged is which classes you leave out, which rules you ask about, and whether you can test what you wrote.

Why it exists

Everybody knows the game, so the conversation is about objects after one minute. Because it is easy, a design that is too big stands out at once.

It teaches the most useful trick for testable code in a friendly setting: anything the program cannot control, such as chance or time, is handed in.

Its extensions are real problems: repeated requests, ordering, recovery from a log, fairness, and the difference between an average and a guess.

A short history

  1. 1892

    F. H. Ayres registers the earliest known English version in October, with a spiral of 100 squares. The game comes from a family of Indian dice board games that includes gyan chauper.

  2. 1943

    Milton Bradley publishes Chutes and Ladders in the United States, with a playground instead of snakes.

  3. 1993

    Althoen, King and Schilling publish How Long Is a Game of Snakes and Ladders? in The Mathematical Gazette, treating it as a Markov chain.

  4. 1994

    The book Design Patterns describes Strategy, the pattern behind a replaceable die.

Words to know

Jump
A start and an end. A snake if the end is lower, a ladder if it is higher.
Landing
Where you end up after stopping on a square.
Finish rule
What happens if a roll goes past the end.
Streak
How many special rolls in a row in this turn.
Turn order
The list of players and who is next.
Scripted die
A die that shows the numbers of a list.
Replay
Making a state again from its inputs.
Idempotent
Doing it twice has the same result as doing it once.
Markov chain
A process where only the present state decides what can follow.
Rejection
Throwing away random values that would make faces unequal.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Refuse or roll. Right player, game on, then the die is asked once

Understand it

Story

Garden slides and steps

Before the board game there was a garden. Eighteen stones lie on three terraces. Two flights of steps lead up, two slides lead down, and whoever stands under the red arch first has won.

Asha and Lee race to the arch
123456789101112131415161718die

Nine turns, no decision by any player. All the design is in what the rules are and who may change what.

What an interviewer looks for here

  • Restraint

    A small problem. Can you keep it small?

  • One idea for two things

    Snakes and ladders are one dictionary.

  • Chance under control

    A die that is handed in.

  • Questions about rules

    Exact finish, sixes, chains, leaving.

  • Turn order

    It breaks when somebody leaves.

  • Proof

    Trace a game by hand with scripted rolls.

How to spend the round

The problem is easy to code, so the time goes to rules, tests and extensions.

Rules

Questions that change the design

QuestionDefaultWhat it changes
Must the last square be hit exactly?Yes, otherwise stayA finish rule
Does a six give another roll?YesA turn may have several rolls: the turn number and not the player identifies a roll
Three sixes in a row?The third is thrown awayA counter that belongs to the turn
Can a jump end where another starts?Not allowedA check when the board is made
Can two players share a square?YesOtherwise: a rule for sending back
Where does everybody start?Beside the board, at 0A ladder on square 1 works
Does the game end with the first winner?YesOtherwise: a list of places, and winners are skipped
May a player leave?YesTurn order

One roll

Every diamond is a question to ask before coding.

Avoid

The design most people draw first

Each noun in the box becomes a class. It feels object-oriented, and almost none of the classes does anything.

The design to avoid: a class for every noun in the box

SnakeAndLadderGame- players: Queue<Player>- static instance+ play()+ printBoard()+ readInput()

1/5The game that talks

Playing, printing and reading the keyboard in one class, with one instance for the whole program. Nothing can be tested without a person at the keyboard.

usesowns (dies together)has (lives on)extends (is a)

Python
snakes = {17: 7}ladders = {7: 14}def land(square):    if square in snakes:        square = snakes[square]    if square in ladders:          # also runs after a snake        square = ladders[square]    return squaredef land_other_way(square):    if square in ladders:        square = ladders[square]    if square in snakes:        square = snakes[square]    return squareprint(land(17), land_other_way(17))      # 14 or 7?
The bug of two lists. Put a ladder at the bottom of a snake, and the order of two ifs decides the rule of the game. Nobody chose it.
Edit and run it in your browser

Target

The design to reach

The design to reach: one game, one unchanging board, two things that are handed in

Board- size: int- jumps: Map<int, int>+ landing(square): int

1/5The board

A size and a dictionary from start to end. Checked when it is made and never changed, so a thousand games can share one.

implementsusesowns (dies together)

Python
jumps = {3: 10, 8: 16, 11: 2, 17: 7}def landing(square):    return jumps.get(square, square)print([landing(s) for s in (3, 5, 11)])
The core idea on its own: one dictionary, one line.
Edit and run it in your browser

State

What each class owns

ClassStateAnswersDoes not know
BoardSize, jumpsWhere do I end up?Players, dice
DieA source of chanceWhich number?The game
RulesThree valuesToo many? Again? Third in a row?Whose turn
GameOrder, positions, next, streak, log, winnerTake a turnScreens, users, time
TurnWhat happenedNothingEverything else

The life of a game

Waiting belongs to the table around the game. Our Game starts in Playing.

Decision

How do you model snakes and ladders?

A snake takes you down, a ladder up. Which classes?

BreaksTwo dictionaries, two ifs
How
snakes and ladders, checked one after the other.
Limit
A square may be in both, and the order of the ifs becomes a rule.
Choose when
Never.
WorksAbstract Jump with Snake and Ladder
How
Subclasses that check their direction in the constructor.
Limit
Two classes without different behaviour. Fine if the direction check is all you want.
Choose when
When the interviewer wants to see a hierarchy. Say what you would miss: nothing.
StrongOne map from start to end
How
Direction is end < start, asked only by the screen.
Limit
A jump that does something else needs more.
Choose when
The default.
StrongSquare effects
How
Map from square to a function or small object: jump, miss a turn, roll again.
Limit
Effects change more than a position, so they return a description the game applies.
Choose when
When special squares are announced. See Extending it.

Who rolls the die?

BreaksThe client sends a number
How
move(player, 6).
Limit
They always need a six, and always roll one.
Choose when
Never online.
Worksrandom.randint inside the game
How
One line.
Limit
Not repeatable, so tests cannot ask for three sixes.
Choose when
A script.
StrongA die handed to the game
How
take_turn asks it.
Limit
One more argument.
Choose when
Always.

Numbers

How long is a game?

Every square leads to at most six others, and only the present square matters. That is a Markov chain, so the average can be computed instead of guessed. For our garden, one player, no extra roll on a six:

Boardstaybouncerun past
Garden, 18 stones11.61 rolls13.375.96
Our 100 board, 7 ladders, 8 snakes54.9872.2437.50
100 squares, no jumps33.3333.3329.05
Computed with the equations on the FAANG page The mathematics. The finish rule matters as much as the snakes.

The equation for one square

Es=1+16∑r=16E next(s,r),Elast=0E_s = 1 + \frac{1}{6}\sum_{r=1}^{6} E_{\,\text{next}(s, r)}, \qquad E_{\text{last}} = 0
One roll, then the average of where it can lead. One equation for each square.

Earned here

  • An interface for the die
  • A function for the finish rule
  • Frozen records
  • One coordinator

Not earned

  • Snake and Ladder classes
  • Cell objects
  • A Singleton board
  • State classes for whose turn
  • Observer before anybody listens

Summary

The whole topic in one minute.

The board is a size and one map from start to end, checked when it is made and shared by all games. The die is handed in, the rules are frozen values, and the game alone owns order, positions, streak and log. take_turn refuses, rolls, computes, changes, records.

Because chance is the only input, the list of rolls is the game: tests, replay, undo and recovery are the same thing. Online, each roll has a number, so that a repeated request finds its answer.

  • Snakes and ladders are one map from start to end.
  • The die is handed in. Chance is the only outside input, so the rolls are the game.
  • take_turn refuses, rolls, computes, changes and records, in this order.
  • The streak belongs to the turn and is cleared when the turn passes.
  • Leaving is the hard part of turn order.
  • Boards are checked once: bounds, duplicates, chains, and whether the end can be reached.

Sources