🎮 Game dev with C++ · session 1 of 24 · 90 minutes · free

Hello, game world: your first C++ program

Every game you have played, from tiny phone games to Unreal Engine worlds, is a program that stores numbers, reads the player's input, makes decisions and moves things on a screen. Today you write your first C++ program and do all four.

🎯 Practice mode⚔️ Boss battle🖨 Print a worksheet
Illustration of a cute pastel robot dancing
Illustration: andremsdesign / Pixabay

A complete lesson · 90 minutes

Teach it, see it, practise it, all on this page.

Open this page with your learner and work down it, or press Teach this lesson to go through it one step at a time on a big screen. Every section has something to do.

See the teacher's plan
  1. Warm-up games6 min
  2. Warm-up4 min
  3. How a C++ program is built15 min
  4. Variables and types15 min
  5. Input and decisions14 min
  6. Positions and velocities14 min
  7. Activity 1: predict, then prove it7 min
  8. Activity 2: the treasure doors6 min
  9. Activity 3: vector race4 min
  10. Quiz4 min
  11. Set the project1 min

By the end you can

  • Build and run a C++ program: #include, main(), std::cout and return 0
  • Store game values in the right type: int, double, bool, char and std::string
  • Predict integer and decimal maths: 7 / 2, 7 % 2 and 7.0 / 2
  • Read the player's choice with std::cin and react with if, else if and else
  • Treat a position and a velocity as 2D vectors and move a sprite frame by frame

Before you start

  • Using a keyboard and a browser
  • Negative numbers and coordinates (x, y)

Have ready

  • A laptop or computer (a tablet works for reading, not for coding)
  • Compiler Explorer (godbolt.org) open in a tab: nothing to install today
  • A notebook for the code journal

Ages 13 to 16 · beginner to first portfolio · 90-minute lessons

Warm-up · think first

A game runs at 60 frames a second. How many frames does a 3-minute level last?

Show the answer

10 800 frames: 3 minutes × 60 seconds × 60 frames.

Teacher tip: Ask for a guess first. Then: if each frame takes the computer 16 milliseconds to draw, why does that matter? (That is the game loop, coming today.)

More warm-ups for every class →

🎮 Warm-up games · 5 quick games

Play with Bolt the robot

Five quick rounds in the game studio. Vote, say why, then show the answer.

  1. Which one doesn't belong: int, double, bool, cout? (int · double · bool · cout)
    Answer: cout is the odd one: it is a stream that prints. The other three are types of variables.
  2. Would you rather your game ran at 30 frames a second with amazing graphics, or 120 frames a second with simple graphics? (30 fps, amazing graphics · 120 fps, simple graphics)
    Answer: Both are real choices studios make: smooth action games aim high, cinematic games accept 30. There is no wrong answer if you can say why.
  3. In C++, 7 / 2 gives 3.5. (Always · Sometimes · Never)
    Answer: Sometimes — Sometimes: with two ints (7 / 2) the answer is 3, but with a decimal (7.0 / 2) it is 3.5. Today's big trap!
  4. Name three things a game must remember about the player.
    Answer: Health, score, position, lives, name, level, inventory… every one becomes a variable.
  5. A sprite starts at x = 10 and moves 4 pixels right every frame. Where is it after 5 frames?
    Answer: x = 30: 10 + 4 × 5. That is a velocity, and Part 4 turns it into vectors.

Three levels, like a real engineer

Use it. Tweak it. Build it.

First use what the lesson shows exactly as it is, then change one key thing and see what happens, then make your own.

  1. 🔒

    Level 1 · Use it

    Run HP Line

    Run this exact line in your C++ program: std::cout << "HP: " << 50 * 2 << "!"; Watch what appears on screen and point to each part that prints.

  2. 🔧

    Level 2 · Tweak it

    Change HP Numbers

    In that same HP line, change 50 to 25 and change * 2 to * 3. Predict the new HP number before you run it, then check your guess.

  3. 🛠️

    Level 3 · Build it

    Make Hero Card

    Write your own C++ program from scratch that prints a hero card: name, HP, and coins. Use std::cout and at least one maths expression, then run it and test.

