Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 135 ยท Projects

Project: 2048 in the Terminal

Build 2048 in C: a one-row slide-and-merge function reused for all four directions through index mapping, then a full game with random tiles, redraw and game-over detection.

2048 looks like a graphics game, but the interesting part is a very small algorithm. You have a four-by-four grid of numbered tiles. When you press a direction, every tile slides as far as it can, and two equal tiles that collide merge into one tile with double the value. After each move a new 2 (or sometimes a 4) appears in a random empty cell. You lose when the grid is full and no neighbors are equal.

Most first attempts write four nearly identical blocks of loops, one per direction, and then spend an hour fixing the bug that is only in the "down" copy. The better design is to write the slide logic once for a single row moving left, and to map the other three directions onto it. That idea is the core of this project, and it applies well beyond games. The project uses two-dimensional arrays, functions with pointer parameters, enums, random numbers and character input. Stage 1 is the slide logic and the four directions. Stage 2 is the complete game.

Stage 1: slide and merge, one row at a time

The rules of one move on one line. Take a row, {2, 2, 4, 0}, and push it to the left. Tiles slide over empty cells, and then adjacent equal tiles merge. The result is {4, 4, 0, 0}. Two details make this tricky:

  • A tile merges at most once per move. {2, 2, 2, 2} becomes {4, 4, 0, 0}, not {8, 0, 0, 0}. The two new 4s must not merge into an 8 in the same move.
  • When three equal tiles are in a row, the pair closest to the wall merges. {2, 2, 2, 0} becomes {4, 2, 0, 0}.

A single pass does it all. slide_left builds a new row, out, and walks over the old row from left to right, skipping empty cells. For each tile, it asks one question: is the last tile I placed equal to this one, and has it not been merged yet? If so, it doubles that tile, marks it as merged, and adds the new value to the score. Otherwise the tile is placed at the next free position. Skipping zeros gives the sliding, and the merged flags give the "once per move" rule. It handles {2, 2, 2, 0} correctly without any special code: the first 2 is placed, the second doubles it, and the third finds a merged tile in front of it and is placed after it.

Did anything move? The game must not add a new tile when the move changed nothing, or the player could fill the board by pressing a useless key. So slide_left compares the new row with the old one and reports the result through an out-parameter (int *moved).

Four directions from one function. To slide a column upwards, think of reading the column from its top to its bottom as if it were a row. For downwards, read it from the bottom. For right, read the row from its right end. In every case you copy four cells into a temporary row, call slide_left, and copy the result back to the same cells. The only thing that changes between directions is which cell the i-th element of line k is. The function coords answers that question with a switch:

Direction row column
left k i
right k 3 - i
up i k
down 3 - i k

Four short lines of mapping replace four blocks of logic. If a bug exists in the sliding code, it exists in all directions at once and is therefore much easier to find. The alternative you may have heard of, rotating the whole grid, works too, but index mapping needs no extra copy of the grid.

C Stage 1: slide_left and the four directions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check the first table against the two rules: 2 2 2 2 gives 4 4 with a score of 8 (two merges of 4), 2 2 2 0 gives 4 2, and the already compact 2 4 2 4 reports no change. In the grid demo, move left and move right are mirror images of each other, and so are up and down. If they were not, you would know the coords table has a typo.

Stage 2: the complete game

New tiles. After a move that changed something, the game adds one tile. add_random_tile first counts the empty cells, then picks a random number n from 0 to empty - 1 and puts the tile in the n-th empty cell. Choosing a cell by position among the empty ones means it never loops, guessing random coordinates until it hits an empty one, which gets slow as the board fills up. The value is a 2 nine times out of ten and a 4 the rest of the time (rand() % 10 == 0).

Game over. The grid being full is not enough to lose: two equal neighbors mean a move still exists. has_move returns true when any cell is empty, or when any cell equals the one to its right or below it. Checking only right and down covers every neighboring pair exactly once. The game calls it after every new tile, and the program demonstrates it first on a hand-made stuck board, a checkerboard of alternating 2 and 4, so the false result is visible.

