Build a Terminal Block-Stacking Game Engine
Data Structure DesignModel answerLast updated
Design a testable, terminal-friendly engine for a falling-block puzzle on a 10x20 grid, covering movement, rotation, gravity, locking, line clearing and game over.
Build the core engine for a falling-block puzzle game (the classic seven-piece stacking game) that can be driven from a terminal. No graphical interface is needed. Plain-text rendering, or an API that a terminal loop can call, is enough.
Requirements
- Grid: 10 columns by 20 rows.
- Pieces: the seven four-cell shapes named
I, O, T, S, Z, J, L. - Player actions: move left or right, rotate, soft drop (one row down on demand), and hard drop (fall straight to the bottom and lock).
- Gravity: the active piece falls one row at regular intervals. When it cannot fall any further, it locks into the grid.
- Line clears: every completely filled row is removed, and the rows above it shift down.
- End condition: the game is over when a newly spawned piece has no room to appear.
Deliverable
A cleanly organized implementation, with a minimal terminal loop or a callable API. Correctness and structure (especially testability) matter more than presentation.
Decisions you should make and document
- How rotation behaves at walls and against stacked cells (for example, no adjustment versus simple "kick" offsets).
- How scoring works (a simplified scheme is fine).
- How the next piece is chosen (uniform random versus a shuffled-bag approach).
In your answer, describe the architecture, explain why the state can never become invalid, discuss edge cases and complexity, and include code.
Hints
Hint 1
Treat the active piece as an immutable value. Build a candidate for every action (move, rotate, drop) and commit it only if the grid says the placement is valid.
Hint 2
Store each piece as cell offsets inside a small bounding box and precompute its four rotations once by rotating coordinates. Keep the grid, the piece logic and the game state machine in separate units so each can be tested without a terminal.
Hint 3
For line clearing, do not delete rows while iterating. Keep the rows that still contain an empty cell, then prepend the right number of blank rows at the top. Route gravity, soft drop and hard drop through one shared lock-and-spawn path, and inject the random source so tests are deterministic.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the engine into small units with clear responsibilities so that nearly everything is testable without a terminal.
- Shape data. Each piece is a set of
(row, col)cells inside a square bounding box (4x4 forI, 2x2 forO, 3x3 for the rest). The four orientations are precomputed once by rotating clockwise:(r, c) -> (c, n-1-r). Piece. An immutable value holdingkind,rotation,row,col, with a method that returns its absolute cells.Board. Owns the grid. It answers "is this placement valid?", locks a piece into the grid, and clears full rows.Game. The state machine. It exposesmove,rotate,soft_drop,hard_drop,tick(one gravity step) andupdate(dt_ms)(time-based gravity). The terminal loop only calls these and prints a rendering.- Randomizer. A shuffled-bag generator that receives its random source as a parameter, so tests can seed it.
Design decisions (documented)
- Rotation: clockwise and counter-clockwise, with simple kicks. Try column offsets
0, -1, +1, -2, +2, then one row up. This is not a full official rotation system, but it is deterministic and handles walls and the longIpiece. If every offset fails, the rotation is rejected and the state is unchanged. - Scoring: line clears give 0/100/300/500/800 for 0 to 4 lines. Soft drop gives +1 per row and hard drop +2 per row.
- Randomizer: a shuffled bag of all seven pieces, refilled when empty. This prevents long droughts of any one piece.
- Spawn: centered horizontally at the top. If the spawn cells collide with the stack, the game is over.
Why the state is always valid
The active piece changes only through one helper that builds a candidate and validates every one of its four cells (in bounds and unoccupied) before committing. No mutation happens before validation, so an out-of-bounds or overlapping piece can never be observed.
Gravity, soft drop and hard drop all end in the same lock_and_spawn routine: lock the piece, clear lines, update score, spawn the next piece. Sharing that path means locking behavior cannot diverge between the three entry points.
Line clearing
Keep, in order, every row that has at least one empty cell. The number of removed rows is height - len(kept). Prepend that many empty rows. This handles non-adjacent full rows and multi-line clears in a single pass, and avoids the classic bug of deleting while iterating and skipping a row.
Complexity
| Operation | Time |
|---|---|
| move, rotate, tick | O(1): 4 cells checked, at most 6 kick attempts |
| hard drop | O(H) |
| lock + clear | O(W*H), 200 cells |
| render | O(W*H) |
Space is O(W*H) for the grid, plus constant-size rotation tables.
Edge cases
- Rotation against a wall or the floor uses kicks; if all fail, nothing changes.
- The
Ipiece standing vertically at a wall may need a 2-column kick. Orotation is an identical shape, so it is a harmless no-op.- Hard drop with zero distance locks immediately and scores 0 drop points.
- Multiple and non-contiguous clears, including four at once.
- Spawn collision sets
game_over; afterwards every action and tick is a no-op. - A large
dt(lag spike) applies several gravity steps in a loop, stopping early if the game ends.
Common mistakes
- Mutating the piece first and "undoing" on failure, which leaks invalid states.
- Duplicating lock logic in tick, soft drop and hard drop.
- Deleting rows from the list while iterating.
- Using global randomness, which makes tests flaky.
- Forgetting that actions must be ignored after game over.
Code (Python)
import random
from dataclasses import dataclass, replace
WIDTH, HEIGHT = 10, 20
SHAPES = {
"I": (4, [(1, 0), (1, 1), (1, 2), (1, 3)]),
"O": (2, [(0, 0), (0, 1), (1, 0), (1, 1)]),
"T": (3, [(0, 1), (1, 0), (1, 1), (1, 2)]),
"S": (3, [(0, 1), (0, 2), (1, 0), (1, 1)]),
"Z": (3, [(0, 0), (0, 1), (1, 1), (1, 2)]),
"J": (3, [(0, 0), (1, 0), (1, 1), (1, 2)]),
"L": (3, [(0, 2), (1, 0), (1, 1), (1, 2)]),
}
def _rotations(size, cells):
states = [tuple(sorted(cells))]
for _ in range(3):
cells = [(c, size - 1 - r) for r, c in cells]
states.append(tuple(sorted(cells)))
return states
ROTATIONS = {k: _rotations(s, c) for k, (s, c) in SHAPES.items()}
KICKS = [(0, 0), (0, -1), (0, 1), (0, -2), (0, 2), (-1, 0)]
LINE_SCORES = [0, 100, 300, 500, 800]
@dataclass(frozen=True)
class Piece:
kind: str
rotation: int
row: int
col: int
def cells(self):
return [(self.row + r, self.col + c)
for r, c in ROTATIONS[self.kind][self.rotation % 4]]
class Board:
def __init__(self, w=WIDTH, h=HEIGHT):
self.width, self.height = w, h
self.grid = [[None] * w for _ in range(h)]
def is_valid(self, p):
return all(0 <= r < self.height and 0 <= c < self.width
and self.grid[r][c] is None for r, c in p.cells())
def lock(self, p):
for r, c in p.cells():
self.grid[r][c] = p.kind
def clear_lines(self):
keep = [row for row in self.grid if any(x is None for x in row)]
cleared = self.height - len(keep)
self.grid = [[None] * self.width for _ in range(cleared)] + keep
return cleared
class SevenBag:
def __init__(self, rng):
self.rng, self.bag = rng, []
def next(self):
if not self.bag:
self.bag = list(SHAPES)
self.rng.shuffle(self.bag)
return self.bag.pop()
class Game:
def __init__(self, rng=None, gravity_ms=500):
self.board = Board()
self.bag = SevenBag(rng or random.Random())
self.score = self.lines = 0
self.game_over = False
self.gravity_ms, self._elapsed = gravity_ms, 0
self.active = None
self._spawn()
def _spawn(self):
kind = self.bag.next()
size = SHAPES[kind][0]
p = Piece(kind, 0, 0, (self.board.width - size) // 2)
if self.board.is_valid(p):
self.active = p
else:
self.active, self.game_over = None, True
def _try(self, cand):
if self.board.is_valid(cand):
self.active = cand
return True
return False
def _lock_and_spawn(self):
self.board.lock(self.active)
n = self.board.clear_lines()
self.lines += n
self.score += LINE_SCORES[n]
self._spawn()
def move(self, dc):
if self.game_over:
return False
return self._try(replace(self.active, col=self.active.col + dc))
def rotate(self, direction=1):
if self.game_over:
return False
p = self.active
rot = (p.rotation + direction) % 4
for dr, dc in KICKS:
if self._try(replace(p, rotation=rot,
row=p.row + dr, col=p.col + dc)):
return True
return False
def tick(self):
if self.game_over:
return
if not self._try(replace(self.active, row=self.active.row + 1)):
self._lock_and_spawn()
def soft_drop(self):
if self.game_over:
return
if self._try(replace(self.active, row=self.active.row + 1)):
self.score += 1
else:
self._lock_and_spawn()
def hard_drop(self):
if self.game_over:
return
while self._try(replace(self.active, row=self.active.row + 1)):
self.score += 2
self._lock_and_spawn()
def update(self, dt_ms):
self._elapsed += dt_ms
while self._elapsed >= self.gravity_ms and not self.game_over:
self._elapsed -= self.gravity_ms
self.tick()
def render(self):
cells = {} if self.game_over else {rc: "#" for rc in self.active.cells()}
rows = []
for r in range(self.board.height):
rows.append("".join(
cells.get((r, c)) or (self.board.grid[r][c] or ".")
for c in range(self.board.width)))
return "\n".join(rows)
Testing strategy
Seed the randomizer for determinism. Unit-test the board directly (fill rows by hand, check single, multiple and non-adjacent clears). Test rotation at walls, move rejection, hard-drop distance, spawn collision producing game over, and large-dt updates.