🗺️ Play the Lesson QuestThree worlds, one for each level, with short stages that bring back what you miss.

Part 1 of 4 · learn, see, practise

How a C++ program is built

Welcome to the studio. I am Byte, the studio robot. Games are written as text called source code, then a compiler turns that text into a program the computer can run. Let's build one.

C++ is the language most big game engines are written in: Unreal Engine, Godot's core and most console games. It is fast because a compiler (g++, clang or Microsoft's MSVC) translates your source file (main.cpp) into machine code once, before the game runs.

Every C++ program starts running in a function called main. The lines between its curly braces { } run from top to bottom. return 0; at the end tells the operating system the program finished without errors.

#include <iostream> brings in the input/output library. std::cout ("see-out") is the console output, and << sends things into it: text in double quotes, numbers and sums. \n (or std::endl) starts a new line.

Almost every statement ends with a semicolon ;. C++ is case-sensitive: Main and main are different names, and the compiler stops at the first mistake with an error message. Reading those messages calmly is a real game-developer skill.

Remember!
  • Program = #include lines + int main() { … return 0; }
  • std::cout << sends text and numbers to the screen
  • End statements with ; and close every { with }
📝 Notes

std:: means "from the standard library". Many tutorials write using namespace std; so they can say cout instead of std::cout. Pros keep std:: to avoid name clashes, so we do too.

Game engines are libraries too: later you will write #include "raylib.h" in exactly the same way.

#include <iostream>

int main() {
    std::cout << "Hello, game world!\n";
    std::cout << "Level " << 1 << " loading...\n";
    std::cout << "Coins: " << 20 + 5 << "\n";
    return 0;
}

▶ Output

Hello, game world!
Level 1 loading...
Coins: 25

Example 1

What does std::cout << "HP: " << 50 * 2 << "!"; print?

  1. The text in quotes prints exactly as written: HP: (with a space).
  2. 50 * 2 is worked out first: 100.
  3. Then the ! follows straight after, with no space.

Answer: HP: 100!

Example 2

The compiler says: error: expected ';' before 'return'. What is wrong?

  1. The error points at the line BEFORE return.
  2. That line is missing its semicolon.
  3. Add ; to the end of it and build again.

Answer: A missing semicolon on the line above return

Practise it

Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.

Warm-up

Warm-up

Core

Core

Stretch 🔥

Stretch 🔥

Answers (for the teacher)
  1. main | main()
  2. 15 coins
  3. AB7
  4. <<
  5. 2
  6. 4:24

Part 2 of 4 · learn, see, practise

Variables and types: the game's memory

A game remembers everything in variables: your health, your speed, whether you are alive, your name. In C++ every variable has a type that says what kind of value it holds.

