A small, pure game core
The rules of this 2048 live in a few plain functions that take a board and return a new one, with no drawing code mixed in. The board is a list of tiles, each with a value, a row and a column. A move works one row (or column) at a time:
// for each line, walk tiles from the side you're sliding toward
for (const tile of line) {
if (last && !last.merged && last.value === tile.value) {
last.value *= 2; last.merged = true; // merge once per move
score += last.value;
} else {
place(tile, nextFreeCell++);
last = tile;
}
}
That is a simplified version of the game's code. Starting from the far side and marking merged tiles is what makes [2, 2, 2, 2] become [4, 4] and not [8], and makes [4, 2, 2] become [4, 4] rather than a single 8.
If a move changes nothing, it is thrown away: no new tile, no move counted, no score.
Randomness
New tiles go in a random empty cell, and are 2s with probability 0.9 and 4s with 0.1. The random number function is passed into the game core as a parameter, so a fixed sequence of tiles can be replayed exactly.
Undo, saving and checking saves
Undo keeps exactly one previous state, including the best score and win count, so undoing the move that reached 2048 also undoes the win. The current board, best score, statistics (games, wins, moves, merges) and sound setting are saved in your browser after every move. When the page loads, the saved board is validated before use: at most 16 tiles, no two in the same cell, every value a power of two between 2 and 131,072, and a "won" flag only if a 2048 tile exists. A damaged save starts a fresh game instead of breaking the page.
Accessibility
The board has a text description that lists every row, so screen readers can follow the game, and each move is announced ("Moved left. Score 432."). Sounds are short generated tones (300 Hz for a slide, 520 Hz for a merge) rather than audio files, and can be turned off.