~/problems / Simulation & OOP design / Simulation

Tetris block drop

medium ~25 min Databricks

Simulate dropping one piece in a Tetris-style game.

def drop_block(background: list[list[int]], block: list[list[int]], offset: int) -> list[list[int]] | None
  • background is an H x W grid of 0 (empty) and 1 (filled). Row 0 is the top.
  • block is an h x w mask. Only its 1 cells are part of the piece; 0 cells are ignored completely (they may overlap filled cells, stick out of the grid, anything). The mask has at least one 1.
  • offset is the grid column where the mask's column 0 lines up. The mask always fits horizontally: 0 <= offset and offset + w <= W.

How the piece falls:

  1. It starts entirely above the grid: mask row i is at grid row i - h.
  2. It moves down one row at a time as long as, after the move, every 1 cell of the mask is either still above the grid (row < 0) or on an empty cell inside the grid (never below the last row).
  3. When it can't move any more, it stops. If any of its 1 cells is still above the grid, the piece doesn't fit: return None.
  4. Otherwise write the piece into a copy of the grid (don't modify the inputs), then clear full rows: every row made only of 1s is removed, the rows above it shift down, and empty rows are added at the top so the grid stays H x W. Return the new grid.
background = [
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [1, 0, 0, 1],
    [1, 1, 0, 1],
]
block = [
    [1, 1],
    [0, 1],
]
drop_block(background, block, 1)
# The piece's right column slides down column 2 until its lower cell sits at row 3;
# its top row lands on row 2 (cells (2,1) and (2,2)). Rows 2 and 3 become full and are cleared:
# [[0, 0, 0, 0],
#  [0, 0, 0, 0],
#  [0, 0, 0, 0],
#  [0, 0, 0, 0]]

drop_block([[0, 1], [0, 1]], [[1, 1]], 0)
# None: column 1 is filled at the top, so the piece can't even enter the grid

Grids are at most 200 x 200.

Show hint

Write fits(r) that checks the piece with its top mask row at grid row r (skip 0 cells, allow rows < 0, reject rows >= H and filled cells). Start at r = -h and increase r while fits(r + 1). For clearing, keep the rows that aren't all 1s and pad the top with fresh zero rows.

Topic: Simulation. Model the process exactly; watch simultaneous updates and direction arithmetic.

0:00
Ctrl ' run · Ctrl ↵ submit
esc