Declare a variable with its type, a name and a starting value: int health = 100; The main types are int (whole numbers: health, score, lives), double (decimals: speed 2.5, gravity 9.8), bool (true or false: isAlive), char (one letter in single quotes: 'A') and std::string (text in double quotes, from #include <string>).

Change a variable with =, which means "store", not "equals": health = health - 35; takes the old value, subtracts 35 and stores the result. Short forms: health -= 35; score += 10; and ++level; adds one.

The type changes the maths. With two ints, / throws the decimal part away: 7 / 2 is 3, and % gives the remainder: 7 % 2 is 1. If either side is a double, you get a decimal: 7.0 / 2 is 3.5. Games use / and % all the time: tiles across a map, frames per animation, minutes and seconds on a timer.

const marks a value that must never change, like const int MAX_HEALTH = 100; The compiler then refuses any line that tries to change it, which catches bugs early.

Remember!
  • int = whole, double = decimal, bool = true/false, std::string = text
  • int / int drops the decimal: 7 / 2 is 3; % is the remainder
  • = stores a value; == compares (Part 3)
📝 Notes

Printing a bool shows 1 for true and 0 for false.

The order matters: double avg = (3 + 4) / 2; stores 3, because (3 + 4) / 2 is worked out with ints first. Write (3 + 4) / 2.0 to get 3.5.

Name variables clearly: playerSpeed beats ps. Names cannot start with a digit or contain spaces.

#include <iostream>
#include <string>

int main() {
    std::string hero = "Byte";
    int health = 100;
    double speed = 2.5;
    bool alive = true;

    health = health - 35;
    std::cout << hero << " has " << health << " health\n";
    std::cout << "Speed x 2 = " << speed * 2 << "\n";
    std::cout << "7 / 2 = " << 7 / 2 << ", 7 % 2 = " << 7 % 2 << "\n";
    std::cout << "alive = " << alive << "\n";
    return 0;
}

▶ Output

Byte has 65 health
Speed x 2 = 5
7 / 2 = 3, 7 % 2 = 1
alive = 1

Example 1

A level lasts 250 seconds. Show it as minutes:seconds.

  1. int minutes = 250 / 60; gives 4 (ints drop the decimal).
  2. int seconds = 250 % 60; gives the remainder, 10.
  3. std::cout << minutes << ":" << seconds; prints 4:10.

Answer: 4:10

Example 2

int coins = 40; coins -= 15; coins += 3; What is coins now?

  1. Start at 40.
  2. coins -= 15 makes 25.
  3. coins += 3 makes 28.

Answer: 28

Practise it

Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.

Warm-up

Warm-up

Core

Core

Core

Stretch 🔥

Stretch 🔥

Answers (for the teacher)
  1. std::string | string
  2. 3
  3. 2
  4. 28
  5. 4.5
  6. 3
  7. 15

Part 3 of 4 · learn, see, practise

Input and decisions: the player chooses

A game is not a film: the player decides. std::cin reads what they type, and if, else if and else choose what happens next.

std::cin >> door; waits for the player to type a value and press Enter, then stores it in the variable door. The variable must exist first (int door;).

if (condition) { … } runs its block only when the condition is true. else if tries another condition, and else catches everything left. Only ONE block of an if / else if / else chain runs.

Conditions compare values: == equal, != not equal, <, >, <=, >=. Combine them with && (and: both must be true) and || (or: at least one). Example: if (health > 0 && hasKey) opens the door only for a living player with the key.

The most famous C++ bug: if (lives = 0) uses ONE equals sign, so it stores 0 in lives instead of comparing, and the condition is false. Always use == to compare. Good compilers warn you; read the warnings.

Remember!
  • std::cin >> variable; reads input
  • Only one branch of if / else if / else runs
  • == compares, = stores; && is and, || is or
📝 Notes

Every game loop is decisions on repeat: is a key pressed? did the player touch the enemy? is health 0? You will write all of these.

When you test a program with input, try every branch: a right answer, a wrong one and a silly one (like 99).

The treasure doors (try typing 2, then 1, then 7)▶ Run it in Compiler Explorer ↗
#include <iostream>

int main() {
    int door;
    std::cout << "Pick a door (1, 2 or 3): ";
    std::cin >> door;
    if (door == 2) {
        std::cout << "Treasure! +50 coins\n";
    } else if (door == 1 || door == 3) {
        std::cout << "A slime appears!\n";
    } else {
        std::cout << "That door does not exist.\n";
    }
    return 0;
}

▶ Output (when the player types 2)

Pick a door (1, 2 or 3): Treasure! +50 coins

Example 1

int score = 120; if (score >= 100) std::cout << "Gold"; else std::cout << "Silver"; What prints?

  1. Is 120 >= 100? Yes.
  2. So the first block runs and the else is skipped.

Answer: Gold

Example 2

int x = 4; Is (x > 2 && x < 4) true or false?

  1. x > 2 is true.
  2. x < 4 is false (4 is not less than 4).
  3. && needs both: false.

Answer: false

Practise it

Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.

Warm-up

Warm-up

Core

Core

Stretch 🔥

Stretch 🔥

Answers (for the teacher)
  1. ==
  2. true
  3. Gold
  4. out
  5. Keep going
  6. Teen

Part 4 of 4 · learn, see, practise

Game maths: positions and velocities are vectors

Here is the secret behind every moving thing in a game: two numbers. Where it is, (x, y), and how far it moves each frame, (vx, vy). Mathematicians call a pair like that a vector.

A 2D vector is an ordered pair of numbers. A sprite's position is a vector (x, y); its velocity (vx, vy) says how far it moves in one frame. In raylib, SDL2 and most 2D engines the screen's (0, 0) is the TOP-LEFT corner: x grows to the right and y grows DOWN, so a negative vy moves a sprite up.

Every frame the game adds the velocity to the position: x = x + vx; y = y + vy; Adding vectors means adding matching parts: (3, 2) + (1, −4) = (4, −2). After n frames the sprite has moved n × velocity.

Multiplying a vector by a number (scaling) multiplies both parts: 3 × (2, −1) = (6, −3). Double the velocity and the sprite goes twice as far each frame in the same direction.

Frames are not seconds. At 60 frames a second, 2 pixels a frame is 120 pixels a second. Real games multiply by the time each frame took (delta time), so the speed stays the same on fast and slow computers: coming in lesson 15.

Remember!
  • Position (x, y), velocity (vx, vy): each frame, position = position + velocity
  • Screen y grows downward: negative vy goes up
  • Add vectors part by part; scale both parts
📝 Notes

This is linear algebra, the maths of vectors and matrices. Unit 2 adds length (Pythagoras), direction, the dot product and matrices that rotate sprites.

The loop in the program below (for) is a preview: lesson 3 explains it fully.

#include <iostream>

int main() {
    int x = 2, y = 10;     // position
    int vx = 2, vy = -1;   // velocity per frame
    for (int frame = 1; frame <= 5; frame++) {
        x = x + vx;
        y = y + vy;
        std::cout << "frame " << frame << ": (" << x << ", " << y << ")\n";
    }
    return 0;
}

▶ Output

frame 1: (4, 9)
frame 2: (6, 8)
frame 3: (8, 7)
frame 4: (10, 6)
frame 5: (12, 5)

Example 1

A sprite at (0, 0) moves with velocity (4, −2). Where is it after 3 frames?

  1. 3 frames add the velocity 3 times: 3 × (4, −2) = (12, −6).
  2. Add that to the start: (0, 0) + (12, −6).

Answer: (12, −6)

Example 2

A sprite at (100, 300) must reach (160, 240) in 20 frames. What velocity does it need?

  1. The change is (160 − 100, 240 − 300) = (60, −60).
  2. Share it over 20 frames: (60 ÷ 20, −60 ÷ 20).

Answer: (3, −3)

The vector lab

The alien starts at (2, 10). Set its velocity with the arrows, then press Next frame: each frame adds the velocity to its position. Grab the coin!

  1. Set the velocity to (2, −1): two right, one up.
  2. Reach the coin at (12, 5) in exactly 5 frames.
  3. Press Reset, then fly to (2, 1): straight up the screen.

Practise it

Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.

Warm-up

Warm-up

Core

Core

Stretch 🔥

Stretch 🔥

Answers (for the teacher)
  1. (4, 6) | 4, 6
  2. 13
  3. (12, -6) | 12, -6
  4. (10, -6) | 10, -6
  5. 180
  6. (3, -3) | 3, -3

Watch out

Common mistakes

Using = instead of == in an if

if (lives = 0) stores 0 and is always false. Compare with ==.

Expecting decimals from int division

7 / 2 is 3 with ints. Make one side a double (7.0 / 2) or use / 2.0.

Forgetting that y grows downward on screen

On screen, up is negative y. Draw a quick axis before you set vy.

Panicking at compiler errors

Read the FIRST error only, look at the line it names and the line above, fix one thing, build again.

Class activity 1 of 3

Predict, then prove it

Predict each output on paper first. Then paste the line into the ▶ Compiler Explorer program from Part 1 (inside main) and run it. Every surprise is a lesson.

  1. Write your prediction.
  2. Run it in Compiler Explorer.
  3. If you were wrong, explain why in your code journal.

Answers (for the teacher)
  1. 3,2
  2. 11
  3. 1
  4. 2
  5. Byte4

Class activity 2 of 3

Build the treasure doors

Open the treasure-door program from Part 3 in Compiler Explorer and make it yours. Type the answers your finished program prints.

  1. Add a fourth door: door 4 gives "A shop! Spend coins?".
  2. Give the player 10 coins at the start and add 50 when they find the treasure; print the total.
  3. Test every door: 1, 2, 3, 4 and a silly number like 99.

Answers (for the teacher)
  1. 60
  2. That door does not exist.
  3. 4
  4. 1

Class activity 3 of 3

Vector race

Two racers start on the same line. Work out where each one is, then decide who reaches the finish first.

  1. Write each racer's position after each frame.
  2. Use position = position + velocity.
  3. Check one racer with the vector lab or a C++ loop.

Answers (for the teacher)
  1. (12, 5) | 12, 5
  2. (8, 9) | 8, 9
  3. 10
  4. 15
  5. (5, 0) | 5, 0

After class · project

Your first text game: the stat card

Write a C++ program that asks the player for their hero's name and a class (1 = knight, 2 = wizard), sets health, speed and coins to suit the class, prints a neat stat card, then offers three doors with a different result for each.

What to make: a console program that asks for the hero's name and class, prints a stat card and lets the player pick a door

Stretch: Add a third class, and a fourth door that only opens if coins >= 20 (use &&).

How it is marked

Look forDone well when
It
Us
if
Th
Ev

Starter code to take home

Press Copy and paste it into the editor at home, or work on it right here.

Project starter

▶ Output

Line 4: SyntaxError: invalid syntax

📦 Memory boxes

No variables yet

Homework

Practise at home

Try each on paper, then tap to see the answer and working. Or print the practice sheet.

  1. What does std::cout << 100 / 7 << " r " << 100 % 7; print?

    14 r 2

  2. A sprite at (20, 40) moves with velocity (−3, 5). Where is it after 4 frames?

    (8, 60) | 8, 60

  3. int lives = 3; lives -= 1; lives *= 2; What is lives?

    4

  4. A countdown starts at 125 seconds. What does std::cout << 125 / 60 << ":" << 125 % 60; print?

    2:5

🔥 Challenge round · finished early?

The hardest questions of the lesson, no notes

Cover the notes and try these from memory. They are meant to make you think hard: draw, try small cases, and check your answer.

Stretch 🔥

Stretch 🔥

Stretch 🔥

Stretch 🔥

Stretch 🔥

Stretch 🔥

Stretch 🔥

Stretch 🔥

Answers (for the teacher)
  1. 2
  2. 4:24
  3. 3
  4. 15
  5. Keep going
  6. Teen
  7. 180
  8. (3, -3) | 3, -3

🧠 Think-hard question

A sprite starts at (0, 0) and its velocity INCREASES by (0, 1) every frame (gravity), starting at (3, −6). Write its position for the first 6 frames. When does it come back to y = 0?

Talk it through or use the drawing board. There is more than one way to get there.

Quiz · 8 questions

Final quiz: check what you learned

Pick an answer to see if it is right and why. Your best score is saved on this device.

1What does std::cout << 9 / 4; print?
Show the answer

2. Both are ints, so / drops the decimal part: 9 / 4 is 2.

2What does std::cout << 9 % 4; print?
Show the answer

1. 4 goes into 9 twice (8) with 1 left over.

3Which line stores a player's speed of 2.5 correctly?
Show the answer

double speed = 2.5;. Decimals need double. int would chop it to 2.

4int hp = 30; if (hp > 50) std::cout << "A"; else if (hp > 20) std::cout << "B"; else std::cout << "C"; What prints?
Show the answer

B. 30 > 50 is false, 30 > 20 is true, so only the B block runs.

5Where does every C++ program start running?
Show the answer

In main(). main is the entry point; #include only brings in libraries.

6A sprite at (5, 5) has velocity (2, −1). Where is it after 2 frames?
Show the answer

(9, 3). 2 × (2, −1) = (4, −2), and (5, 5) + (4, −2) = (9, 3).

7On a raylib or SDL2 screen, which velocity moves a sprite straight UP?
Show the answer

(0, −3). Screen y grows downward, so up means negative y.

8double avg = (3 + 4) / 2; What is avg?
Show the answer

3. (3 + 4) / 2 is worked out with ints first (3), then stored as a double.

🖨 Print what we learned

Make a worksheet from this lesson

Pick what to practise, then print it or choose Save as PDF in the print window to download it.

Include
Options

For parents and teachers

The 90-minute lesson plan

Use it as it is, or stretch any part over two sessions. Each row links to the part of the page you need.

TimePartThe teacherThe learner
0–6 minWarm-up gamesFive fast rounds; take votes and reasons, not just answers.Vote and say why.
6–10 minWarm-up60 × 60 × 3 on the board, then ask why speed per frame matters.Guess, then explain.
10–25 minHow a C++ program is builtOpen Compiler Explorer with ▶; change the text, break a semicolon on purpose and read the error together.Run it, change it, read one error.
25–40 minVariables and typesRun the stats program, then predict 7 / 2 before revealing. Spend time on the int-division trap.Practise up to the stretch.
40–54 minInput and decisionsRun the doors program three times with different input (the stdin box in Compiler Explorer).Test every branch.
54–68 minPositions and velocitiesDo the vector lab tasks first, then run the five-frames program and match it to the lab.Lab tasks, then practice.
68–75 minActivity 1: predict, then prove itPredictions on paper first; then run.Predict and check.
75–81 minActivity 2: the treasure doorsLearner drives the keyboard; the teacher only asks questions.Extend the program.
81–85 minActivity 3: vector raceQuick mental maths; the lab checks one racer.Race maths.
85–89 minQuizEight questions, no running the code.Answer and read why.
89–90 minSet the projectShow the stat-card starter and agree a due date.Start the project.

Questions to ask

  • Why does 7 / 2 give 3 in C++?
  • What is the difference between = and ==?
  • Which way does a sprite with velocity (0, −5) move, and why?
  • What does the compiler do?

If it feels hard

Pair-program: the learner types, the teacher reads the error messages aloud with them. Keep a code journal of every error and its fix.

If it feels easy

A sprite starts at (0, 0) and its velocity INCREASES by (0, 1) every frame (gravity), starting at (3, −6). Write its position for the first 6 frames. When does it come back to y = 0?

FAQ

Hello, game world: your first C++ program: questions

Does my child need to install anything?

Not for the first lessons: Compiler Explorer runs C++ in the browser. From the raylib unit we help set up a free compiler and raylib on Windows, Mac or Linux, step by step.

Why C++ and not a game engine straight away?

Unreal Engine is written in C++, and engines make far more sense once you know the language and the vector maths underneath. The course gets to raylib prototypes and UE5, but on solid ground.

Is the maths hard?

It starts with coordinates and grows slowly: vectors, distance, angles and matrices, always shown moving on screen first.

Start a conversation

Want a teacher to take this class?

Tell us the learner's age and level. A teacher from our network teaches with these lessons; we confirm timing and price first.

  • Tell us the learner’s age or grade and goals
  • We’ll suggest a suitable class or learning path
  • We’ll confirm format, timing and fees with a parent or guardian

For a child’s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

We’ll use your details only to respond to this request.

Chat on WhatsApp
Esc

Try