Build a Terminal-Ready Tetris Engine

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Build a deterministic, clock-free Tetris engine in pure Python together with a thin text-mode runner that drives it from line-oriented commands.

Using the module constants defined in starter.py (WIDTH = 10, HEIGHT = 20, EMPTY = ".", PIECES = "IOTSZJL", SHAPES, LINE_SCORES = {1: 100, 2: 300, 3: 500, 4: 800}, and KICKS = [0, -1, 1, -2, 2]), implement the following components:

  1. piece_cells(kind: str, rotation: int) -> List[Tuple[int, int]]

    • Each tetromino in SHAPES sits inside an n x n square bounding box (4 x 4 for "I", 2 x 2 for "O", and 3 x 3 for "T", "S", "Z", "J", "L").
    • Apply rotation % 4 clockwise 90-degree turns to the occupied coordinates of SHAPES[kind], where one clockwise turn inside an n x n box maps (r, c) to (c, n - 1 - r).
    • Return the 4 occupied (row, col) pairs sorted in ascending order.
  2. SevenBag(seed: Optional[int] = None)

    • Uses a dedicated random.Random(seed) instance.
    • next() -> str deals pieces using the modern 7-bag rule: whenever the current bag is empty, load one copy of each letter in PIECES, shuffle them, and pop one piece per call so every group of 7 consecutive draws is a permutation of all 7 shapes.
  3. Game(width: int = WIDTH, height: int = HEIGHT, sequence: Optional[List[str]] = None, seed: Optional[int] = None)

    • Grid & public state: board is a list of height rows, each a list of width one-character strings holding "." (EMPTY) or a locked piece letter (row = 0 is the top row). Active falling pieces are tracked separately from board until they lock. Expose board, width, height, kind (the active piece letter, or None once the match ends), score, lines, game_over, and pieces_locked.
    • Piece source & spawning: Draw pieces cyclically from sequence if a non-empty list is supplied, or from SevenBag(seed) otherwise. Spawn the first piece during __init__. Every spawned piece begins at rotation = 0, box top at row = 0, and box left column at (width - box_size) // 2. If any of its 4 squares lies out of bounds or overlaps a locked cell on board, set game_over = True and kind = None.
    • Queries:
      • cells() -> List[Tuple[int, int]]: board (row, col) coordinates currently covered by the active piece ([] once game_over is True).
      • render() -> str: height newline-separated strings of length width showing board with the active piece drawn on top, without mutating board.
    • Actions (once game_over is True, all boolean actions do nothing and return False, and hard_drop() returns 0):
      • move_left() -> bool and move_right() -> bool: shift the active piece by -1 or +1 column if all 4 cells stay inside the grid over ".".
      • rotate(clockwise: bool = True) -> bool: turn +1 quarter turn when clockwise is True (or -1 when False), trying each horizontal column offset in KICKS = [0, -1, 1, -2, 2] in order and committing the first placement that fits.
      • tick() -> bool: advance gravity by one row (True) if unobstructed; otherwise stamp the active piece's 4 cells into board, increment pieces_locked, delete every full row (rows with no ".") while shifting upper rows down and prepending fresh "." rows at the top, add cleared rows to lines, add LINE_SCORES[cleared] to score when at least one row clears, spawn the next piece, and return False.
      • soft_drop() -> bool: execute one tick(), adding 1 point to score if the piece moved down.
      • hard_drop() -> int: slide the active piece down as many rows as possible, add 2 * rows_dropped to score, lock it immediately (applying line clears and next-piece spawn), and return rows_dropped.
  4. apply_command(game: Game, command: str) -> None and run_terminal(game: Game, read_line=input, write=print) -> None

    • apply_command dispatches "a" (move_left), "d" (move_right), "w" (rotate(True)), "z" (rotate(False)), "s" (soft_drop), and "x" (hard_drop), ignoring unrecognized characters.
    • run_terminal repeats until game.game_over: write game.render() and a status line, read a command line via read_line("> ") (exiting immediately on EOFError or if "q" appears anywhere in the line), pass each character to apply_command, and call game.tick() once. When game.game_over ends the loop, write game.render() and a final summary line.

Examples

Example 1

Input:
  game = Game(sequence=["L", "J"])
  game.rotate(clockwise=True)
  for _ in range(4):
      game.move_right()
  dropped = game.hard_drop()

Output:
  dropped == 17
  game.score == 34
  game.lines == 0
  game.pieces_locked == 1
  game.kind == "J"
  "".join(game.board[17]) == "........L."
  "".join(game.board[18]) == "........L."
  "".join(game.board[19]) == "........LL"

