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:
-
piece_cells(kind: str, rotation: int) -> List[Tuple[int, int]]- Each tetromino in
SHAPESsits inside ann x nsquare bounding box (4 x 4for"I",2 x 2for"O", and3 x 3for"T","S","Z","J","L"). - Apply
rotation % 4clockwise 90-degree turns to the occupied coordinates ofSHAPES[kind], where one clockwise turn inside ann x nbox maps(r, c)to(c, n - 1 - r). - Return the 4 occupied
(row, col)pairs sorted in ascending order.
- Each tetromino in
-
SevenBag(seed: Optional[int] = None)- Uses a dedicated
random.Random(seed)instance. next() -> strdeals pieces using the modern 7-bag rule: whenever the current bag is empty, load one copy of each letter inPIECES, shuffle them, and pop one piece per call so every group of 7 consecutive draws is a permutation of all 7 shapes.
- Uses a dedicated
-
Game(width: int = WIDTH, height: int = HEIGHT, sequence: Optional[List[str]] = None, seed: Optional[int] = None)- Grid & public state:
boardis a list ofheightrows, each a list ofwidthone-character strings holding"."(EMPTY) or a locked piece letter (row = 0is the top row). Active falling pieces are tracked separately fromboarduntil they lock. Exposeboard,width,height,kind(the active piece letter, orNoneonce the match ends),score,lines,game_over, andpieces_locked. - Piece source & spawning: Draw pieces cyclically from
sequenceif a non-empty list is supplied, or fromSevenBag(seed)otherwise. Spawn the first piece during__init__. Every spawned piece begins atrotation = 0, box top atrow = 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 onboard, setgame_over = Trueandkind = None. - Queries:
cells() -> List[Tuple[int, int]]: board(row, col)coordinates currently covered by the active piece ([]oncegame_overisTrue).render() -> str:heightnewline-separated strings of lengthwidthshowingboardwith the active piece drawn on top, without mutatingboard.
- Actions (once
game_overisTrue, all boolean actions do nothing and returnFalse, andhard_drop()returns0):move_left() -> boolandmove_right() -> bool: shift the active piece by-1or+1column if all 4 cells stay inside the grid over".".rotate(clockwise: bool = True) -> bool: turn+1quarter turn whenclockwiseisTrue(or-1whenFalse), trying each horizontal column offset inKICKS = [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 intoboard, incrementpieces_locked, delete every full row (rows with no".") while shifting upper rows down and prepending fresh"."rows at the top, add cleared rows tolines, addLINE_SCORES[cleared]toscorewhen at least one row clears, spawn the next piece, and returnFalse.soft_drop() -> bool: execute onetick(), adding1point toscoreif the piece moved down.hard_drop() -> int: slide the active piece down as many rows as possible, add2 * rows_droppedtoscore, lock it immediately (applying line clears and next-piece spawn), and returnrows_dropped.
- Grid & public state:
-
apply_command(game: Game, command: str) -> Noneandrun_terminal(game: Game, read_line=input, write=print) -> Noneapply_commanddispatches"a"(move_left),"d"(move_right),"w"(rotate(True)),"z"(rotate(False)),"s"(soft_drop), and"x"(hard_drop), ignoring unrecognized characters.run_terminalrepeats untilgame.game_over: writegame.render()and a status line, read a command line viaread_line("> ")(exiting immediately onEOFErroror if"q"appears anywhere in the line), pass each character toapply_command, and callgame.tick()once. Whengame.game_overends the loop, writegame.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 <= 20and4 <= height <= 40(defaultsWIDTH = 10,HEIGHT = 20).kindis always one of"I","O","T","S","Z","J","L".rotationpassed topiece_cellsmay be any integer (positive, zero, or negative).- At most
4rows can be completed by a single locked piece (LINE_SCOREScovers1..4). Gamemethods must be purely deterministic with zero wall-clock sleeps or direct standard I/O.
Step-by-step walkthrough
Pin down the rules and separate game state from I/O
Tetris has seven 4-square shapes (tetrominoes):
I,O,T,S,Z,J, andLfalling down a10-wide by20-tall grid. Before writing any code, we make two architectural choices that keep the implementation tiny and 100% deterministic to test:- Keep the falling piece separate from the locked board.
self.board(20rows of10strings, with row0at the top and row19at the bottom) stores only"."(EMPTY) and already-locked blocks. The active falling piece lives in four variables:kind,rotation(0..3),row, andcol. That way, moving or rotating a piece never has to "erase" old squares fromself.boardor avoid colliding with itself. - Keep
Gamecompletely free of clocks,input(), andprint(). Gravity is exposed as an explicitgame.tick()method, and randomness comes from an injectablesequenceor seededSevenBag(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 onrow = 0, centered horizontally atcol = (width - box_size) // 2. If any of its 4 squares already has a locked block,game_overbecomesTrue. - 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 / 800points for clearing1 / 2 / 3 / 4lines at once, plus1point per soft-drop row and2points per hard-drop row.- Keep the falling piece separate from the locked board.
Represent tetrominoes and rotate their bounding boxes
Each tetromino sits inside a small square bounding box (an imaginary
n x nframe around the piece:4 x 4forI,2 x 2forO, and3 x 3forT, 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 ngrid, turning 90 degrees clockwise moves the top row (r = 0) to the rightmost column (new_c = n - 1), and columncbecomes the new rownew_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
Istarts on row1("IIII") inside a4 x 4box: one clockwise turn maps row1to column4 - 1 - 1 = 2(rows0..3, column2), soIcan rotate vertically right after spawning atrow = 0without 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)Deal fair pieces with a 7-bag randomizer
Picking each piece independently at random (
random.choice("IOTSZJL")) can starve a player of anIpiece for 30+ turns or deal fourZpieces 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 privaterandom.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()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)withrotation, would all 4 occupied squares land inside0 <= r < height,0 <= c < width, and onEMPTY(".") cells?Building everything on
_fitseliminates "move then undo" bugs: - Left / right / down (_move): check_fitsat(row + d_row, col + d_col)first; updateself.rowandself.colonly when it returnsTrue. - 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 verticalIis pressed flush against the left wall (col = -2, occupying board column0). Rotating flat atcol = -2would place squares at columns-2, -1, 0, 1(off-board!), sorotatetriescol_shiftin[0, -1, 1, -2, 2]and succeeds on+2(columns0, 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 atrotation = 0,row = 0,col = (width - box_size) // 2. If_fitsisFalse, setself.game_over = Trueandself.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- Spawning (
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 returnsTrue; if blocked below, it calls_lock()and returnsFalse. -soft_drop()callstick()and adds+1point when the piece moved down a row. -hard_drop()loopswhile self._move(1, 0): rows_dropped += 1, adds2 * rows_droppedpoints, and immediately calls_lock().Inside
_lock(), we stamp the 4 squares ofself.cells()intoself.board, clear any completed rows, addLINE_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"."intokept_rows, countcleared = height - len(kept_rows), and prependclearedfresh empty rows on top. That works even when cleared rows are non-adjacent (for example, a verticalIcompleting rows16and18while row17has 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 clearedNotice a rock-solid invariant you can assert after every move in tests: every locked piece contributes
4blocks and every cleared line removeswidth(10) blocks, so total non-empty cells onself.boardalways equals4 * pieces_locked - 10 * lines.Connect a testable terminal loop
render()copiesself.boardrow by row, overlays the active piece's 4 coordinates onto the copy, and joins rows with"\n". Never draw ontoself.boarddirectly, or rendering would permanently lock the falling piece!Then
run_terminaltakesread_line(defaultinput) andwrite(defaultprint) 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}")Trace a concrete three-line clear
Let's trace Example 2 (
Game(sequence=["J", "S"])) when row17is filled with"X"everywhere except columns4and5, rows18and19are filled everywhere except column4, and row16has a lone"T"at column0: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- Spawn and rotate:
J(3 x 3box) spawns atrow = 0,col = (10 - 3) // 2 = 3. One clockwise rotation gives local cells(0, 1), (0, 2), (1, 1), (2, 1), covering board columns4, 5on its top row and column4on its lower two rows. - Soft drop + hard drop:
soft_drop()steps torow = 1(+1point). Thenhard_drop()advances16more rows torow = 17(2 * 16 = 32points), bringing the drop score to33. - Lock and clear:
Jwrites into(17, 4), (17, 5), (18, 4), (19, 4), completing rows17,18, and19simultaneously ("." not in row)._clear_full_rowsremoves those 3 rows and prepends 3 empty rows at the top, shifting"T........."from row16down to row19. - Score and next spawn:
cleared = 3addsLINE_SCORES[3] = 500for a total score of33 + 500 = 533,lines = 3, and"S"spawns cleanly at the top.
- Spawn and rotate:
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:
- Spawn:
J(3 x 3bounding box, an imaginary square frame around the piece) spawns atrow = 0,col = (10 - 3) // 2 = 3, covering(0,3), (1,3), (1,4), (1,5). - Rotate / move check: Every move or rotation calls
_fits(new_rotation, new_row, new_col). TurningJclockwise once maps its occupied squares onto(0,4), (0,5), (1,4), (2,4); if a rotation hits a wall,rotatetries wall kicks (small sideways column nudges[0, -1, 1, -2, 2]) and keeps the first offset where all 4 cells fit. - Soft drop and hard drop:
soft_drop()steps down1row (+1point), andhard_drop()steps down16more rows torow = 17(+32points), where moving torow = 18fails_fitsbecause18 + 2 = 20is off the bottom. - Lock and clear:
_lock()stamps"J"into(17,4), (17,5), (18,4), (19,4), completing rows17,18, and19together._clear_full_rows()filters out full rows, prepends3empty rows at the top, awards500points (533total), 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, andtick(when not locking): Each runs in O(1) time and O(1) space because a tetromino always has 4 cells inside at most a4 x 4box, androtatetests at most 5 kick offsets (5 * 4 = 20array 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._lockand_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 updated20 x 10grid (200 cells per locked piece).render: Runs in O(W * H) time and space to copy the20 x 10board, overlay the 4 active cells, and join the strings.- Overall memory:
Gamestores theheight x widthboard plus a 7-elementSevenBaglist, using O(W * H) space.
Edge cases
- Rotating
Iat the side walls: A verticalIagainst the left wall has its4 x 4box atcol = -2; shifts0,-1,+1, and-2still leave cells outside column0, so the+2offset inKICKSis essential to kick it onto columns0..3. - Rotating
Iright after spawn: BecauseIsits on row1of its4 x 4box and spawns withself.row = 0, rotating vertical places its cells on rows0..3, fitting cleanly inside the top of the board instead of clippingrow = -1. - Rotation blocked inside a narrow well: When all 5 offsets in
KICKScollide with walls or blocks,rotatereturnsFalseand leaves(rotation, row, col)completely untouched. - Clearing non-adjacent rows: If a vertical
Icompletes rows16and18while row17still has a hole,[row for row in self.board if EMPTY in row]preserves row17in order and shifts everything above row16down by 2 rows. - Actions after game over: Once
_spawndetects an overlap at the top,self.game_over = Trueandself.kind = None; every subsequent move, rotation, drop, or tick returnsFalse(or0forhard_drop) without mutatingboardorscore. EOFErrorin the terminal loop: Closing standard input (for example, piping scripted moves intopython solution.py) exitsrun_terminalcleanly instead of crashing with an unhandled exception.
Common mistakes
- Mutating
self.boardinsiderender(): Drawing the active piece directly intoself.boardinstead 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]insidefor r in range(height):shifts rowr + 1into indexrand skips checking it on the next iteration, leaving consecutive full rows uncleared. - Checking collision after mutating coordinates: Updating
self.col -= 1first and trying to undo on collision is error-prone when rotations modify bothrotationandcol; always check_fitson 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 (IandO) drift or round inconsistently across four quarter turns. - Using global
random.shuffle: Calling module-levelrandomshares state acrossGameinstances, 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_tickscounter toGamethat starts at0whenever a piece spawns or successfully moves down a row. Whentick()finds_move(1, 0)blocked, incrementlock_ticksinstead of locking immediately, and call_lock()only oncelock_ticks >= lock_delay_limit(say2ticks); resetlock_ticks = 0on a successful move or rotation, capped at15resets 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 calltick()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
KICKSlist with a dictionary keyed by(piece_group, from_rotation, to_rotation)mapping to five(d_row, d_col)pairs — SRS uses one table forJ, L, S, T, Zand a second table forI, including negatived_rowoffsets ("floor kicks") that lift a piece over a 1-block lip. To detect a T-spin on_lock(), record a booleanlast_action_was_rotate: ifkind == "T",last_action_was_rotateisTrue, and at least 3 of the 4 diagonal corners ofT's3 x 3box 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, multiplyLINE_SCORES[cleared]bylevel, and let the real-time loop shorten the interval betweentick()calls aslevelincreases. BecauseGamehas zero wall-clock dependencies and draws pieces solely fromSevenBag(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_fitscall, 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 = 1023and 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 a20 x 10list of strings is much easier to read and render in an interview.
Follow-up questions
- How would you introduce a lock delay so players can nudge a piece briefly after touching the stack?
- How could you extend horizontal kicks into the full Super Rotation System (SRS) and detect T-spins?
- How would you add progression levels and compact deterministic match replays?
Similar questions
- Eddington Number of Daily Rides
- Shortest Connection Degree in a Social Network
- Shortest Substring Run-Length Encoding and Decoding
- Validate and Expand an IPv6 Address
- Upper-Tail Probability of 1,000 Die Rolls
- Dynamic Dynasty Succession Without an Initial Monarch