Input. The game reads one character at a time with getchar. The characters w, a, s and d move, q quits, and white space is ignored. This means you can type wasd on one line or press them one per line. A function key_to_dir turns a character into a direction, or into one of two special values for "quit" and "not a key". Keeping the key mapping in one function makes it easy to add arrow keys later. In a terminal, getchar only returns after Enter, because the terminal collects a whole line first. Reading single key presses without Enter needs the terminal to be switched to raw mode, which is platform-specific (termios on Linux and macOS), and is left as an exercise below.

Redrawing the screen. A real terminal game clears the screen between frames, so the board seems to stay in one place. The ANSI escape sequence ESC [ H ESC [ 2 J (cursor to the top-left, then clear the screen) does that on practically every modern terminal, and Windows 10 and later support it too. On this page the output is a log, not a terminal, so the code has a switch, USE_ANSI, which is 0 here. Set it to 1 in a real terminal to see the board redraw in place. A macro switch is a good habit for output that depends on where the program runs.

Game state. The game has a grid, a score, and a flag so the "You reached 2048" message appears once. It would be natural to put them in a struct and pass its address around, as in the library project. The code below keeps them as local variables in main to stay short.

C Stage 2: the whole game

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The board after each key press is printed below the previous one. Every move that changes the board adds one tile, so the number of tiles only drops when merges happen. A press that changes nothing prints (nothing moved) and does not add a tile. A game over is only checked after a move that worked, which is right: if the last move filled the board with no pair left, the check right after the new tile ends the game. The checkerboard test at the top is how you can try has_move without playing for an hour.

Ideas for going further

  • Arrow keys and raw mode. On Linux or macOS, switch the terminal to raw mode with tcsetattr, as in the user input lesson, and read arrow-key escape sequences.
  • Colors. Print each tile value in its own ANSI color; the values are powers of two, so the color can be chosen by counting how many times the value can be halved.
  • Undo. Keep a copy of the grid and score before each move and restore them on u.
  • High score. Save the best score to a file, as in the library project.
  • A computer player. Try each of the four moves on a copy of the grid and choose the one with the most empty cells, or the highest score. It will often beat a casual player.
  • Other sizes. Change SIZE to 5 or 3; the code should adapt, except for the %5d width and the table of keys.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does slide_left produce for the row {2, 2, 2, 2}?

    Each tile merges at most once per move. The two new 4s do not merge again, so the result is 4 4 0 0, with 8 points.
  2. 2. Why does the code have one slide function and a coordinate mapping instead of four separate movement functions?

    Left, right, up and down differ only in which cells form a line and in what order. Mapping those cells onto one row routine keeps the real logic in a single copy.
  3. 3. For direction DOWN, line k and position i, which cell does coords return?

    Moving down means the bottom cell of a column plays the role of index 0, so the position is counted from the bottom row upwards.
  4. 4. Why is a full grid not always game over?

    A move exists if a cell is empty or if two adjacent cells are equal, so has_move checks both conditions.
  5. 5. Why does the program add a new tile only when moved is true?

    In 2048 a move must change the board to count. Otherwise pressing a useless key repeatedly would add tiles with no benefit to the player.

Summary

  • Design the core rule for one case (a row sliding left) and map the other cases onto it, instead of copying the code four times.
  • A single left-to-right pass with a merged flag per output slot gives slide, merge-once and closest-to-the-wall behavior together.
  • Report whether a move changed anything, and add a new tile only if it did.
  • Choose a random empty cell by counting the empties and picking the n-th, never by guessing coordinates.
  • A move exists if any cell is empty or any two neighbors are equal; checking right and down covers all pairs.
  • Redrawing a screen needs ANSI escape codes, and single key presses need raw terminal mode; both are platform features worth hiding behind a switch or a function.

Next: the calendar project, where the algorithm is date arithmetic and the layout is the challenge.