Walk-through: "L" (3 x 3 box) spawns at row = 0, col = 3. One clockwise turn places its 4 blocks at local coordinates (0, 1), (1, 1), (2, 1), (2, 2). Four right shifts move col to 7, pressing the piece flush against column 9. Hard-dropping moves it down 17 rows to row = 17 (2 * 17 = 34 points), locks "L" into rows 17..19, clears 0 lines, and spawns "J" at the top.

Example 2

Input:
  game = Game(sequence=["J", "S"])
  game.board[16][0] = "T"
  # Fill row 17 with "X" except columns 4 and 5; fill rows 18 and 19 with "X" except column 4.
  game.rotate(clockwise=True)
  game.soft_drop()
  dropped = game.hard_drop()

Output:
  dropped == 16
  game.lines == 3
  game.score == 533
  game.pieces_locked == 1
  game.kind == "S"
  "".join(game.board[18]) == ".........."
  "".join(game.board[19]) == "T........."

Walk-through: Rotating "J" clockwise once gives local cells (0, 1), (0, 2), (1, 1), (2, 1), which occupy board columns 4, 5 on its top row and column 4 on its lower two rows. One soft_drop() advances to row = 1 (+1 point), and hard_drop() falls 16 more rows to row = 17 (+32 points), plugging (17, 4), (17, 5), (18, 4), (19, 4). Rows 17, 18, and 19 all become full and clear together (+500 points, 533 total), shifting the lone "T" from row 16 down 3 rows to row 19.

Constraints

  • 4 <= width <= 20 and 4 <= height <= 40 (defaults WIDTH = 10, HEIGHT = 20).
  • kind is always one of "I", "O", "T", "S", "Z", "J", "L".
  • rotation passed to piece_cells may be any integer (positive, zero, or negative).
  • At most 4 rows can be completed by a single locked piece (LINE_SCORES covers 1..4).
  • Game methods must be purely deterministic with zero wall-clock sleeps or direct standard I/O.

