Object Model and Move Engine for a Sliding-Tile Merge Game
Data Structure DesignModel answerLast updated
Design the classes and core move algorithm for a configurable N x N sliding-tile merge puzzle, with testable randomness, win and loss detection, and room for undo.
You are asked to design the classes and the core move logic for a sliding-tile merge puzzle in the style of 2048, played on a square N x N board. Focus on the object model, who owns which state, and the move algorithm. Do not design a UI or rendering layer.
How the game works
The player picks one of four directions. Every tile slides as far as it can in that direction. When two neighboring tiles with equal values collide, they combine into a single tile holding their sum. After any move that changes the board, one new tile appears in a random empty cell.
Assumptions
- The board is
N x N, withN = 4by default but configurable. - Tile values are powers of two. An empty cell is stored as
0. - A spawned tile is
2with probability 0.9 and4with probability 0.1. Both numbers must be configurable. - A new game begins with two tiles already placed.
- By default the player wins on creating a
2048tile. Play may continue afterward. - Randomness must be injectable so that tests are reproducible.
- This is a single local session. Networking and persistence are out of scope, but the design should not make them hard to add later.
Requirements
- Start-up: create a board with two random tiles.
- Moves: support
UP,DOWN,LEFT,RIGHT. - Slide and merge: tiles slide toward the move direction, and any given tile may take part in at most one merge per move.
- Scoring: each merge adds the value of the newly created tile to the score.
- Spawning: add a new tile only if the move changed the board.
- End states: detect when the player has won and when the game is over.
- Separation of concerns: keep presentation code completely out of the game logic.
What to discuss
Describe the classes, their responsibilities and their relationships, then give the move algorithm and its complexity. Also explain how your design supports each of the following without rewriting the merge logic:
- undo
- custom board sizes
- deterministic tests
- configurable spawn probabilities
State any clarifying questions you would ask before starting.
Hints
Hint 1
Reduce all four directions to one operation: take a single row, compress it toward index 0, and merge. Then think about how to turn UP, DOWN and RIGHT into that same operation by extracting lines in the right order.
Hint 2
To enforce one merge per tile per move, build the output list left to right and only merge the incoming value with the last output value if that last value has not itself been produced by a merge in this pass.
Hint 3
Game over is not the same as a full board. A full board can still have a legal move if any two adjacent cells are equal. Also, compare the board before and after to decide whether to spawn a tile or count the move as valid.
Hint 4
Inject a random source and a spawn policy into the game rather than calling a global random function, and keep the board state immutable or cheaply copyable so that undo becomes a stack of snapshots.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying questions
- Is the board always square, and is
Nconfigurable? (Assume yes to both.) - After the target tile appears, does play stop or continue? (Assume it continues, with a "won" flag set once.)
- Are spawn probabilities fixed, and is the target tile value configurable?
- Is undo required, and how deep? Is there any need for save/resume?
- Does the score only count merge gains?
Class model
| Class | Responsibility |
|---|---|
Direction (enum) | UP, DOWN, LEFT, RIGHT |
Board | Owns the N x N grid of ints. Exposes get, set, empty_cells(), rows(), copy(), and lines(direction) / write_lines(direction, lines) |
LineMerger | Pure function: takes one line, returns (new_line, gained_score). Holds all the merge rules and no state |
SpawnPolicy | Picks a value (2 or 4) using a probability table and a Random instance |
GameConfig | size, target, spawn_probs, initial_tiles |
Game | Orchestrates moves. Holds the Board, score, won flag, SpawnPolicy, and a history stack |
GameView / ConsoleView | Reads state from Game and renders it. The game never imports it |
Game depends on abstractions (Random, SpawnPolicy), and the view depends on Game, never the reverse. This is what keeps presentation out of the logic.
Core idea: one merge function, four directions
Write the merge rule once, for a line being pushed toward index 0:
- Drop zeros.
- Walk the remaining values left to right, building an output list. If the next value equals the last output value and that last output value was not created by a merge this pass, replace the last output with their sum, add the sum to the score, and mark it as merged. Otherwise append the value.
- Pad with zeros to length
N.
Example: [2,2,2,2] -> [4,4,0,0] (not [8,0,0,0]), and [2,2,4,0] -> [4,4,0,0].
To handle the other directions, extract lines so that "toward index 0" always matches the move:
LEFT: rows as they are.RIGHT: rows reversed, then reverse the result back.UP: columns top to bottom.DOWN: columns bottom to top, then reverse the result back.
def merge_line(line):
out, gained, last_merged = [], 0, False
for v in line:
if v == 0:
continue
if out and out[-1] == v and not last_merged:
out[-1] *= 2
gained += out[-1]
last_merged = True
else:
out.append(v)
last_merged = False
out += [0] * (len(line) - len(out))
return out, gained
class Game:
def __init__(self, config, rng):
self.cfg, self.rng = config, rng
self.board = Board(config.size)
self.score, self.won = 0, False
self.history = []
for _ in range(config.initial_tiles):
self._spawn()
def move(self, d):
before = self.board.copy()
lines = self.board.lines(d)
results = [merge_line(l) for l in lines]
new_lines = [r[0] for r in results]
gained = sum(r[1] for r in results)
self.board.write_lines(d, new_lines)
if self.board == before:
return False # invalid move: no spawn, no score
self.history.append((before, self.score, self.won))
self.score += gained
if self.board.max() >= self.cfg.target:
self.won = True
self._spawn()
return True
def is_game_over(self):
b = self.board
if b.empty_cells():
return False
return not any(b.has_equal_neighbor(r, c) for r, c in b.cells())
Key rules to get right
- Merge once per move: the
last_mergedflag prevents chaining, so[4,2,2,0]becomes[4,4,0,0]rather than[8,0,0,0]. - Spawn only on change: compare the board before and after. If equal, return without spawning, scoring or recording history. This also stops a stuck player from filling the board.
- Win detection: set
wonthe first time any tile reaches the target. Keep it as a flag, so play can continue and the win is reported once. - Game over: the board is full and no two horizontally or vertically adjacent cells are equal. Checking only for a full board is a common mistake. Run the check after the spawn, because the spawn can fill the last cell.
- Spawn when the board is full: guard against it. A move that changed the board always frees at least one cell, but a defensive check is cheap.
Complexity
A move touches each cell a constant number of times, so time is $O(N^2)$ and extra space is $O(N^2)$ for the copy. Game-over detection is also $O(N^2)$. Spawning is $O(N^2)$ to list empty cells, which is fine at this size.
Extensions
- Undo: the history stack holds
(board snapshot, score, won). At 16 cells a snapshot is tiny, so snapshots beat reverse-computing a move, which is lossy because merges cannot be uniquely inverted. Cap the depth with a deque if required. Note that the spawn is part of what was undone, so redo would need the stored spawn. - Custom board size:
Ncomes fromGameConfig, and nothing inmerge_lineor the line extraction assumes 4. - Deterministic tests: inject
random.Random(seed), or a scriptedSpawnPolicythat returns a fixed sequence of (cell, value) pairs. Tests then assert exact boards. - Configurable spawn probabilities:
SpawnPolicytakes a weight table, for example{2: 0.9, 4: 0.1}, and the game never hardcodes it. - Persistence or networking later:
BoardandGamestate are plain data, so serializing them is trivial. Moves can be exposed as commands (move(direction)), which fits a client/server split.
Testing strategy
- Table-driven tests for
merge_line: empty line, single tile,[2,2,2,2],[2,2,4,4],[2,0,2,4],[4,2,2,0], and a line that is already compressed. - Direction tests on a fixed 4x4 board for all four moves, checking that RIGHT and DOWN are the mirror images of LEFT and UP.
- A no-op move leaves the score, board and history unchanged and spawns nothing.
- A seeded full-game test, plus constructed boards for the win and game-over states, including a full board that still has a legal move.
- Undo restores the board, score and won flag exactly.
Common mistakes
- Allowing a freshly merged tile to merge again in the same move.
- Spawning a tile after an invalid move.
- Declaring game over whenever the board is full.
- Using a global random function, which makes tests flaky.
- Writing four separate move implementations instead of one merge function plus line extraction.
- Mixing printing or input handling into
Game.