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:
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.
Score: 0Goal: 2048
Row 1: empty. Row 2: empty, empty, 2, 2. Row 3: empty. Row 4: empty.
Slide the tiles. Two equal tiles that touch join into one.
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 of integers, where 0 means an empty cell.score, an integer.n, the starting number, andtarget, which isn * 1024.
The jobs fall into four groups:
- Board.
ShowBoardwrites the score and the grid.AddTileputs a new tile in a random empty cell. - Moves.
Moveslides the whole board. It copies each row or column into a small array and callsSlideRightorSlideLeft. Those use two helpers,PushRightandFlip. - Rules.
HasWonchecks for the target tile.CanMovechecks if any move is left. - Saving.
save_gameandload_gamewrite 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:
- Push every non zero number to the right, keeping their order.
- Join equal neighbors, starting from the right. Each join doubles one tile and empties the other.
- Push to the right again, to close the gaps the joins left.
Sliding a row of 4 numbers. To slide right: push the numbers right, join equal neighbors starting from the right, and push right again. For example 2 2 2 0 becomes 0 2 2 2, then 0 2 0 4, then 0 0 2 4, for 4 points. To slide left, flip the row first, slide it right, and flip it back. You can pick one of the workshop rows and a direction and step through it.
Result: 0 0 2 4. Points: 4.
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), because SlideRight must add points to the caller’s variable.
When you type 2, 2, 2 and 0, you should see:
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, turns the command into lowercase, so R and r both work.
When you type u, R, r and q, you should see:
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:
AddTilecounts the empty cells, picks one withRandomBetween, and walks the board again until it reaches that cell.RandomBetween(a, b)gives back a random whole number fromatob, and both ends can come out, soRandomBetween(1, empty)picks any one of the empty cells. It writes N there, or 2N one time in ten, usingRandom, one of the built in functions.HasWonreturnsTruewhen any tile reaches the target. A function can stop at the firstReturn True.CanMovereturnsTruewhen 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.
You should see:
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.
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:
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.
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.
Save this as save_game.py:
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:
N: 2 Score: 12
[0, 0, 2, 0]
[4, 0, 0, 0]
[4, 4, 0, 0]
[0, 0, 0, 2]
And game.txt contains:
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.
Solution
You should see:
Biggest tile: 64Exercise 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. Then it shows every score from highest to lowest. Use the bubble sort from the arrays lesson, in descending order.
Solution
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:
Your name: Mateo
Your score: 130
Best scores:
1 Mateo 130
2 Ana 120
3 Luis 95Exercise 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, 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.
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,
ByReffor 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, and you will read it with new eyes.
- Keep practicing in StepCode, the editor I built for my students at UCAB. Every program in this series opens there.
- Review Procedures and functions and Files as you build the full brief.