Step-by-step walkthrough

  1. Pin down the rules and separate game state from I/O

    Tetris has seven 4-square shapes (tetrominoes): I, O, T, S, Z, J, and L falling down a 10-wide by 20-tall grid. Before writing any code, we make two architectural choices that keep the implementation tiny and 100% deterministic to test:

    1. Keep the falling piece separate from the locked board. self.board (20 rows of 10 strings, with row 0 at the top and row 19 at the bottom) stores only "." (EMPTY) and already-locked blocks. The active falling piece lives in four variables: kind, rotation (0..3), row, and col. That way, moving or rotating a piece never has to "erase" old squares from self.board or avoid colliding with itself.
    2. Keep Game completely free of clocks, input(), and print(). Gravity is exposed as an explicit game.tick() method, and randomness comes from an injectable sequence or seeded SevenBag(seed). A separate thin front-end (run_terminal) owns user input and screen output.
      Terminal Loop (run_terminal)          Game State Machine (Game)
      ----------------------------          -----------------------------------------
      read_line() / timer  ----calls---->   move_left / move_right / rotate
                           ----calls---->   soft_drop / hard_drop / tick
      write(game.render()) <---queries---   board (locked cells) + (kind, rot, row, col)
    

    Let's also document the open rules upfront: - Spawn position: rotation 0, bounding-box top on row = 0, centered horizontally at col = (width - box_size) // 2. If any of its 4 squares already has a locked block, game_over becomes True. - Wall kicks: if a rotation hits a wall or block, try horizontal column shifts [0, -1, 1, -2, 2] and accept the first one that fits. - Scoring: 100 / 300 / 500 / 800 points for clearing 1 / 2 / 3 / 4 lines at once, plus 1 point per soft-drop row and 2 points per hard-drop row.

  2. Represent tetrominoes and rotate their bounding boxes

    Each tetromino sits inside a small square bounding box (an imaginary n x n frame around the piece: 4 x 4 for I, 2 x 2 for O, and 3 x 3 for T, S, Z, J, L). Rotating the entire square box — rather than trying to pivot around a fractional center — gives every piece clean integer coordinates matching the standard Tetris rotation states.

    In an n x n grid, turning 90 degrees clockwise moves the top row (r = 0) to the rightmost column (new_c = n - 1), and column c becomes the new row new_r = c. So every occupied cell (r, c) maps to (c, n - 1 - r):

    T-piece inside its 3x3 box (n = 3):
    
      rotation 0           rotation 1           rotation 2           rotation 3
      . T .  (0,1)         . T .  (0,1)         . . .                . T .  (0,1)
      T T T  (1,0..2)  ->  . T T  (1,1),(1,2)-> T T T  (1,0..2)  ->  T T .  (1,0),(1,1)
      . . .                . T .  (2,1)         . T .  (2,1)         . T .  (2,1)
    

    Notice why I starts on row 1 ("IIII") inside a 4 x 4 box: one clockwise turn maps row 1 to column 4 - 1 - 1 = 2 (rows 0..3, column 2), so I can rotate vertically right after spawning at row = 0 without sticking out above the top of the board!

    SHAPES = {
        "I": ["....", "IIII", "....", "...."],
        "O": ["OO", "OO"],
        "T": [".T.", "TTT", "..."],
        "S": [".SS", "SS.", "..."],
        "Z": ["ZZ.", ".ZZ", "..."],
        "J": ["J..", "JJJ", "..."],
        "L": ["..L", "LLL", "..."],
    }
    
    LINE_SCORES = {1: 100, 2: 300, 3: 500, 4: 800}
    KICKS = [0, -1, 1, -2, 2]
    
    
    def piece_cells(kind: str, rotation: int) -> List[Tuple[int, int]]:
        """Cells (row, col) of a piece inside its box after `rotation` clockwise quarter turns."""
        rows = SHAPES[kind]
        size = len(rows)
    
        cells: List[Tuple[int, int]] = []
        for r in range(size):
            for c in range(size):
                if rows[r][c] != EMPTY:
                    cells.append((r, c))
    
        quarter_turns = rotation % 4
        for _ in range(quarter_turns):
            turned: List[Tuple[int, int]] = []
            for r, c in cells:
                turned.append((c, size - 1 - r))
            cells = turned
    
        return sorted(cells)
    
  3. Deal fair pieces with a 7-bag randomizer

    Picking each piece independently at random (random.choice("IOTSZJL")) can starve a player of an I piece for 30+ turns or deal four Z pieces in a row. Modern Tetris uses a 7-bag randomizer: put one copy of all 7 tetrominoes into a list, shuffle it, deal all 7 one by one, and only then refill and reshuffle. Every group of 7 pieces is guaranteed to contain one of each shape, and using a private random.Random(seed) avoids mutating Python's global random generator.

    class SevenBag:
        """Deals the 7 pieces in a shuffled order, then reshuffles: every piece once per 7."""
    
        def __init__(self, seed: Optional[int] = None):
            self.rng = random.Random(seed)
            self.bag: List[str] = []
    
        def next(self) -> str:
            if not self.bag:
                self.bag = list(PIECES)
                self.rng.shuffle(self.bag)
            return self.bag.pop()
    
  4. Drive movement, wall kicks, and spawning from one collision check

    Every positioning rule reduces to a single helper _fits(rotation, row, col): if we placed the active piece's box at (row, col) with rotation, would all 4 occupied squares land inside 0 <= r < height, 0 <= c < width, and on EMPTY (".") cells?

    Building everything on _fits eliminates "move then undo" bugs: - Left / right / down (_move): check _fits at (row + d_row, col + d_col) first; update self.row and self.col only when it returns True. - Rotation with wall kicks (rotate): a wall kick nudges a rotating piece sideways when its rotated shape would clip a wall or neighbor block. Suppose a vertical I is pressed flush against the left wall (col = -2, occupying board column 0). Rotating flat at col = -2 would place squares at columns -2, -1, 0, 1 (off-board!), so rotate tries col_shift in [0, -1, 1, -2, 2] and succeeds on +2 (columns 0, 1, 2, 3):

    Vertical I against left wall (box col = -2):     Rotate clockwise -> kick +2 (box col = 0):
      col: -2 -1 | 0  1  2  3                          col: | 0  1  2  3
           .  .  | I  .  .  .                               | .  .  .  .
           .  .  | I  .  .  .     shift 0,-1,+1,-2 fail     | .  .  .  .
           .  .  | I  .  .  .     shift +2 fits!   ------>  | I  I  I  I
           .  .  | I  .  .  .                               | .  .  .  .
                 ^ left wall                                ^ left wall
    
    • Spawning (_spawn): place the new piece at rotation = 0, row = 0, col = (width - box_size) // 2. If _fits is False, set self.game_over = True and self.kind = None.
        def _fits(self, rotation: int, row: int, col: int) -> bool:
            for local_r, local_c in piece_cells(self.kind, rotation):
                board_r = row + local_r
                board_c = col + local_c
                if board_r < 0 or board_r >= self.height or board_c < 0 or board_c >= self.width:
                    return False
                if self.board[board_r][board_c] != EMPTY:
                    return False
            return True
    
        def _move(self, d_row: int, d_col: int) -> bool:
            if self.game_over:
                return False
            target_row = self.row + d_row
            target_col = self.col + d_col
            if not self._fits(self.rotation, target_row, target_col):
                return False
            self.row = target_row
            self.col = target_col
            return True
    
        def rotate(self, clockwise: bool = True) -> bool:
            if self.game_over:
                return False
            step = 1 if clockwise else 3
            new_rotation = (self.rotation + step) % 4
            for col_shift in KICKS:
                if self._fits(new_rotation, self.row, self.col + col_shift):
                    self.rotation = new_rotation
                    self.col += col_shift
                    return True
            return False
    
  5. Handle gravity, drops, locking, and line clears

    Gravity and drops share _move(1, 0) and _lock(): - tick() tries _move(1, 0). If that succeeds, it returns True; if blocked below, it calls _lock() and returns False. - soft_drop() calls tick() and adds +1 point when the piece moved down a row. - hard_drop() loops while self._move(1, 0): rows_dropped += 1, adds 2 * rows_dropped points, and immediately calls _lock().

    Inside _lock(), we stamp the 4 squares of self.cells() into self.board, clear any completed rows, add LINE_SCORES[cleared], and spawn the next piece. Clearing full rows without index-skipping bugs is a clean filter-and-pad operation: collect all rows that still contain at least one "." into kept_rows, count cleared = height - len(kept_rows), and prepend cleared fresh empty rows on top. That works even when cleared rows are non-adjacent (for example, a vertical I completing rows 16 and 18 while row 17 has a gap)!

        def _lock(self) -> None:
            for r, c in self.cells():
                self.board[r][c] = self.kind
            self.pieces_locked += 1
    
            cleared = self._clear_full_rows()
            if cleared > 0:
                self.lines += cleared
                self.score += LINE_SCORES[cleared]
    
            self._spawn()
    
        def _clear_full_rows(self) -> int:
            kept_rows = [row for row in self.board if EMPTY in row]
            cleared = self.height - len(kept_rows)
            fresh_top_rows = [[EMPTY] * self.width for _ in range(cleared)]
            self.board = fresh_top_rows + kept_rows
            return cleared
    

    Notice a rock-solid invariant you can assert after every move in tests: every locked piece contributes 4 blocks and every cleared line removes width (10) blocks, so total non-empty cells on self.board always equals 4 * pieces_locked - 10 * lines.

  6. Connect a testable terminal loop

    render() copies self.board row by row, overlays the active piece's 4 coordinates onto the copy, and joins rows with "\n". Never draw onto self.board directly, or rendering would permanently lock the falling piece!

    Then run_terminal takes read_line (default input) and write (default print) as arguments so automated tests can feed scripted commands like ["x", "q"] and inspect rendered frames without an interactive terminal:

    def apply_command(game: Game, command: str) -> None:
        if command == "a":
            game.move_left()
        elif command == "d":
            game.move_right()
        elif command == "w":
            game.rotate(clockwise=True)
        elif command == "z":
            game.rotate(clockwise=False)
        elif command == "s":
            game.soft_drop()
        elif command == "x":
            game.hard_drop()
    
    
    def run_terminal(
        game: Game,
        read_line: Callable[[str], str] = input,
        write: Callable[[str], None] = print,
    ) -> None:
        """Turn-based loop: show the board, read a line of commands, apply them, then tick once."""
        while not game.game_over:
            write(game.render())
            write(f"score {game.score}  lines {game.lines}  ({HELP})")
            try:
                line = read_line("> ")
            except EOFError:
                return
            if "q" in line:
                return
            for command in line:
                apply_command(game, command)
            game.tick()
        write(game.render())
        write(f"game over  score {game.score}  lines {game.lines}")
    
  7. Trace a concrete three-line clear

    Let's trace Example 2 (Game(sequence=["J", "S"])) when row 17 is filled with "X" everywhere except columns 4 and 5, rows 18 and 19 are filled everywhere except column 4, and row 16 has a lone "T" at column 0:

    After rotate + soft_drop:      On lock (before clear):        After _clear_full_rows():
    row 1:  ....JJ.... (active)    row 16: T.........             row 17: .......... (shifted!)
    row 2:  ....J..... (active)    row 17: XXXXJJXXXX (full!)     row 18: ..........
    row 3:  ....J..... (active)    row 18: XXXXJXXXXX (full!)     row 19: T......... (fell 3 rows)
    ...                            row 19: XXXXJXXXXX (full!)
    row 16: T.........
    row 17: XXXX..XXXX
    row 18: XXXX.XXXXX
    row 19: XXXX.XXXXX
    
    1. Spawn and rotate: J (3 x 3 box) spawns at row = 0, col = (10 - 3) // 2 = 3. One clockwise rotation gives local cells (0, 1), (0, 2), (1, 1), (2, 1), covering board columns 4, 5 on its top row and column 4 on its lower two rows.
    2. Soft drop + hard drop: soft_drop() steps to row = 1 (+1 point). Then hard_drop() advances 16 more rows to row = 17 (2 * 16 = 32 points), bringing the drop score to 33.
    3. Lock and clear: J writes into (17, 4), (17, 5), (18, 4), (19, 4), completing rows 17, 18, and 19 simultaneously ("." not in row). _clear_full_rows removes those 3 rows and prepends 3 empty rows at the top, shifting "T........." from row 16 down to row 19.
    4. Score and next spawn: cleared = 3 adds LINE_SCORES[3] = 500 for a total score of 33 + 500 = 533, lines = 3, and "S" spawns cleanly at the top.
  8. Complete solution

    from typing import Callable, List, Optional, Tuple
    import random
    
    WIDTH = 10
    HEIGHT = 20
    EMPTY = "."
    PIECES = "IOTSZJL"
    
    # Spawn orientation of each piece inside its square bounding box (standard SRS layout).
    # Rotating the entire square box keeps I inside 4x4, O inside 2x2, and the rest inside 3x3.
    SHAPES = {
        "I": ["....", "IIII", "....", "...."],
        "O": ["OO", "OO"],
        "T": [".T.", "TTT", "..."],
        "S": [".SS", "SS.", "..."],
        "Z": ["ZZ.", ".ZZ", "..."],
        "J": ["J..", "JJJ", "..."],
        "L": ["..L", "LLL", "..."],
    }
    
    # Points awarded when a single lock clears 1, 2, 3, or 4 full rows at once.
    LINE_SCORES = {1: 100, 2: 300, 3: 500, 4: 800}
    
    # Horizontal column offsets tried in order when a rotation overlaps a wall or block.
    # Including -2 and +2 lets a vertical 4-long I-piece kick away from either side wall.
    KICKS = [0, -1, 1, -2, 2]
    
    
    def piece_cells(kind: str, rotation: int) -> List[Tuple[int, int]]:
        """Cells (row, col) of a piece inside its box after `rotation` clockwise quarter turns."""
        rows = SHAPES[kind]
        size = len(rows)
    
        # Phase 1: collect the 4 occupied (row, col) coordinates in the spawn orientation.
        cells: List[Tuple[int, int]] = []
        for r in range(size):
            for c in range(size):
                if rows[r][c] != EMPTY:
                    cells.append((r, c))
    
        # Phase 2: apply `rotation % 4` clockwise 90-degree turns.
        # In a size x size grid, one clockwise turn sends (r, c) -> (c, size - 1 - r).
        quarter_turns = rotation % 4
        for _ in range(quarter_turns):
            turned: List[Tuple[int, int]] = []
            for r, c in cells:
                turned.append((c, size - 1 - r))
            cells = turned
    
        return sorted(cells)
    
    
    class SevenBag:
        """Deals the 7 pieces in a shuffled order, then reshuffles: every piece once per 7."""
    
        def __init__(self, seed: Optional[int] = None):
            # Use a dedicated Random instance so two games never interfere via global RNG state.
            self.rng = random.Random(seed)
            # self.bag: remaining piece letters in the current shuffled batch, e.g. ["L", "T", "I"]
            self.bag: List[str] = []
    
        def next(self) -> str:
            # Refill and shuffle all 7 tetrominoes whenever the current bag runs dry.
            if not self.bag:
                self.bag = list(PIECES)
                self.rng.shuffle(self.bag)
            return self.bag.pop()
    
    
    class Game:
        """Tetris rules with no I/O and no clock.
    
        board[row][col] holds EMPTY or the letter of a locked piece; row 0 is the top.
        Pieces come from `sequence` in order (cycling), or from SevenBag(seed) if none is given.
        The active piece is `kind` turned `rotation` quarter turns clockwise, with its box's
        top-left corner at (row, col). The caller decides when gravity happens by calling tick().
        """
    
        def __init__(
            self,
            width: int = WIDTH,
            height: int = HEIGHT,
            sequence: Optional[List[str]] = None,
            seed: Optional[int] = None,
        ):
            self.width = width
            self.height = height
            # self.board: height x width grid of "." or locked piece letters ("I", "O", "T", ...)
            # Active falling cells are NOT stored in self.board until the piece locks.
            self.board = [[EMPTY] * width for _ in range(height)]
            self.sequence = list(sequence) if sequence else []
            self.bag = SevenBag(seed)
            self.spawned = 0
            self.pieces_locked = 0
            self.score = 0
            self.lines = 0
            self.game_over = False
    
            # Active piece state: kind is None once game_over becomes True.
            self.kind: Optional[str] = None
            self.rotation = 0
            self.row = 0
            self.col = 0
            self._spawn()
    
        # ---- queries
    
        def cells(self) -> List[Tuple[int, int]]:
            """Board cells covered by the active piece ([] once the game is over)."""
            if self.kind is None:
                return []
            result: List[Tuple[int, int]] = []
            for local_r, local_c in piece_cells(self.kind, self.rotation):
                result.append((self.row + local_r, self.col + local_c))
            return result
    
        def render(self) -> str:
            # Copy self.board before drawing the active piece so rendering never mutates game state.
            grid = [list(row) for row in self.board]
            for r, c in self.cells():
                grid[r][c] = self.kind
            rendered_rows = ["".join(row) for row in grid]
            return "\n".join(rendered_rows)
    
        # ---- player actions; each returns whether anything happened
    
        def move_left(self) -> bool:
            return self._move(0, -1)
    
        def move_right(self) -> bool:
            return self._move(0, 1)
    
        def rotate(self, clockwise: bool = True) -> bool:
            if self.game_over:
                return False
            # Counter-clockwise is equivalent to +3 clockwise quarter turns modulo 4.
            step = 1 if clockwise else 3
            new_rotation = (self.rotation + step) % 4
            # Try offset 0 (in-place) first, then small left/right wall kicks in KICKS order.
            for col_shift in KICKS:
                if self._fits(new_rotation, self.row, self.col + col_shift):
                    self.rotation = new_rotation
                    self.col += col_shift
                    return True
            return False
    
        def tick(self) -> bool:
            """One gravity step: move down a row, or lock the piece if it rests on something."""
            if self.game_over:
                return False
            if self._move(1, 0):
                return True
            # Gravity could not move the piece down: stamp it onto the board and spawn the next one.
            self._lock()
            return False
    
        def soft_drop(self) -> bool:
            """A gravity step the player asks for; 1 point if the piece moved."""
            moved = self.tick()
            if moved:
                self.score += 1
            return moved
    
        def hard_drop(self) -> int:
            """Drop to the lowest free position and lock at once; 2 points per row. Returns the rows."""
            if self.game_over:
                return 0
            rows_dropped = 0
            while self._move(1, 0):
                rows_dropped += 1
            self.score += 2 * rows_dropped
            self._lock()
            return rows_dropped
    
        # ---- internals
    
        def _fits(self, rotation: int, row: int, col: int) -> bool:
            # Every one of the 4 piece cells must lie within board bounds and land on EMPTY (".").
            for local_r, local_c in piece_cells(self.kind, rotation):
                board_r = row + local_r
                board_c = col + local_c
                if board_r < 0 or board_r >= self.height or board_c < 0 or board_c >= self.width:
                    return False
                if self.board[board_r][board_c] != EMPTY:
                    return False
            return True
    
        def _move(self, d_row: int, d_col: int) -> bool:
            if self.game_over:
                return False
            target_row = self.row + d_row
            target_col = self.col + d_col
            if not self._fits(self.rotation, target_row, target_col):
                return False
            self.row = target_row
            self.col = target_col
            return True
    
        def _next_kind(self) -> str:
            if self.sequence:
                kind = self.sequence[self.spawned % len(self.sequence)]
            else:
                kind = self.bag.next()
            self.spawned += 1
            return kind
    
        def _spawn(self) -> None:
            self.kind = self._next_kind()
            self.rotation = 0
            # Place the bounding box top at row 0 (so I spawns on row 1 with room to rotate up to row 0).
            self.row = 0
            box_size = len(SHAPES[self.kind])
            self.col = (self.width - box_size) // 2
            # End condition: if the freshly spawned piece overlaps locked blocks, the game ends.
            if not self._fits(0, self.row, self.col):
                self.game_over = True
                self.kind = None
    
        def _lock(self) -> None:
            # Phase 1: permanently write the active piece's 4 cells into self.board.
            for r, c in self.cells():
                self.board[r][c] = self.kind
            self.pieces_locked += 1
    
            # Phase 2: remove completed rows and award line-clear points.
            cleared = self._clear_full_rows()
            if cleared > 0:
                self.lines += cleared
                self.score += LINE_SCORES[cleared]
    
            # Phase 3: spawn the next piece (which checks the game-over condition).
            self._spawn()
    
        def _clear_full_rows(self) -> int:
            # Keep every row that still has at least one "." cell, preserving top-to-bottom order.
            kept_rows = [row for row in self.board if EMPTY in row]
            cleared = self.height - len(kept_rows)
            # Prepend `cleared` fresh empty rows at the top so surviving rows shift down naturally.
            fresh_top_rows = [[EMPTY] * self.width for _ in range(cleared)]
            self.board = fresh_top_rows + kept_rows
            return cleared
    
    
    # ---- terminal front end
    
    HELP = "a/d move, w/z rotate, s soft drop, x hard drop, q quit"
    
    
    def apply_command(game: Game, command: str) -> None:
        if command == "a":
            game.move_left()
        elif command == "d":
            game.move_right()
        elif command == "w":
            game.rotate(clockwise=True)
        elif command == "z":
            game.rotate(clockwise=False)
        elif command == "s":
            game.soft_drop()
        elif command == "x":
            game.hard_drop()
    
    
    def run_terminal(
        game: Game,
        read_line: Callable[[str], str] = input,
        write: Callable[[str], None] = print,
    ) -> None:
        """Turn-based loop: show the board, read a line of commands, apply them, then tick once."""
        while not game.game_over:
            write(game.render())
            write(f"score {game.score}  lines {game.lines}  ({HELP})")
            try:
                line = read_line("> ")
            except EOFError:
                return
            if "q" in line:
                return
            for command in line:
                apply_command(game, command)
            game.tick()
        write(game.render())
        write(f"game over  score {game.score}  lines {game.lines}")
    
    
    if __name__ == "__main__":
        run_terminal(Game())
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine holding a clear plastic stencil with 4 painted squares over a 20 x 10 sheet of graph paper. While a tetromino (one of the seven 4-square Tetris shapes) is falling, you never draw ink onto the paper; you simply slide or turn the plastic stencil by updating its (row, col, rotation) numbers and checking whether its 4 squares sit inside the page over blank cells. Only when the stencil cannot slide down any further do you stamp its 4 letters onto the graph paper, snip out any completely filled horizontal strips, slide the upper strips down, and pick up the next stencil.

