LLD6 min read
Snake and Ladder
Game loop with chained jumps, dice strategy and configurable board.
lldoopgame
Intro
Snake and Ladder is the classic 'simulate this rule set' problem. The clean solution separates Board (positions of snakes and ladders), Dice (configurable), Player (position + bookkeeping) and Game (the orchestration loop).
Functional
- Board with N cells, multiple snakes (cell→cell, head > tail) and ladders (cell→cell, top > bottom).
- Roll dice, advance, apply chained snakes/ladders until the position stabilises.
- First player to reach the last cell wins.
Non-functional
- Configurable dice (count, faces).
- Board configuration loadable from data.
Components
Board
Maps cell → next-cell after chained snake/ladder.
Dice
Sum of k dice each with f faces. Strategy hook for loaded dice in tests.
Player
Position + name.
Game
Round-robin loop until someone reaches the last cell.
Code
Snippetpython
class Board:
def __init__(self, n, snakes, ladders):
self.n = n
self.jump = {**snakes, **ladders}
def settle(self, pos):
seen = set()
while pos in self.jump and pos not in seen:
seen.add(pos)
pos = self.jump[pos]
return pos
class Game:
def __init__(self, board, dice, players):
self.board, self.dice, self.players = board, dice, players
def play(self):
i = 0
while True:
p = self.players[i % len(self.players)]
roll = self.dice.roll()
target = p.pos + roll
if target <= self.board.n:
p.pos = self.board.settle(target)
if p.pos == self.board.n:
return p
i += 1
Pitfalls
- Forgetting that ladders chain — a ladder can land you on a snake.
- Hardcoding snakes/ladders in the engine.