In 2048, the board is simply a fixed 4×4 grid. A clean mental model is a 2D array of integers: 0 means “empty,” and any other value (2, 4, 8, …) is a tile. The UI is just presentation—the real game is the move logic.
1) Forget directions first: reduce everything to “move left”
You can understand the entire game by solving one problem: how a single line moves to the left. Every direction can be transformed into that same operation:
- Move right: reverse the line, move left, then reverse back
- Move up/down: treat each column as a line (or rotate the board to reuse the same logic)
So the core is a one-line move; directions are just different ways to read/write lines.
2) A one-line move is always: compress → merge → compress
For one row (length 4), the move is always the same three-step sequence:
Step A — Compress (remove zeros)
Slide all non-zero values to the left while keeping their order; fill the remaining cells with zeros.
Example: [2, 0, 2, 4] → [2, 2, 4, 0]
Step B — Merge (combine equal neighbors)
Scan from left to right. If two adjacent tiles are equal, merge them into one (double the left tile), and the right tile becomes empty.
The key rule: a tile can merge at most once per move
This prevents “chain merging” in a single swipe.
Example: [2, 2, 2, 0] becomes [4, 2, 0, 0], not [8, 0, 0, 0].
And [2, 2, 2, 2] becomes [4, 4, 0, 0].
Step C — Compress again
Merging creates gaps, so you compress once more to produce a clean final line.
That’s it. A full board move is just applying this line operation to four lines (rows or columns).
3) Spawn a new tile: only after a valid move
After a move, the game spawns a new tile in a random empty cell. The important rule is:
- Only spawn if the move actually changed the board (a tile moved or merged)
Classic versions also use probabilities (commonly 2 appears more often than 4), but the key idea is “spawn only after a valid move.”
4) Game Over: not just “no empty cells”
The game ends when:
- There are no empty cells, and
- No adjacent tiles (up/down/left/right) are equal, meaning no merges are possible
If both are true, no direction can change the board—so you are Game Over.
Full runnable project (GitHub)
If you want the complete Java + Swing implementation (including images and a runnable entry point), the full project is here:
https://github.com/CashStolen/Java2048
Quick run (from the project root):
Windows
javac -d out src\Procedure.java src\MainFrame.java
java -cp out ProcedureLinux / macOS
javac -d out src/Procedure.java src/MainFrame.java
java -cp out ProcedureFeel free to add new methods in the .java files, or swap in prettier images to customize the look and feel of the game.
Finally, best wishes!