A naive beginner implementation writes the falling piece directly into board on every move and couples gravity to time.sleep(). Writing the active piece into board forces you to erase its 4 old cells before checking whether the moved piece collides with anything — forget one branch and the piece collides with itself or leaves ghost blocks behind. Putting timers or input() inside Game makes unit tests slow and flaky instead of deterministic microsecond method calls.

Walk through a tiny concrete trace on a 20 x 10 board where row 17 is filled everywhere except columns 4 and 5 and rows 18 and 19 are filled everywhere except column 4:

  1. Spawn: J (3 x 3 bounding box, an imaginary square frame around the piece) spawns at row = 0, col = (10 - 3) // 2 = 3, covering (0,3), (1,3), (1,4), (1,5).
  2. Rotate / move check: Every move or rotation calls _fits(new_rotation, new_row, new_col). Turning J clockwise once maps its occupied squares onto (0,4), (0,5), (1,4), (2,4); if a rotation hits a wall, rotate tries wall kicks (small sideways column nudges [0, -1, 1, -2, 2]) and keeps the first offset where all 4 cells fit.
  3. Soft drop and hard drop: soft_drop() steps down 1 row (+1 point), and hard_drop() steps down 16 more rows to row = 17 (+32 points), where moving to row = 18 fails _fits because 18 + 2 = 20 is off the bottom.
  4. Lock and clear: _lock() stamps "J" into (17,4), (17,5), (18,4), (19,4), completing rows 17, 18, and 19 together. _clear_full_rows() filters out full rows, prepends 3 empty rows at the top, awards 500 points (533 total), and spawns the next piece from the 7-bag randomizer (a deck of all 7 shapes shuffled and dealt without replacement before reshuffling).

