Chapter 4: The Brains of the Operation
The Brains of the Operation 🧠
Section titled “The Brains of the Operation 🧠”Turn statues into characters
When the creator of Space Invaders first built his game in 1978, he accidentally made the alien ships speed up as the player destroyed them. It wasn’t planned. The computer simply had fewer graphics to draw, so it processed everything faster. Players loved the challenge, so the “bug” became an official feature, and one of the most famous difficulty curves in history.
You’ve designed a blueprint, created characters, and built levels. But without programming, those characters are statues. This chapter is about the logic that makes them move, react, remember, and fight back, and about what to do when, not if, it goes wrong.
4.1 — Thinking Like a Computer 💭
Section titled “4.1 — Thinking Like a Computer 💭”Computers aren’t smart. They’re fast and obedient. A computer does exactly what you tell it, nothing more, at millions of instructions a second. To make a game, you break big actions into tiny, logical steps it can follow.
Sequence
Section titled “Sequence”The simplest program is a list of steps in order: move the player, then check for a coin, then update the score. Order matters. Check for the coin before moving, and the player collects coins they haven’t reached yet.
If / Then / Else
Section titled “If / Then / Else”The foundation of all game logic is the if/then statementif/then statement: A logic rule that tells the computer: IF a condition is true, THEN do something. It's how programs make decisions.. It tells the computer what to do when something happens:
IF the player presses Jump → THEN move the character upGames are usually more complex, so we add an Else branch. Think of Super Mario:
IF Mario gets hit AND he has a Super Mushroom → THEN he shrinksELSE → he loses a lifeBooleans
Section titled “Booleans”A BooleanBoolean: A data type that can only be True or False. Named after mathematician George Boole. is a simple True or False value. Think of a zombie in Minecraft:
| Condition | Result |
|---|---|
isDaytime = True |
Zombie catches fire |
isDaytime = False |
Zombie keeps chasing you |
You combine Booleans with AND, OR, and NOT to make more complex decisions. isDaytime AND NOT isRaining AND NOT underRoof is the actual rule. Every one of those words is a Boolean, and getting them exactly right is most of what programming a game is.
When you need an action to repeat, you use a looploop: A programming structure that repeats a block of code either a set number of times or while a condition is true.:
| Loop Type | What It Does | Example |
|---|---|---|
| While loop | Runs while a condition is true | While health > 0, keep playing battle music |
| For loop | Runs a specific number of times | Run this code 5 times to spawn 5 enemies |
| For each | Runs once for every object in a group | For each enemy, move it toward the player |
The game loop from Chapter 1 is just a while loop: while the game is running, do the three steps.
Functions
Section titled “Functions”A functionfunction: A reusable block of code that performs a specific task. You write it once, then call it whenever you need it. is a mini-program you write once and reuse whenever you want. Instead of typing the same damage math 100 times, you write a CalculateDamage function once and call it. Functions can take inputs (which weapon, which enemy) and hand back an answer (how much damage). When a game has a bug in its damage math, a programmer fixes one function instead of a hundred copies.
Flowcharts
Section titled “Flowcharts”Before writing code, developers often draw a flowchartflowchart: A diagram that maps out a program's decisions and actions step-by-step using shapes and arrows. to plan their logic visually: rectangles for actions, diamonds for decisions, arrows for “then what.” If you can’t draw the flowchart, you don’t understand the logic yet, and the code won’t work either.
4.2 — Keeping Track of the Game 🗃️
Section titled “4.2 — Keeping Track of the Game 🗃️”While your game runs, the computer needs to remember a ton of information. That’s the game state from Chapter 1, and this is how it’s stored.
Variables and Constants
Section titled “Variables and Constants”| Concept | What It Is | Example |
|---|---|---|
| variablevariable: A named storage location in a program whose value can change during execution. | A labeled box that stores information that can change | playerHealth = 100 |
| constantconstant: A named storage location whose value is set once and never changes during execution. | A locked box that never changes | MAX_LEVEL = 100 |
Good names matter more than beginners expect. h means nothing next week. playerHealth still will.
Data Types
Section titled “Data Types”When you create a storage box, you choose a data typedata type: The category of data a variable can hold, such as whole numbers, decimals, text, or true/false.:
- Integers: whole numbers. Perfect for counting:
5coins,3lives,1sword. - Floats: numbers with decimals. Great for precision: a speed of
4.5, a position of120.25. - Strings: words and text. When an NPC says
"Welcome to my shop!", that’s a string. - Booleans:
TrueorFalse.hasKey,isJumping,isPaused.
Mixing types causes bugs. Add the string "5" to the number 5 and some languages give you "55".
Scope: Who Can See a Variable?
Section titled “Scope: Who Can See a Variable?”A variable’s scopescope: Where in a program a variable can be seen and used: inside one object, one scene, or the whole game (global). is where it can be used. A global variable (the score) is visible everywhere. An object variable (this enemy’s health) belongs to one enemy, so ten enemies have ten separate health values. Choosing the wrong scope is a classic bug: put health in global scope and every enemy shares one health bar, so killing one kills them all.
Arrays
Section titled “Arrays”An arrayarray: An ordered, numbered list that stores multiple values of the same type in a single variable. stores many similar items in a numbered list instead of hundreds of separate variables: inventory = ["sword", "potion", "key"]. Computers start counting at zero, so the first item is inventory[0], not inventory[1]. Forgetting this is possibly the most common bug in all of programming.
Object-Oriented Programming (OOP)
Section titled “Object-Oriented Programming (OOP)”Professionals use Object-Oriented ProgrammingObject-Oriented Programming: A programming approach where you create reusable templates (classes) and stamp out individual copies (objects) from them. to stay organized. Think of it like a cookie cutter:
- Design one
Goombaclass (the cookie cutter) with variables for health and speed, and functions likewalk()andgetStomped(). - Stamp out 50 Goomba objects into your game, each one independent, with its own health.
Change the cutter, and every future cookie changes. That’s why engines like GDevelop are built around objects: a sprite object is a class, and every copy in a scene is an object with its own variables.
Saving and Loading
Section titled “Saving and Loading”Saving a game means writing the important state (level, score, inventory, position) to a file or the cloud. Loading means reading it back into variables. Deciding what to save is a design decision: save too little and progress is lost; save everything and the file is huge and slow. Most games save at checkpoints, when the state is simple.
4.3 — Making Things Move and React 🏃
Section titled “4.3 — Making Things Move and React 🏃”The Game Loop, Up Close
Section titled “The Game Loop, Up Close”Behind the scenes, the game loop runs over and over, usually 60 times per second (60 FPS). Every cycle, it checks: did the player press a button? Where is everything now? Did anything collide? Should we play a sound? What should be drawn?
Because the loop runs so often, “move the player 5 pixels” happens 60 times a second, which is 300 pixels a second. Movement in games is almost always tiny changes applied every frame.
You write code that responds to two kinds of input:
- Hardware input: keyboard, mouse, touch, controller.
- GUI input: clicking an on-screen button like “Inventory” or “Pause.”
Good input code separates what the player pressed from what the game does. A “jump” action can be triggered by the space bar, a controller button, or a screen tap, and the rest of the code doesn’t care which.
Physics: Velocity and Gravity
Section titled “Physics: Velocity and Gravity”Most 2D games fake physics with two numbers per object: horizontal speed and vertical speed, together called velocityvelocity: How fast and in which direction an object is moving, usually stored as a horizontal and a vertical speed.. Every frame, position moves by velocity. Gravity is just “add a little downward speed every frame.” A jump is “set upward speed once.” The rest happens automatically:
every frame: velocityY = velocityY + gravity y = y + velocityY IF touching the ground → velocityY = 0That tiny loop produces the arc of every jump you’ve ever made in a platformer. Tune gravity and the jump feels floaty or heavy. Game feel is mostly numbers.
Collision Detection
Section titled “Collision Detection”The game needs to know when objects bump into each other. Every object has a hitboxhitbox: An invisible shape (usually a rectangle) drawn around a game object that the engine uses to detect collisions., an invisible shape around it. When two hitboxes overlap, a collision happens, and your code decides what to do next: bounce, take damage, collect, open.
Hitboxes are usually smaller than the picture. In Touhou and other bullet-hell games, the player’s hitbox is a few pixels wide even though the character is large. That is a design choice: it makes near-misses possible, and near-misses are fun.
Point Systems and Feedback
Section titled “Point Systems and Feedback”To make gameplay rewarding, implement a feedback loopfeedback loop: A cycle where the game responds to player actions with visible or audible rewards (like score updates and sound effects), encouraging continued play.. Display the score on the GUI and trigger a satisfying sound effect every time it increases. Remember juice from Chapter 3: a score that ticks up with a chime feels better than a number that silently changes.
4.4 — Events in GDevelop ⚙️
Section titled “4.4 — Events in GDevelop ⚙️”GDevelop doesn’t make you type code. Instead, you build logic with eventsevents: GDevelop's way of writing logic: each event is a list of conditions and, when they are all true, a list of actions to perform.: when these conditions are true, do these actions. Every event is really an if/then statement.
| Conditions (IF) | Actions (THEN) |
|---|---|
| Space key is pressed AND Player is on the floor | Set Player vertical speed to -600 |
| Player is in collision with Coin | Delete Coin; add 1 to variable Score; play sound “coin.wav” |
| Variable Lives = 0 | Change to scene “GameOver” |
| Enemy is in collision with Player | Subtract 1 from Lives; play “hurt.wav”; flash Player |
Behaviors
Section titled “Behaviors”GDevelop adds behaviorsbehaviors: Ready-made bundles of logic in GDevelop, such as Platformer Character or Physics, that you attach to an object instead of writing the events yourself.: pre-built logic you attach to an object. Attach Platformer Character to your hero and you get running, jumping, gravity, and ladders without writing the physics yourself. Attach Platform to the ground. The engine handles the loop; you handle the rules.
The Events Are Still Programming
Section titled “The Events Are Still Programming”Even though you’re clicking instead of typing, everything in 4.1 applies. Events run top to bottom every frame (sequence). Conditions are Booleans combined with AND (and OR, with a special event). “For each object” events are loops. External events and functions let you reuse logic. Learn GDevelop’s events well and Python or C# will feel familiar later, because the ideas are identical.
Scenes and Objects
Section titled “Scenes and Objects”A GDevelop game is made of scenes (menu, level 1, game over) filled with objects (sprites, text, tiled backgrounds). Global variables live across scenes; scene variables reset when the scene restarts; object variables belong to each instance. That is scope, from 4.2, exactly.
4.5 — Code Types and Catching Mistakes 🐛
Section titled “4.5 — Code Types and Catching Mistakes 🐛”Visual vs. Scripting
Section titled “Visual vs. Scripting”Modern game engines offer two approaches:
| Approach | How It Works | Examples |
|---|---|---|
| Visual programming | Drag-and-drop blocks or events | Scratch, GDevelop, Unreal Blueprints |
| Scripting | Typing code line by line | GDScript in Godot, C# in Unity, Lua in Roblox |
Visual tools are faster to learn and great for prototypes. Typed code is faster to write once you know it and scales better to big games. Most professionals use both.
Syntax vs. Semantics
Section titled “Syntax vs. Semantics”| Term | Meaning | Analogy |
|---|---|---|
| syntaxsyntax: The rules for how code must be written — spelling, punctuation, and structure that the computer requires. | The spelling and grammar of your code | Following English grammar rules |
| semanticssemantics: The actual meaning or logic behind your code instructions — what you intend the code to do. | The actual meaning of your instructions | Whether the sentence makes sense |
“Player the jump make” is a syntax error. “Make the player jump when they die” is perfect syntax and terrible semantics.
Types of Errors
Section titled “Types of Errors”Mistakes will happen. There are three main kinds:
- Syntax (compile) error: the code can’t even run. A missing bracket, a misspelled command. The engine usually tells you the line.
- Runtime error: the game runs, then crashes. Dividing by zero, using an object that was deleted, reading
inventory[3]when there are only three items. - Logic error: the game runs fine and does the wrong thing. The score goes up when you lose a coin. These are the hardest, because nothing tells you.
Debugging
Section titled “Debugging”To fix bugs, you debugdebug: The process of finding and fixing errors (bugs) in your code.. Professionals follow a routine:
- Reproduce it. Find the exact steps that cause the bug every time.
- Isolate it. Turn off half the events. Still broken? The bug is in the half that’s on.
- Look at the state. Print variables to the screen or use the debugger to watch them change.
- Change one thing. Test. Change one more thing. Never five at once.
- Write down what fixed it. Future you will hit it again.
Rubber duck debugging is real: explain your logic out loud, line by line, to a rubber duck or any object. By the time you finish, you’ll usually hear your own mistake.
Chapter 4 Activity: Program a Player 🎮
Section titled “Chapter 4 Activity: Program a Player 🎮”Your Mission: Build the logic of your Chapter 2 game on paper and then in GDevelop.
Part 1: The Variables
Section titled “Part 1: The Variables”List every variable your game needs. For each, write its type (integer, float, string, Boolean) and its scope (global, scene, or object). Circle the two most likely to cause bugs if the scope is wrong.
Part 2: Flowchart the Core Loop
Section titled “Part 2: Flowchart the Core Loop”Draw a flowchart for one full frame of your core loop: input, decisions, movement, collisions, score. Use diamonds for every Boolean decision.
Part 3: Write the Events
Section titled “Part 3: Write the Events”Write at least six GDevelop events as condition → action tables: jump, collect, take damage, win, lose, and one of your own. Then build them in GDevelop with the Platformer Character behavior and test.
Part 4: Break It on Purpose
Section titled “Part 4: Break It on Purpose”Introduce one bug of each type into your project (a wrong condition, a deleted object still referenced, a score that counts the wrong way). Swap projects with a partner and use the five-step debugging routine to find all three. Write down how you found each one.
Key Concepts Checklist
Section titled “Key Concepts Checklist”- I understand sequence, if/then/else, Booleans, loops, and functions
- I can draw a flowchart for a game decision
- I know the difference between variables and constants and the four data types
- I can explain scope and why it causes bugs
- I understand arrays (starting at zero) and OOP with the cookie-cutter analogy
- I can explain velocity, gravity, hitboxes, and feedback loops
- I can write a GDevelop event as conditions and actions and know what a behavior is
- I can name three types of errors and the five-step debugging routine
