KatInterview

Build a Terminal Block-Stacking Game Engine

Data Structure DesignModel answer
MediumModel answerData Structure Designgame-logicstate-machinesimulation

Last 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.