Complexity

  • move_left, move_right, rotate, and tick (when not locking): Each runs in O(1) time and O(1) space because a tetromino always has 4 cells inside at most a 4 x 4 box, and rotate tests at most 5 kick offsets (5 * 4 = 20 array lookups).
  • hard_drop (falling step): Runs in O(H) time where H is the board height (20), testing 4 cells per row until the piece hits the floor or stack.
  • _lock and _clear_full_rows: Runs in O(W * H) time and space where W = 10 and H = 20 because we scan all H rows of length W to filter out completed lines and construct the updated 20 x 10 grid (200 cells per locked piece).
  • render: Runs in O(W * H) time and space to copy the 20 x 10 board, overlay the 4 active cells, and join the strings.
  • Overall memory: Game stores the height x width board plus a 7-element SevenBag list, using O(W * H) space.

Edge cases

  • Rotating I at the side walls: A vertical I against the left wall has its 4 x 4 box at col = -2; shifts 0, -1, +1, and -2 still leave cells outside column 0, so the +2 offset in KICKS is essential to kick it onto columns 0..3.
  • Rotating I right after spawn: Because I sits on row 1 of its 4 x 4 box and spawns with self.row = 0, rotating vertical places its cells on rows 0..3, fitting cleanly inside the top of the board instead of clipping row = -1.
  • Rotation blocked inside a narrow well: When all 5 offsets in KICKS collide with walls or blocks, rotate returns False and leaves (rotation, row, col) completely untouched.
  • Clearing non-adjacent rows: If a vertical I completes rows 16 and 18 while row 17 still has a hole, [row for row in self.board if EMPTY in row] preserves row 17 in order and shifts everything above row 16 down by 2 rows.
  • Actions after game over: Once _spawn detects an overlap at the top, self.game_over = True and self.kind = None; every subsequent move, rotation, drop, or tick returns False (or 0 for hard_drop) without mutating board or score.
  • EOFError in the terminal loop: Closing standard input (for example, piping scripted moves into python solution.py) exits run_terminal cleanly instead of crashing with an unhandled exception.

