---
title: "Build a 2048 Game in Pseudocode, Step by Step: Programming Fundamentals (14)"
date: "2026-11-15"
description: "Plan and build a 2048 style game in pseudocode with arrays, matrices, loops and functions, save it to a file, and learn how to keep learning with AI agents."
tags: ["Programming Fundamentals", "Tutorials"]
url: "https://rolandoandrade.me/blog/programming-fundamentals-final-project/"
author: "Rolando Andrade"
---

# Build a 2048 Game in Pseudocode, Step by Step: Programming Fundamentals (14)

> Plan and build a 2048 style game in pseudocode with arrays, matrices, loops and functions, save it to a file, and learn how to keep learning with AI agents.

The final project of the course is a number puzzle game called **N210**. It is the game 2048, made general so it works with any starting number from 1 to 10. In this lesson you plan it, build it piece by piece in StepCode, and save games to a file with Python.

When you finish, you have a complete game that you can play in your browser. This is the start of a real game, where the player typed `2` for N, then `u` to move up, then `q` to quit:

```text
Type N [1-10]: 
Welcome to 2048
Up [u], down [d], left [l], right [r], quit [q]
Score: 0
0 0 0 0 
0 0 2 2 
0 0 0 0 
0 0 0 0 
R: 
Score: 0
4 0 2 2 
0 0 0 0 
0 0 0 0 
0 0 0 0 
R: 
Final score: 0. Thanks for playing.
```

In this lesson you will:

- Split a real problem into subprograms before you write any code.
- Slide and join a row of numbers, the heart of the game.
- Use a matrix for the board, random numbers for new tiles, and functions to check the rules.
- Join everything in one game loop.
- Save and load a game with a text file.
- Plan how to keep learning, now that AI agents write so much code.

It takes about 60 minutes. The game is about 230 lines of pseudocode, and it uses something from almost every lesson in the series.

## The rules of N210

2048 is played on a 4 by 4 grid. Here are the rules from the project brief, for any N:

- The game starts with two tiles worth N in random cells.
- Each turn, the player slides every tile up, down, left or right.
- When two tiles with the same value touch, they join into one tile worth their sum.
- After each move, a new tile appears in a random empty cell. It is worth N or 2N.
- The score starts at 0. Each time two tiles join, the score goes up by the value of the new tile.
- The player wins on reaching a tile worth N × 2¹⁰, which is N × 1024. After a win, the player can keep playing in sandbox mode.
- The game ends when the board is full and no two neighbors have the same value.

With N = 2 you get the classic 2048. N = 3 gives 3072, and N = 5 gives 5120.

Play a few moves before you build it. This board follows the same rules and the same steps you will write in this lesson.

*Figure: Slide with the buttons, or click the board and use the arrow keys. A new tile appears only after a move that changes something. Change N to see the same game with other numbers.*

## Why build a project

Each lesson taught one idea in a small program. Real programs mix all of them, and the hard part is deciding how they fit together. A project is where you practice that.

In my course, writing the project was worth 0 points. The whole grade came from the **defense**, where students showed each feature working and added a new feature in a reasonable time. Today that rule makes even more sense. An AI agent can write a 2048 game in seconds. What it cannot do for you is understand the code, explain it, and change it with confidence. That is the skill this project trains.

## Plan before you code

Do not start with the first line of code. Start with a list of jobs, then give each job to a subprogram. A good subprogram does one thing and has a name that says what it does.

The data is small:

- `board`, a 4 by 4 [matrix](/blog/programming-fundamentals-matrices/) of integers, where 0 means an empty cell.
- `score`, an integer.
- `n`, the starting number, and `target`, which is `n * 1024`.

The jobs fall into four groups:

*Figure: The game as a tree of subprograms. Each box is small enough to write and test on its own. Saving uses Python, because StepCode has no files.*

- **Board.** `ShowBoard` writes the score and the grid. `AddTile` puts a new tile in a random empty cell.
- **Moves.** `Move` slides the whole board. It copies each row or column into a small array and calls `SlideRight` or `SlideLeft`. Those use two helpers, `PushRight` and `Flip`.
- **Rules.** `HasWon` checks for the target tile. `CanMove` checks if any move is left.
- **Saving.** `save_game` and `load_game` write and read a text file.

You build the moves first, because they are the hardest part and everything else depends on them. Then the board, then the rules, then the loop.

## 1. Slide one row

This part comes from the third workshop of the course. Forget the grid for now and solve one row of 4 numbers. To slide a row to the right:

