Simulate 2048 Moves with Scripted Tile Spawns
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate a 4x4 sliding-tile merge game with scripted spawns, skipping spawns on no-op moves, then report the final board and whether any move remains.
2048 Replay Engine
You are building the deterministic core of a 2048-style game. Randomness is replaced by a pre-written script of spawns, so the same inputs always give the same result.
Implement a function that takes a starting 4x4 board and a list of moves. It applies the moves in order and returns the final board and whether the game is over.
Board and moves
- The board is a 4x4 grid of non-negative integers.
0means an empty cell. - Each move is one of
"left","right","up","down", matched case-insensitively ("LEFT"and"Left"are valid). - On a move, every tile slides as far as possible in that direction, stopping at the wall or at another tile.
- Two adjacent tiles with equal value (after sliding) merge into one tile of double the value.
- A tile may take part in at most one merge per move. A tile created by a merge cannot merge again in the same move. For example, a row
[2,2,2,2]moved left becomes[4,4,0,0], and[4,4,8,0]becomes[8,8,0,0]. - When three equal tiles are in a line, the pair closest to the wall being moved toward merges first.
[2,2,2,0]moved left becomes[4,2,0,0], and moved right becomes[0,0,2,4].
Spawning
- The move at index
iis paired withspawn_cells[i](a[row, col]pair) andspawn_tiles[i](the value to place). - If move
ichanged the board, the tilespawn_tiles[i]is placed atspawn_cells[i]after the slide and merge. - If move
idid not change the board, nothing spawns, and the spawn entry at indexiis simply ignored. Spawn entries are always looked up by the move's index, not by how many moves have succeeded so far. - When a spawn happens, it must be valid. Otherwise raise
ValueErrorif:- the value is not
2or4, - the position does not have exactly two elements,
- the position is outside the 4x4 grid,
- the target cell is not empty after the slide and merge.
- the value is not
Game over
After all moves, the game is over exactly when the board has no empty cell and no two orthogonally adjacent cells hold equal values. If moves is empty, evaluate this on the starting board.
Return value
Return a dictionary with two keys:
"board": the final board as a tuple of 4 tuples of 4 integers."game_over": a boolean.
The input board must not be modified.
Errors
Raise ValueError in each of these cases:
- the board is not 4x4,
- any board value is negative,
spawn_cellsorspawn_tileshas fewer entries thanmoves(checked before processing any move),- a move string is not one of the four directions (case-insensitive),
- a spawn is invalid, as described above.
Constraints
- The board is 4x4.
0 <= len(moves) <= 1000.- Board values are integers, and valid boards contain only non-negative values.
- Spawn lists may be longer than
moves. Extra entries are ignored.
Examples
Example 1
Input: simulate_2048([[2, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], ['left'], [[0, 2]], [2])
Output: {'board': [[4, 0, 2, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], 'game_over': False}
Example 2
Input: simulate_2048([[2, 2, 2, 2], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], ['left'], [[1, 0]], [4])
Output: {'board': [[4, 4, 0, 0], [4, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], 'game_over': False}
Example 3
Input: simulate_2048([[2, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], ['left'], [[0, 1]], [4])
Output: {'board': [[2, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], 'game_over': False}
Hints
Hint 1
Reduce every direction to one primitive that operates on a single line of 4 cells: drop zeros, merge equal neighbours from the front once, then pad with zeros.
Hint 2
For right and down, reverse the line, apply the same primitive, and reverse back. For up and down, extract each column into a list first and write the result back.
Hint 3
Take a copy of the grid before each move and compare afterwards to decide whether to spawn. Index the spawn data by the move's position in the list, and for the game-over check look at empties plus right and down neighbours.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every move reduces to one operation on a line of 4 cells: drop the zeros, scan from the front merging each pair of equal neighbours once (skipping both after a merge), then pad with zeros to length 4.
The four directions are orientation adapters around this primitive:
- Left: apply it to each row.
- Right: reverse each row, apply it, reverse back.
- Up: apply it to each column read top to bottom, then write the result back.
- Down: read each column bottom to top, apply it, reverse, and write back.
For each move, snapshot the grid before sliding and compare afterwards:
- If the grid is unchanged, the move is a no-op. Skip the spawn and move on. Its spawn entry is consumed implicitly, because entries are looked up by the move's index.
- If the grid changed, validate the spawn entry (value is 2 or 4, position has two elements, is in bounds, and targets an empty cell) and place the tile.
After all moves, the game is over exactly when no cell is empty and no two adjacent cells are equal. Checking each cell against its empty status and its right and down neighbours covers every adjacent pair once.
Why it is correct
- Merge once: after emitting a merged value, the scan advances by two, so the merged tile is never compared again. This gives
[2,2,2,2] -> [4,4,0,0]. - Merge priority: scanning from the front means the pair nearest the destination wall merges first, and reversing for right/down mirrors this exactly.
- Spawn only on change: comparing against the pre-move snapshot detects no-ops precisely.
- Game over: a move is possible iff there is an empty cell (tiles can slide) or an equal adjacent pair (they can merge).
- Immutability: the input is copied into a working grid and the result is a tuple of tuples.
Complexity
For k moves, time is O(k · 16), which is O(k) for the fixed 4x4 board. Space is O(16), which is O(1). On an N×N board these would be O(k · N²) time and O(N²) space.
Reference solution
from typing import List, Dict
def simulate_2048(board: List[List[int]], moves: List[str],
spawn_cells: List[List[int]], spawn_tiles: List[int]) -> Dict[str, object]:
grid = [list(row) for row in board]
if len(grid) != 4 or any(len(row) != 4 for row in grid):
raise ValueError('Board must be 4x4')
if any(v < 0 for row in grid for v in row):
raise ValueError('Tile values must be nonnegative')
if len(spawn_cells) < len(moves) or len(spawn_tiles) < len(moves):
raise ValueError('Insufficient spawn data')
def slide_line(line):
vals = [v for v in line if v != 0]
out = []
i = 0
while i < len(vals):
if i + 1 < len(vals) and vals[i] == vals[i + 1]:
out.append(vals[i] * 2)
i += 2
else:
out.append(vals[i])
i += 1
return out + [0] * (4 - len(out))
def apply_move(direction):
before = [row[:] for row in grid]
if direction in ('left', 'right'):
for r in range(4):
line = grid[r][:] if direction == 'left' else grid[r][::-1]
res = slide_line(line)
grid[r] = res if direction == 'left' else res[::-1]
elif direction in ('up', 'down'):
for c in range(4):
line = [grid[r][c] for r in range(4)]
if direction == 'down':
line.reverse()
res = slide_line(line)
if direction == 'down':
res.reverse()
for r in range(4):
grid[r][c] = res[r]
else:
raise ValueError('Invalid direction')
return grid != before
for i, direction in enumerate(moves):
if not apply_move(direction.lower()):
continue
cell = spawn_cells[i]
value = spawn_tiles[i]
if value not in (2, 4):
raise ValueError('Spawn value must be 2 or 4')
if len(cell) != 2:
raise ValueError('Spawn position must contain row and column')
r, c = cell
if not (0 <= r < 4 and 0 <= c < 4):
raise ValueError('Spawn position out of bounds')
if grid[r][c] != 0:
raise ValueError('Spawn position must be empty after the move')
grid[r][c] = value
game_over = True
for r in range(4):
for c in range(4):
if grid[r][c] == 0:
game_over = False
elif r + 1 < 4 and grid[r][c] == grid[r + 1][c]:
game_over = False
elif c + 1 < 4 and grid[r][c] == grid[r][c + 1]:
game_over = False
return {'board': tuple(tuple(row) for row in grid), 'game_over': game_over}