Common mistakes

  • Mutating self.board inside render(): Drawing the active piece directly into self.board instead of a shallow row copy permanently locks the piece onto the playfield every time the screen prints.
  • Deleting full rows in-place while iterating forward: Calling del self.board[r] inside for r in range(height): shifts row r + 1 into index r and skips checking it on the next iteration, leaving consecutive full rows uncleared.
  • Checking collision after mutating coordinates: Updating self.col -= 1 first and trying to undo on collision is error-prone when rotations modify both rotation and col; always check _fits on candidate values before assigning.
  • Rotating around per-piece centroids instead of a fixed square box: Computing (r - center_r, c - center_c) makes even-sized pieces (I and O) drift or round inconsistently across four quarter turns.
  • Using global random.shuffle: Calling module-level random shares state across Game instances, breaking deterministic replays when two seeded games run side by side.

Follow-up questions

  • How would you introduce a lock delay so players can nudge a piece briefly after touching the stack? Add a lock_ticks counter to Game that starts at 0 whenever a piece spawns or successfully moves down a row. When tick() finds _move(1, 0) blocked, increment lock_ticks instead of locking immediately, and call _lock() only once lock_ticks >= lock_delay_limit (say 2 ticks); reset lock_ticks = 0 on a successful move or rotation, capped at 15 resets so a player cannot stall forever by wiggling a piece endlessly. hard_drop() still calls _lock() immediately, and unit tests remain clock-free because they just call tick() the exact number of times.
  • How could you extend horizontal kicks into the full Super Rotation System (SRS) and detect T-spins? Replace the 1D KICKS list with a dictionary keyed by (piece_group, from_rotation, to_rotation) mapping to five (d_row, d_col) pairs — SRS uses one table for J, L, S, T, Z and a second table for I, including negative d_row offsets ("floor kicks") that lift a piece over a 1-block lip. To detect a T-spin on _lock(), record a boolean last_action_was_rotate: if kind == "T", last_action_was_rotate is True, and at least 3 of the 4 diagonal corners of T's 3 x 3 box are occupied or out-of-bounds, award T-spin bonus points.
  • How would you add progression levels and compact deterministic match replays? Compute level = 1 + self.lines // 10, multiply LINE_SCORES[cleared] by level, and let the real-time loop shorten the interval between tick() calls as level increases. Because Game has zero wall-clock dependencies and draws pieces solely from SevenBag(seed), recording (seed, [(step_index, command), ...]) is enough to replay an entire match frame-for-frame or synchronize two multiplayer boards over a network by sending inputs rather than full board states.

Alternative approaches

  • Hardcoded rotation lookup tables: Storing all 4 orientations per piece explicitly as coordinate tuples (ROTATIONS["T"][0..3]) avoids running the (c, size - 1 - r) loop on every _fits call, trading a larger constant table for slightly faster lookups.
  • Bitboard representation: Representing each 10-cell row as a 10-bit integer (where a full row equals (1 << 10) - 1 = 1023 and collision checking is a single bitwise &) runs orders of magnitude faster when building an AI search agent that evaluates thousands of candidate placements per turn, though a 20 x 10 list of strings is much easier to read and render in an interview.

Follow-up questions

Similar questions

More Liftoff interview questions

All 6 Liftoff questions →