
turn a written rule set into GDScript using variables, a conditional, a timer event, a signal and random placement, and explain what each line does.
Instruction
A paper game’s rules live in a rulebook and in players’ heads. A video game’s rules live in code. Today you will write a tiny game with three rules and see exactly where each rule lives. (The structure is adapted from the Godot documentation’s “Your first 2D game” and “Using signals” pages, CC BY 3.0.)
The rules. (1) The player moves in eight directions. (2) Touching the coin scores one point and moves the coin somewhere random. (3) The round ends after 30 seconds and shows the final score.
Rule 1: the player. Last time you moved a Sprite2D directly. For anything that collides, Godot uses a physics body. A CharacterBody2D is a body you control with code. It needs a CollisionShape2D child to give it a shape, and a Sprite2D child to be seen.
extends CharacterBody2D
@export var speed: float = 250.0
func _physics_process(_delta: float) -> void:
velocity = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down") * speed
move_and_slide()velocity is a built-in property of the body. move_and_slide() moves the body by its velocity, stops it at walls and handles the frame time for you, which is why the parameter is named _delta: the underscore tells Godot we do not use it.
Rule 2: the coin. An Area2D is a region that detects bodies entering it but does not block them. When the player enters, the area emits a signal, body_entered. A signal is Godot’s word for an event: something happens, and any function connected to it runs.
extends Area2D
class_name Coin
signal collected
func _ready() -> void:
body_entered.connect(_on_body_entered)
func _on_body_entered(body: Node2D) -> void:
if body.is_in_group("player"):
collected.emit()
position = Vector2(randf_range(40.0, 1100.0), randf_range(40.0, 600.0))The if line is a conditional: only bodies in the group “player” count, so a future enemy could not steal points. class_name Coin registers the script as a new type, so other scripts can declare a variable of type Coin and use its custom signal. The coin declares its own signal, collected, and emits it, so the coin does not need to know anything about the score. randf_range(a, b) returns a random decimal between a and b; the numbers keep the coin inside the default 1152 × 648 window with a margin.
Rule 3: the clock and the score. The main scene holds the score in a variable and listens to both the coin and a Timer node.
extends Node2D
var score: int = 0
@onready var coin: Coin = $Coin
@onready var score_label: Label = $ScoreLabel
@onready var round_timer: Timer = $RoundTimer
func _ready() -> void:
coin.collected.connect(_on_coin_collected)
round_timer.timeout.connect(_on_round_timer_timeout)
round_timer.start(30.0)
func _process(_delta: float) -> void:
score_label.text = "Score: %d Time: %d" % [score, ceili(round_timer.time_left)]
func _on_coin_collected() -> void:
score += 1
func _on_round_timer_timeout() -> void:
set_process(false)
score_label.text = "Time! Final score: %d" % score
coin.queue_free()@onready fetches the child nodes when the scene starts; $Coin is shorthand for “my child named Coin”. %d inserts a whole number into text. When the timer runs out, set_process(false) stops the label updating and queue_free() removes the coin, so no more points can be scored.
Scenes as reusable symbols. Animation and multimedia programs let you build an object once as a symbol and place copies, called instances, wherever you need them; edit the symbol and every instance updates. A Godot scene works the same way. Coin.tscn is built once; dragging it into Main.tscn creates an instance, and you could drag in ten. Change the coin’s sprite or collision shape in Coin.tscn and every instance changes the next time you run. Change a property on one instance in Main.tscn (its position, or its scale) and only that copy differs. Build anything you will use more than once, such as a coin, an enemy or a button, as its own scene.
Why this matters for design. Each rule is now a line you can change. Want more tension? Shorten the timer. Want a comeback mechanic? Give a bonus in the last five seconds. The design question and the code change are the same size, which is why designers who can read code prototype faster.
📖 Read for this lesson
The reading opens over the lesson; close it to come back to exactly where you were. The checks below draw on it.
Build: Timed coin grab
Question. Can you implement three written rules (movement, scoring, a time limit) so that each rule maps to specific lines of code, and then change the game’s feel by changing one number?
Materials
- A computer with the Godot 4 desktop editor (4.3 or later)
- Your first-scene project from Lesson 1.2, or a new project
- Kenney sprites (CC0) for a character and a coin from the pack you downloaded in Lesson 1.2, or icon.svg for both
- The rule sheet from this lesson and your build log
- Keep the ergonomic set-up and 20-20-20 breaks from Lesson 1.2.
- Save after every step and zip a dated backup of the project folder at the end of the session and copy it to your USB drive.
Procedure
- Create a scene Player.tscn: root CharacterBody2D named Player, with children Sprite2D (character texture) and CollisionShape2D (set Shape to a new CircleShape2D or RectangleShape2D sized to the sprite). In the Node dock, open Groups and add the group player. Attach and type the player script.
- Create a scene Coin.tscn: root Area2D named Coin, with Sprite2D and CollisionShape2D children. Attach and type the coin script.
- Create Main.tscn with a Node2D root named Main. Instance Player and Coin into it (drag the .tscn files into the scene), add a Label named ScoreLabel near the top-left and a Timer named RoundTimer. Attach and type the main script, then set Main.tscn as the main scene (Project Settings > Application > Run).
- Run the game (F5). Play three rounds and record each final score.
- Test the coin as a reusable scene: open Coin.tscn, change its Sprite2D’s Modulate color, save and run Main. Then, in Main.tscn, select the Coin instance and change only its Scale. Record which change affected the scene file (every instance) and which affected only that one copy, then restore both.
- In your build log, copy each of the three written rules and, beside each, write the exact line or lines of code that enforce it.
- Make one design change by changing one number (timer length, player speed or the coin’s random range), predict its effect on the score and on how the game feels, then play three more rounds and record the result.
Data
| Version | Change made | Round 1 | Round 2 | Round 3 | Mean score | How it felt |
|---|---|---|---|---|---|---|
| Original (30 s, speed 250) | none | |||||
| Version 2 |
Analysis
- Did your one-number change affect the mean score as you predicted? Use your data.
- Which rule was hardest to find in the code, and why? What would make it easier for someone else reading your code, or for you a month from now, to find?
- Write one new rule (for example, a coin that shrinks over time) and describe which node and which lines you would change to add it.
If you cannot do this build in person: If you cannot use Godot, write the three scripts by hand on paper from the lesson, then play the game as a paper simulation by yourself: move a token on a grid, roll two dice to place the coin at a random grid square, and run a 30-second kitchen or phone timer while you keep the score (a family member may run the timer if one is free). Record three rounds and map each rule to the script line that would enforce it.
Formative check
Work through these before moving on. They are not graded — they tell you whether the standard below has landed yet.
Why does the coin script check body.is_in_group(“player”) before scoring?
randf_range(40.0, 1100.0) returns a random between 40 and 1100. To place the coin only in the right half of a 1152-pixel-wide window, a good x range would be randf_range(, 1100.0).
You change round_timer.start(30.0) to round_timer.start(10.0) and leave everything else the same. What do you predict?
Missouri standard: MM.ANI.2
Main.tscn holds three instances of Coin.tscn. You open Coin.tscn and swap its sprite for a gem image. What happens when you run Main?
How confident are you that you can map written rules to GDScript using variables, conditionals, signals and random numbers?
Practice
Work these on paper or in your notebook, then open Check your answer. Aim for all of Fluency and Application; try at least one Challenge.
Printable version: this unit’s practice workbook (PDF)
Fluency
Build speed and accuracy with the core skill.
- CharacterBody2D or Area2D? (a) the player you move with code; (b) a coin that notices when the player touches it; (c) a zone that detects when the player reaches the exit.
Check your answer
Answer: (a) CharacterBody2D; (b) Area2D; (c) Area2D.An Area2D detects bodies entering it but does not block them; a CharacterBody2D is a physics body moved by code. - What is a signal in Godot? Name the two signals the coin-grab game uses from built-in nodes.
Check your answer
Answer: A signal is an event a node emits that runs any function connected to it. The game uses body_entered (from the Area2D coin) and timeout (from the Timer).The coin also declares and emits its own custom signal, collected. - In the main script, what do @onready and $Coin mean?
Check your answer
Answer: @onready fetches the value when the scene starts (once child nodes exist); $Coin is shorthand for “my child node named Coin.”So @onready var coin: Coin = $Coin stores a reference to the child named Coin as soon as the scene is ready.
Application
Use the skill in context. Show your reasoning.
- The label line is score_label.text = “Score: %d Time: %d” % [score, ceili(round_timer.time_left)]. If score is 7 and time_left is 12.3, what text appears?
Check your answer
Answer: Score: 7 Time: 13%d inserts a whole number. ceili rounds up, so 12.3 becomes 13. - Find the bug. In a later version an enemy that wanders into the coin scores points for the player:
func _on_body_entered(body: Node2D) -> void:
collected.emit()
position = Vector2(randf_range(40.0, 1100.0), randf_range(40.0, 600.0))Check your answer
Answer: The conditional is missing. Wrap both lines in if body.is_in_group(“player”): so only the player scores.Without the check, any body entering the Area2D, including an enemy, triggers the point. - Code reading: in the timeout function, a student deletes coin.queue_free() but keeps set_process(false). What can still happen after time runs out, and what will the player see?
Check your answer
Answer: The coin is still there, so the player can keep touching it and the score variable keeps rising. But the label stopped updating and still shows “Time! Final score” with the old number.set_process(false) only stops _process from updating the label; queue_free() is what removes the coin so no more points can be scored. - The window is 1152 × 648. Write the randf_range calls that would keep the coin in the top half of the window with the same 40-pixel margins used in the lesson.
Check your answer
Answer: x: randf_range(40.0, 1100.0); y: randf_range(40.0, 324.0).Half of 648 is 324, so the y range runs from 40 to 324. x keeps the full-width range. - Three rounds at 30 seconds score 12, 15 and 9. Find the mean. If you shorten the timer to 15 seconds, what mean would you roughly predict, and what might make the real result a little higher?
Check your answer
Answer: Mean 12. Predict about 6. Players may hurry under pressure, so the drop may be a little less.(12 + 15 + 9) ÷ 3 = 36 ÷ 3 = 12. Half the time gives roughly half the coins: 12 ÷ 2 = 6.
Challenge
Stretch problems. Expect to think before you write.
- Main.tscn has four Coin instances. You change one instance’s scale in Main.tscn, then change the sprite in Coin.tscn. Describe what each of the four coins looks like when you run the game.
Check your answer
Answer: All four show the new sprite. Only the one you rescaled is a different size; the other three keep the original scale.Editing the source scene updates every instance; a property changed on one instance is an override that stays with that copy.
Review
Keep earlier skills sharp.
- Review (Lesson 1.2): the player script moves with move_and_slide() and names its parameter _delta. Why does it not multiply by delta, and what does the underscore tell Godot?
Check your answer
Answer: move_and_slide() moves the body by its velocity and handles the frame time itself. The underscore says the parameter is not used.In Lesson 1.2 you multiplied by delta yourself because you changed position directly.
Coin-Grab: Rules Mapped to Code, and the Score Arithmetic
SLS original; the 433-pixel figure is an SLS computation (two million random pairs, fixed seed) · SLS original
Why this reading. The build log asks you to map each written rule to the line of code that enforces it and the predict block asks what a shorter timer does. This sheet gives the mapping worked out, and the arithmetic behind the score you should expect.
Rules to code, mapped
| Written rule | Where it lives | Line |
|---|---|---|
| The player moves in eight directions | player script, _physics_process | velocity = Input.get_vector(...) * speed |
| Only the player scores | coin script, _on_body_entered | if body.is_in_group("player"): |
| Touching the coin scores one point | coin emits; main scene adds | collected.emit(), then score += 1 |
| The coin moves somewhere random | coin script | position = Vector2(randf_range(...), randf_range(...)) |
| The round ends after 30 seconds | main scene | round_timer.start(30.0), then _on_round_timer_timeout |
| No scoring after time is up | main scene | coin.queue_free() |
In your build log write one row like this for every rule, and add a column for what you saw when you tested it.
Numbers to check
- Window: 1152 × 648 pixels. Crossing it at speed 250 takes 1152 ÷ 250 = 4.6 seconds.
- Coin range: x from 40 to 1100 and y from 40 to 600, a 1060 × 560 rectangle. Two random points in it are on average about 433 pixels apart (a computer estimate from two million random pairs).
- Assume the player and coin shapes each have radius 16, so touching starts about 32 pixels early. Each coin then costs about 433 − 32 = 401 pixels of travel, or 401 ÷ 250 = 1.6 seconds.
| Timer | Coins for a perfect player (time ÷ 1.6) | Compared with 30 seconds |
|---|---|---|
| 30 s | 18 to 19 | 1× |
| 10 s | 6 | one third |
So shortening to 10 seconds cuts the best possible score from about 18 to about 6, matching the lesson’s “roughly a third.” A person will score lower than the perfect player, and the score gap between good and average players shrinks in absolute terms, which is a design fact worth writing in your log.
Frames in a round
30 seconds at 60 frames per second is 30 × 60 = 1,800 physics frames; 10 seconds is 600.