1. Push every non zero number to the right, keeping their order.
2. Join equal neighbors, starting from the right. Each join doubles one tile and empties the other.
3. Push to the right again, to close the gaps the joins left.

*Figure: Pick a row from the workshop and a direction, then press Next step. In 2 2 2 0, the two 2s on the right join into a 4, and the third 2 slides next to it. Try 2 2 2 2 to see that each tile joins only once.*

To slide left, you do not need new logic. Flip the row, slide it right, and flip it back. This trick of reusing a solution is common in programming.

The score is a `ByRef` parameter ([Procedures and functions](/blog/programming-fundamentals-procedures-and-functions/#by-value-or-by-reference)), because `SlideRight` must add points to the caller's variable.

**Final project, part 1: slide one row** (StepCode)

```stepcode
Program SlideOneRow
    Define row, right, left As Integer;
    Dimension row[4], right[4], left[4];
    Define i, score As Integer;
    Write "Type a row of 4 numbers, one per line:";
    For i <- 1 To 4 Step 1 Do
        Read row[i];
        right[i] <- row[i];
        left[i] <- row[i];
    EndFor
    score <- 0;
    SlideRight(right, score);
    WriteNoNewline "To the right: ";
    ShowRow(right);
    SlideLeft(left, score);
    WriteNoNewline "To the left: ";
    ShowRow(left);
    Write "Points from both moves: ", score;
EndProgram

// Moves the non zero numbers of the row to the right, keeping their order
Procedure PushRight(row As Integer[])
    Define i, target As Integer;
    target <- 4;
    For i <- 4 To 1 Step -1 Do
        If row[i] <> 0 Then
            row[target] <- row[i];
            If target <> i Then
                row[i] <- 0;
            EndIf
            target <- target - 1;
        EndIf
    EndFor
EndProcedure

// Slides a row of 4 to the right: push, join equal neighbors, push again
Procedure SlideRight(row As Integer[], score As Integer ByRef)
    Define i As Integer;
    PushRight(row);
    For i <- 4 To 2 Step -1 Do
        If row[i] <> 0 And row[i] = row[i - 1] Then
            row[i] <- row[i] * 2;
            row[i - 1] <- 0;
            score <- score + row[i];
        EndIf
    EndFor
    PushRight(row);
EndProcedure

// Reverses a row of 4 in place
Procedure Flip(row As Integer[])
    Define temp As Integer;
    temp <- row[1];
    row[1] <- row[4];
    row[4] <- temp;
    temp <- row[2];
    row[2] <- row[3];
    row[3] <- temp;
EndProcedure

// Slides a row to the left: flip, slide right, flip back
Procedure SlideLeft(row As Integer[], score As Integer ByRef)
    Flip(row);
    SlideRight(row, score);
    Flip(row);
EndProcedure

// Writes a row of 4 on one line
Procedure ShowRow(row As Integer[])
    Define i As Integer;
    For i <- 1 To 4 Step 1 Do
        WriteNoNewline row[i], " ";
    EndFor
    Write "";
EndProcedure
```

When you type `2`, `2`, `2` and `0`, you should see:

```text
Type a row of 4 numbers, one per line:
To the right: 0 0 2 4 
To the left: 4 2 0 0 
Points from both moves: 8
```

These are the examples from the workshop, and the program gives the same answers:

| Row | To the right | To the left |
| --- | --- | --- |
| `2 2 2 2` | `0 0 4 4` | `4 4 0 0` |
| `0 0 4 4` | `0 0 0 8` | `8 0 0 0` |
| `0 16 4 2` | `0 16 4 2` | `16 4 2 0` |
| `16 4 2 2` | `0 16 4 4` | `16 4 4 0` |
| `16 0 0 16` | `0 0 0 32` | `32 0 0 0` |

Try them in the editor. The row `2 2 2 2` is the tricky one, and you will see why in Common mistakes.

## 2. Move the whole board

A board move is four row moves. For left and right, `Move` copies each row into `line`. For up and down, it copies each column, from top to bottom. Down then means "slide the column right", and up means "slide it left". After the slide, it copies `line` back into the board.

`Move` is a function that returns `True` when any tile changed place. The game needs that, because a move that changes nothing does not get a new tile. The board is passed without `ByRef`, because arrays and matrices are always shared with the subprogram.

This program starts from a fixed board, so you can predict every result. `Lower`, from [Strings](/blog/programming-fundamentals-strings/#the-tools-for-strings), turns the command into lowercase, so `R` and `r` both work.

**Final project, part 2: move the board** (StepCode)

```stepcode
Program MoveTheBoard
    Define board As Integer;
    Dimension board[4, 4];
    Define i, j, score As Integer;
    Define direction As String;
    // A fixed start, so you can predict every move
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            board[i, j] <- 0;
        EndFor
    EndFor
    board[1, 3] <- 2;
    board[2, 2] <- 2;
    board[3, 3] <- 2;
    board[4, 1] <- 4;
    score <- 0;
    ShowBoard(board, score);
    Repeat
        Write "Move [u, d, l, r] or q to quit: ";
        Read direction;
        direction <- Lower(direction);
        If direction <> "q" Then
            If Move(board, direction, score) Then
                ShowBoard(board, score);
            Else
                Write "Nothing moved. Try another direction.";
            EndIf
        EndIf
    Until direction = "q";
EndProgram

// Moves the non zero numbers of the row to the right, keeping their order
Procedure PushRight(row As Integer[])
    Define i, target As Integer;
    target <- 4;
    For i <- 4 To 1 Step -1 Do
        If row[i] <> 0 Then
            row[target] <- row[i];
            If target <> i Then
                row[i] <- 0;
            EndIf
            target <- target - 1;
        EndIf
    EndFor
EndProcedure

// Slides a row of 4 to the right: push, join equal neighbors, push again
Procedure SlideRight(row As Integer[], score As Integer ByRef)
    Define i As Integer;
    PushRight(row);
    For i <- 4 To 2 Step -1 Do
        If row[i] <> 0 And row[i] = row[i - 1] Then
            row[i] <- row[i] * 2;
            row[i - 1] <- 0;
            score <- score + row[i];
        EndIf
    EndFor
    PushRight(row);
EndProcedure

// Reverses a row of 4 in place
Procedure Flip(row As Integer[])
    Define temp As Integer;
    temp <- row[1];
    row[1] <- row[4];
    row[4] <- temp;
    temp <- row[2];
    row[2] <- row[3];
    row[3] <- temp;
EndProcedure

// Slides a row to the left: flip, slide right, flip back
Procedure SlideLeft(row As Integer[], score As Integer ByRef)
    Flip(row);
    SlideRight(row, score);
    Flip(row);
EndProcedure

// Writes a row of 4 on one line
Procedure ShowRow(row As Integer[])
    Define i As Integer;
    For i <- 1 To 4 Step 1 Do
        WriteNoNewline row[i], " ";
    EndFor
    Write "";
EndProcedure

// Writes the score and the 4 by 4 board
Procedure ShowBoard(board As Integer[,], score As Integer)
    Define i, j As Integer;
    Write "Score: ", score;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            WriteNoNewline board[i, j], " ";
        EndFor
        Write "";
    EndFor
EndProcedure

// Moves the whole board. Returns True if any tile changed place.
Function Move(board As Integer[,], direction As String, score As Integer ByRef): Boolean
    Define line As Integer;
    Dimension line[4];
    Define k, i As Integer;
    Define changed As Boolean;
    changed <- False;
    For k <- 1 To 4 Step 1 Do
        // Copy row k (for l and r) or column k (for u and d) into line
        For i <- 1 To 4 Step 1 Do
            If direction = "l" Or direction = "r" Then
                line[i] <- board[k, i];
            Else
                line[i] <- board[i, k];
            EndIf
        EndFor
        If direction = "r" Or direction = "d" Then
            SlideRight(line, score);
        Else
            SlideLeft(line, score);
        EndIf
        // Copy line back and note any change
        For i <- 1 To 4 Step 1 Do
            If direction = "l" Or direction = "r" Then
                If board[k, i] <> line[i] Then
                    changed <- True;
                EndIf
                board[k, i] <- line[i];
            Else
                If board[i, k] <> line[i] Then
                    changed <- True;
                EndIf
                board[i, k] <- line[i];
            EndIf
        EndFor
    EndFor
    Return changed;
EndFunction
```

When you type `u`, `R`, `r` and `q`, you should see:

```text
Score: 0
0 0 2 0 
0 2 0 0 
0 0 2 0 
4 0 0 0 
Move [u, d, l, r] or q to quit: 
Score: 4
4 2 4 0 
0 0 0 0 
0 0 0 0 
0 0 0 0 
Move [u, d, l, r] or q to quit: 
Score: 4
0 4 2 4 
0 0 0 0 
0 0 0 0 
0 0 0 0 
Move [u, d, l, r] or q to quit: 
Nothing moved. Try another direction.
Move [u, d, l, r] or q to quit: 
```

The first move joined the two 2s in the third column into a 4, and the score went up by 4. The last `r` changed nothing, so the program said so.

## 3. Add tiles and rules

Three subprograms complete the rules:

- `AddTile` counts the empty cells, picks one with `RandomBetween`, and walks the board again until it reaches that cell. `RandomBetween(a, b)` gives back a random whole number from `a` to `b`, and both ends can come out, so `RandomBetween(1, empty)` picks any one of the empty cells. It writes N there, or 2N one time in ten, using `Random`, one of the [built in functions](/blog/programming-fundamentals-operators-and-expressions/#built-in-functions).
- `HasWon` returns `True` when any tile reaches the target. A function can stop at the first `Return True`.
- `CanMove` returns `True` when there is an empty cell, or two equal neighbors to the right or below.

To test them, the program builds a board where no move is possible, then empties one cell.

**Final project, part 3: tiles and rules** (StepCode)

```stepcode
Program CheckTheRules
    Define board As Integer;
    Dimension board[4, 4];
    Define i, j As Integer;
    // A full board where no two neighbors are equal
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            If (i + j) Mod 2 = 0 Then
                board[i, j] <- 2;
            Else
                board[i, j] <- 4;
            EndIf
        EndFor
    EndFor
    board[4, 4] <- 2048;
    ShowBoard(board, 0);
    Write "Won with N = 2 (target 2048)? ", HasWon(board, 2 * 1024);
    Write "Won with N = 3 (target 3072)? ", HasWon(board, 3 * 1024);
    Write "Can still move? ", CanMove(board);
    // Empty one cell and ask again
    board[1, 1] <- 0;
    Write "After emptying a cell, can move? ", CanMove(board);
    AddTile(board, 2);
    Write "AddTile filled it with: ", board[1, 1];
EndProgram

// Moves the non zero numbers of the row to the right, keeping their order
Procedure PushRight(row As Integer[])
    Define i, target As Integer;
    target <- 4;
    For i <- 4 To 1 Step -1 Do
        If row[i] <> 0 Then
            row[target] <- row[i];
            If target <> i Then
                row[i] <- 0;
            EndIf
            target <- target - 1;
        EndIf
    EndFor
EndProcedure

// Slides a row of 4 to the right: push, join equal neighbors, push again
Procedure SlideRight(row As Integer[], score As Integer ByRef)
    Define i As Integer;
    PushRight(row);
    For i <- 4 To 2 Step -1 Do
        If row[i] <> 0 And row[i] = row[i - 1] Then
            row[i] <- row[i] * 2;
            row[i - 1] <- 0;
            score <- score + row[i];
        EndIf
    EndFor
    PushRight(row);
EndProcedure

// Reverses a row of 4 in place
Procedure Flip(row As Integer[])
    Define temp As Integer;
    temp <- row[1];
    row[1] <- row[4];
    row[4] <- temp;
    temp <- row[2];
    row[2] <- row[3];
    row[3] <- temp;
EndProcedure

// Slides a row to the left: flip, slide right, flip back
Procedure SlideLeft(row As Integer[], score As Integer ByRef)
    Flip(row);
    SlideRight(row, score);
    Flip(row);
EndProcedure

// Writes a row of 4 on one line
Procedure ShowRow(row As Integer[])
    Define i As Integer;
    For i <- 1 To 4 Step 1 Do
        WriteNoNewline row[i], " ";
    EndFor
    Write "";
EndProcedure

// Writes the score and the 4 by 4 board
Procedure ShowBoard(board As Integer[,], score As Integer)
    Define i, j As Integer;
    Write "Score: ", score;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            WriteNoNewline board[i, j], " ";
        EndFor
        Write "";
    EndFor
EndProcedure

// Moves the whole board. Returns True if any tile changed place.
Function Move(board As Integer[,], direction As String, score As Integer ByRef): Boolean
    Define line As Integer;
    Dimension line[4];
    Define k, i As Integer;
    Define changed As Boolean;
    changed <- False;
    For k <- 1 To 4 Step 1 Do
        // Copy row k (for l and r) or column k (for u and d) into line
        For i <- 1 To 4 Step 1 Do
            If direction = "l" Or direction = "r" Then
                line[i] <- board[k, i];
            Else
                line[i] <- board[i, k];
            EndIf
        EndFor
        If direction = "r" Or direction = "d" Then
            SlideRight(line, score);
        Else
            SlideLeft(line, score);
        EndIf
        // Copy line back and note any change
        For i <- 1 To 4 Step 1 Do
            If direction = "l" Or direction = "r" Then
                If board[k, i] <> line[i] Then
                    changed <- True;
                EndIf
                board[k, i] <- line[i];
            Else
                If board[i, k] <> line[i] Then
                    changed <- True;
                EndIf
                board[i, k] <- line[i];
            EndIf
        EndFor
    EndFor
    Return changed;
EndFunction

// Puts N (9 times in 10) or 2N in a random empty cell
Procedure AddTile(board As Integer[,], n As Integer)
    Define i, j, empty, pick As Integer;
    empty <- 0;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            If board[i, j] = 0 Then
                empty <- empty + 1;
            EndIf
        EndFor
    EndFor
    If empty > 0 Then
        pick <- RandomBetween(1, empty);
        For i <- 1 To 4 Step 1 Do
            For j <- 1 To 4 Step 1 Do
                If board[i, j] = 0 Then
                    pick <- pick - 1;
                    If pick = 0 Then
                        If Random() < 0.9 Then
                            board[i, j] <- n;
                        Else
                            board[i, j] <- 2 * n;
                        EndIf
                    EndIf
                EndIf
            EndFor
        EndFor
    EndIf
EndProcedure

// True when some tile reached the target
Function HasWon(board As Integer[,], target As Integer): Boolean
    Define i, j As Integer;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            If board[i, j] >= target Then
                Return True;
            EndIf
        EndFor
    EndFor
    Return False;
EndFunction

// True when there is an empty cell or two equal neighbors
Function CanMove(board As Integer[,]): Boolean
    Define i, j As Integer;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            If board[i, j] = 0 Then
                Return True;
            EndIf
            If j < 4 Then
                If board[i, j] = board[i, j + 1] Then
                    Return True;
                EndIf
            EndIf
            If i < 4 Then
                If board[i, j] = board[i + 1, j] Then
                    Return True;
                EndIf
            EndIf
        EndFor
    EndFor
    Return False;
EndFunction
```

You should see:

```text
Score: 0
2 4 2 4 
4 2 4 2 
2 4 2 4 
4 2 4 2048 
Won with N = 2 (target 2048)? True
Won with N = 3 (target 3072)? False
Can still move? False
After emptying a cell, can move? True
AddTile filled it with: 2
```

The last line uses `Random`, so about one run in ten shows `4` instead of `2`. Press Run a few times to see it.

## 4. Play the full game

Now the main program joins everything. It reads N and checks that it is between 1 and 10. It places two tiles, then repeats a loop: read a command, check it, move, add a tile, and check the rules. It says when a command is unknown, and it asks once if you want to keep playing after a win.

Read the main program before you press Run. It is long, but each line calls a subprogram whose name says what happens.

**Final project, part 4: the complete N210 game** (StepCode)

```stepcode
Program N210
    Define board As Integer;
    Dimension board[4, 4];
    Define i, j, n, score, target As Integer;
    Define command, answer As String;
    Define won, playing As Boolean;
    Repeat
        Write "Type N [1-10]: ";
        Read n;
        If n < 1 Or n > 10 Then
            Write "N must be between 1 and 10.";
        EndIf
    Until n >= 1 And n <= 10;
    target <- n * 1024;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            board[i, j] <- 0;
        EndFor
    EndFor
    AddTile(board, n);
    AddTile(board, n);
    score <- 0;
    won <- False;
    playing <- True;
    Write "Welcome to ", target;
    Write "Up [u], down [d], left [l], right [r], quit [q]";
    ShowBoard(board, score);
    While playing Do
        Write "R: ";
        Read command;
        command <- Lower(command);
        If command = "q" Then
            playing <- False;
        ElseIf command <> "u" And command <> "d" And command <> "l" And command <> "r" Then
            Write "Unknown command: ", command;
        ElseIf Move(board, command, score) Then
            AddTile(board, n);
            ShowBoard(board, score);
            If Not won And HasWon(board, target) Then
                won <- True;
                Write "Wow, you won! Keep playing in sandbox mode? [Y/n]: ";
                Read answer;
                If Lower(answer) = "n" Then
                    playing <- False;
                EndIf
            ElseIf Not CanMove(board) Then
                Write "No moves left. Game over.";
                playing <- False;
            EndIf
        Else
            Write "Nothing moved. Try another direction.";
        EndIf
    EndWhile
    Write "Final score: ", score, ". Thanks for playing.";
EndProgram

// Moves the non zero numbers of the row to the right, keeping their order
Procedure PushRight(row As Integer[])
    Define i, target As Integer;
    target <- 4;
    For i <- 4 To 1 Step -1 Do
        If row[i] <> 0 Then
            row[target] <- row[i];
            If target <> i Then
                row[i] <- 0;
            EndIf
            target <- target - 1;
        EndIf
    EndFor
EndProcedure

// Slides a row of 4 to the right: push, join equal neighbors, push again
Procedure SlideRight(row As Integer[], score As Integer ByRef)
    Define i As Integer;
    PushRight(row);
    For i <- 4 To 2 Step -1 Do
        If row[i] <> 0 And row[i] = row[i - 1] Then
            row[i] <- row[i] * 2;
            row[i - 1] <- 0;
            score <- score + row[i];
        EndIf
    EndFor
    PushRight(row);
EndProcedure

// Reverses a row of 4 in place
Procedure Flip(row As Integer[])
    Define temp As Integer;
    temp <- row[1];
    row[1] <- row[4];
    row[4] <- temp;
    temp <- row[2];
    row[2] <- row[3];
    row[3] <- temp;
EndProcedure

// Slides a row to the left: flip, slide right, flip back
Procedure SlideLeft(row As Integer[], score As Integer ByRef)
    Flip(row);
    SlideRight(row, score);
    Flip(row);
EndProcedure

// Writes a row of 4 on one line
Procedure ShowRow(row As Integer[])
    Define i As Integer;
    For i <- 1 To 4 Step 1 Do
        WriteNoNewline row[i], " ";
    EndFor
    Write "";
EndProcedure

// Writes the score and the 4 by 4 board
Procedure ShowBoard(board As Integer[,], score As Integer)
    Define i, j As Integer;
    Write "Score: ", score;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            WriteNoNewline board[i, j], " ";
        EndFor
        Write "";
    EndFor
EndProcedure

// Moves the whole board. Returns True if any tile changed place.
Function Move(board As Integer[,], direction As String, score As Integer ByRef): Boolean
    Define line As Integer;
    Dimension line[4];
    Define k, i As Integer;
    Define changed As Boolean;
    changed <- False;
    For k <- 1 To 4 Step 1 Do
        // Copy row k (for l and r) or column k (for u and d) into line
        For i <- 1 To 4 Step 1 Do
            If direction = "l" Or direction = "r" Then
                line[i] <- board[k, i];
            Else
                line[i] <- board[i, k];
            EndIf
        EndFor
        If direction = "r" Or direction = "d" Then
            SlideRight(line, score);
        Else
            SlideLeft(line, score);
        EndIf
        // Copy line back and note any change
        For i <- 1 To 4 Step 1 Do
            If direction = "l" Or direction = "r" Then
                If board[k, i] <> line[i] Then
                    changed <- True;
                EndIf
                board[k, i] <- line[i];
            Else
                If board[i, k] <> line[i] Then
                    changed <- True;
                EndIf
                board[i, k] <- line[i];
            EndIf
        EndFor
    EndFor
    Return changed;
EndFunction

// Puts N (9 times in 10) or 2N in a random empty cell
Procedure AddTile(board As Integer[,], n As Integer)
    Define i, j, empty, pick As Integer;
    empty <- 0;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            If board[i, j] = 0 Then
                empty <- empty + 1;
            EndIf
        EndFor
    EndFor
    If empty > 0 Then
        pick <- RandomBetween(1, empty);
        For i <- 1 To 4 Step 1 Do
            For j <- 1 To 4 Step 1 Do
                If board[i, j] = 0 Then
                    pick <- pick - 1;
                    If pick = 0 Then
                        If Random() < 0.9 Then
                            board[i, j] <- n;
                        Else
                            board[i, j] <- 2 * n;
                        EndIf
                    EndIf
                EndIf
            EndFor
        EndFor
    EndIf
EndProcedure

// True when some tile reached the target
Function HasWon(board As Integer[,], target As Integer): Boolean
    Define i, j As Integer;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            If board[i, j] >= target Then
                Return True;
            EndIf
        EndFor
    EndFor
    Return False;
EndFunction

// True when there is an empty cell or two equal neighbors
Function CanMove(board As Integer[,]): Boolean
    Define i, j As Integer;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            If board[i, j] = 0 Then
                Return True;
            EndIf
            If j < 4 Then
                If board[i, j] = board[i, j + 1] Then
                    Return True;
                EndIf
            EndIf
            If i < 4 Then
                If board[i, j] = board[i + 1, j] Then
                    Return True;
                EndIf
            EndIf
        EndFor
    EndFor
    Return False;
EndFunction
```

Tiles appear at random, so every game is different. In one run where we typed `2`, `l`, `X`, `u`, `r` and `q`, the output was:

```text
Type N [1-10]: 
Welcome to 2048
Up [u], down [d], left [l], right [r], quit [q]
Score: 0
0 0 0 0 
2 0 2 0 
0 0 0 0 
0 0 0 0 
R: 
Score: 4
0 0 0 0 
4 0 0 0 
0 0 0 0 
0 2 0 0 
R: 
Unknown command: x
R: 
Score: 4
4 2 0 0 
0 0 0 0 
2 0 0 0 
0 0 0 0 
R: 
Score: 4
0 0 4 2 
0 0 0 0 
0 2 0 2 
0 0 0 0 
R: 
Final score: 4. Thanks for playing.
```

Your tiles will be in other places, but the shape is the same: a board after each move that changes something, `Unknown command: x` for the invalid command, and the final score at the end.

## 5. Save the game in Python

The project brief asks players to save a game at any turn and continue it later. StepCode has no files, so this part uses Python, as in the [files lesson](/blog/programming-fundamentals-files/).

Choose a format first. The first line holds N and the score. The next four lines hold the rows of the board, with one space between numbers. These are the same `JoinLine` and `SplitLine` ideas from the [files lesson](/blog/programming-fundamentals-files/#design-a-file-format).

Save this as `save_game.py`:

```python
def save_game(file_name: str, n: int, score: int, board: list[list[int]]) -> None:
    with open(file_name, "w") as file:
        file.write(str(n) + " " + str(score) + "\n")
        for row in board:
            line = ""
            for value in row:
                line = line + str(value) + " "
            file.write(line.strip() + "\n")

def load_game(file_name: str):
    with open(file_name, "r") as file:
        lines = file.readlines()
    first = lines[0].split(" ")
    n = int(first[0])
    score = int(first[1])
    board = []
    for line in lines[1:5]:
        row = []
        for value in line.split(" "):
            row.append(int(value))
        board.append(row)
    return n, score, board

board = [[0, 0, 2, 0], [4, 0, 0, 0], [4, 4, 0, 0], [0, 0, 0, 2]]
save_game("game.txt", 2, 12, board)
n, score, loaded = load_game("game.txt")
print("N:", n, "Score:", score)
for row in loaded:
    print(row)
```

Run it with `python3 save_game.py`. You should see:

```text
N: 2 Score: 12
[0, 0, 2, 0]
[4, 0, 0, 0]
[4, 4, 0, 0]
[0, 0, 0, 2]
```

And `game.txt` contains:

```text
2 12
0 0 2 0
4 0 0 0
4 4 0 0
0 0 0 2
```

The load function gives back three values at once. That is a Python feature called a **tuple**. In pseudocode, you would use three `ByRef` parameters instead.

## Common mistakes

If the row `2 2 2 2` slides to `2 4 4 4` instead of `0 0 4 4`, it means a tile joined twice. After a join, you must set the other tile to 0, so it cannot join again in the same move. That is the line `row[i - 1] <- 0;` in `SlideRight`. The real game joins each tile at most once per move.

If the program stops with `Index 5 is outside "board": its positions run from 1 to 4.`, a loop looked past the edge. This happens in `CanMove` when it compares `board[i, j]` with `board[i, j + 1]` on the last column. Check `j < 4` before you look to the right, and `i < 4` before you look down.

If a new tile appears after a move that changed nothing, the player can fill the board without doing anything. Add the tile only when `Move` returns `True`.

If `U` is reported as an unknown command, you compared the input before you converted it. Call `Lower` right after `Read`.

## Make it yours

The project brief asked for more than the game: a menu, saved games, and two lists in files. It also gave points for a new feature of your choice. These exercises take you there.

### Exercise 1: the biggest tile

Write a function `BiggestTile(board)` that returns the highest value on the board. Show it under the score.

<details>
<summary>Solution</summary>

**Solution: the biggest tile** (StepCode)

```stepcode
Program BiggestTileTest
    Define board As Integer;
    Dimension board[4, 4];
    Define i, j As Integer;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            board[i, j] <- 0;
        EndFor
    EndFor
    board[1, 2] <- 8;
    board[3, 4] <- 64;
    board[4, 1] <- 16;
    Write "Biggest tile: ", BiggestTile(board);
EndProgram

// Gives back the highest value on the board
Function BiggestTile(board As Integer[,]): Integer
    Define i, j, best As Integer;
    best <- 0;
    For i <- 1 To 4 Step 1 Do
        For j <- 1 To 4 Step 1 Do
            If board[i, j] > best Then
                best <- board[i, j];
            EndIf
        EndFor
    EndFor
    Return best;
EndFunction
```

You should see:

```text
Biggest tile: 64
```

</details>

### Exercise 2: the best scores list

When a game ends, the player types a name, and the program adds the name and score to `scores.txt`, the score board you built in [Files](/blog/programming-fundamentals-files/#save-and-load-scores). Then it shows every score from highest to lowest. Use the bubble sort from the [arrays lesson](/blog/programming-fundamentals-arrays/), in descending order.

<details>
<summary>Solution</summary>

```python
def read_scores(file_name: str, names: list[str], points: list[int]) -> None:
    with open(file_name, "r") as file:
        for line in file.readlines():
            name, value = line.strip().split(" ")
            names.append(name)
            points.append(int(value))

def sort_descending(names: list[str], points: list[int]) -> None:
    n = len(points)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            if points[j] < points[j + 1]:
                points[j], points[j + 1] = points[j + 1], points[j]
                names[j], names[j + 1] = names[j + 1], names[j]

name = input("Your name: ")
score = input("Your score: ")
with open("scores.txt", "a") as file:
    file.write(name + " " + score + "\n")

names = []
points = []
read_scores("scores.txt", names, points)
sort_descending(names, points)
print("Best scores:")
for i in range(len(names)):
    print(i + 1, names[i], points[i])
```

With `Ana 120` and `Luis 95` already in the file, run it and type `Mateo` and `130`. You should see:

```text
Your name: Mateo
Your score: 130
Best scores:
1 Mateo 130
2 Ana 120
3 Luis 95
```

</details>

### Exercise 3: the full brief

Build the complete N210 from the brief, in Python. It starts with a menu: play, continue a saved game, show winners, and show scores. Winners go in a file with how many times each one won, sorted from fewest to most wins. Scores go from highest to lowest. Use the StepCode game as your plan: each subprogram becomes a Python function with the same name and the same job. There is no solution here. This one is yours.

## Keep learning with AI agents

You finished the fundamentals. The next step is to build more, and today you will build with AI agents next to you. Use them in a way that makes you stronger, not weaker.

- **Ask for explanations.** Paste one function and ask the agent to explain it line by line. Then close the chat and explain it again in your own words.
- **Ask for test cases, then trace them by hand.** Ask for five inputs that could break `SlideRight`. Work out the answer on paper first, with a trace table like the one in [Input, process and output](/blog/programming-fundamentals-sequential-structures/#trace-a-program-by-hand), then run the code.
- **Ask for a review.** Give the agent your code and the Common mistakes section of a lesson. Ask it to find those mistakes in your code. You decide which findings are real.
- **Read every line it writes.** When an agent writes code for you, read all of it before you run it. If you cannot explain a line, ask about it or delete it.
- **Change something.** After the code works, change one rule, like the size of the board. If you can make the change, you understand the code.

The test is the same as the defense in my course. Could you show every feature working, explain every line, and add a new feature in front of another person? If yes, the code is yours, whoever typed it. I wrote more about this for teams in [How to review AI generated code](/blog/how-to-review-ai-generated-code/).

## What you learned

- How to plan a program as a tree of small subprograms before you write code.
- How the series fits together: variables, conditionals and loops inside functions, arrays and a matrix for data, `ByRef` for results, random numbers for the game, and a file to remember.
- How to reuse a solution, like flipping a row to turn a right slide into a left slide.
- How to test each piece alone with fixed data before you join them.
- How to learn with AI agents: let them explain and review, and read every line yourself.

## Next steps

This is the last lesson of the Programming Fundamentals series. Go back to the start, [Algorithms](/blog/programming-fundamentals-design-and-development-of-algorithms/), and you will read it with new eyes.

- Keep practicing in [StepCode](/projects/stepcode/), the editor I built for my students at UCAB. Every program in this series opens there.
- Review [Procedures and functions](/blog/programming-fundamentals-procedures-and-functions/) and [Files](/blog/programming-fundamentals-files/) as you build the full brief.
