Design snake and ladders
easy 75 minA 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
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
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.
1943
Milton Bradley publishes Chutes and Ladders in the United States, with a playground instead of snakes.
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.
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.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
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.
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
Rules
Questions that change the design
| Question | Default | What it changes |
|---|---|---|
| Must the last square be hit exactly? | Yes, otherwise stay | A finish rule |
| Does a six give another roll? | Yes | A turn may have several rolls: the turn number and not the player identifies a roll |
| Three sixes in a row? | The third is thrown away | A counter that belongs to the turn |
| Can a jump end where another starts? | Not allowed | A check when the board is made |
| Can two players share a square? | Yes | Otherwise: a rule for sending back |
| Where does everybody start? | Beside the board, at 0 | A ladder on square 1 works |
| Does the game end with the first winner? | Yes | Otherwise: a list of places, and winners are skipped |
| May a player leave? | Yes | Turn order |
One roll
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
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)
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?Target
The design to reach
The design to reach: one game, one unchanging board, two things that are handed in
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)
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)])State
What each class owns
| Class | State | Answers | Does not know |
|---|---|---|---|
Board | Size, jumps | Where do I end up? | Players, dice |
Die | A source of chance | Which number? | The game |
Rules | Three values | Too many? Again? Third in a row? | Whose turn |
Game | Order, positions, next, streak, log, winner | Take a turn | Screens, users, time |
Turn | What happened | Nothing | Everything else |
The life of a game
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
snakesandladders, 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_turnasks 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:
| Board | stay | bounce | run past |
|---|---|---|---|
| Garden, 18 stones | 11.61 rolls | 13.37 | 5.96 |
| Our 100 board, 7 ladders, 8 snakes | 54.98 | 72.24 | 37.50 |
| 100 squares, no jumps | 33.33 | 33.33 | 29.05 |
The equation for one 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_turnrefuses, 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.