TExcelTAD
Home › Godot 4 with GDScript › Godot Exercises

Godot Exercises

Practice the GDScript you need every day in Godot: typed functions, dictionaries, signals, frame-rate independent movement, saving and a state machine. Each exercise has a starter script with its current, wrong output, and a task with the expected output. Edit the parts marked TODO, then run the script in your own project (or with godot --headless -s for the extends SceneTree ones) and compare. When you are done, or stuck, open the solution.

Tip: To run a script without a scene, save it as exercise.gd in a project folder and run godot --headless -s exercise.gd from a terminal. Scripts that extend Node need a scene: attach them to the root node of a new scene and press F6 (Run Current Scene).

Exercise 1: Damage with armor

Topics: GDScript Syntax, Static Typing

Armor reduces each hit, but every hit does at least 1 damage, and health never drops below 0 or rises above 100. Use the typed built-ins maxi() and clampi(). Expected output:

text
80
49
0
99
gdscript · try it yourself
extends SceneTree

func apply_damage(health: int, damage: int, armor: int) -> int:
	# TODO: armor reduces damage, but every hit does at least 1;
	# health never goes below 0
	return health - damage

func _init():
	print(apply_damage(100, 30, 10))
	print(apply_damage(50, 5, 10))
	print(apply_damage(15, 40, 0))
	print(apply_damage(100, 0, 0))
	quit()
70
45
-25
100
Show solution
gdscript
extends SceneTree

func apply_damage(health: int, damage: int, armor: int) -> int:
	var taken := maxi(damage - armor, 1)
	return clampi(health - taken, 0, 100)

func _init():
	print(apply_damage(100, 30, 10))
	print(apply_damage(50, 5, 10))
	print(apply_damage(15, 40, 0))
	print(apply_damage(100, 0, 0))
	quit()

Exercise 2: Inventory stacks

Topics: Arrays, Dictionaries & Strings, typed dictionaries

Complete add_item and remove_item. Removing more than you have fails and changes nothing; a stack that reaches 0 is erased. Expected output:

text
{ "potion": 3, "arrow": 20 }
false true true
{ "potion": 2 }
gdscript · try it yourself
extends SceneTree

var inventory: Dictionary[String, int] = {}

func add_item(item: String, count: int) -> void:
	pass  # TODO: add count to the item's stack (create it if missing)

func remove_item(item: String, count: int) -> bool:
	return false  # TODO: remove count if there are enough; erase empty stacks

func _init():
	add_item("potion", 2)
	add_item("arrow", 20)
	add_item("potion", 1)
	print(inventory)
	print(remove_item("arrow", 25), " ", remove_item("arrow", 20), " ", remove_item("potion", 1))
	print(inventory)
	quit()
{  }
false false false
{  }
Show solution
gdscript
extends SceneTree

var inventory: Dictionary[String, int] = {}

func add_item(item: String, count: int) -> void:
	inventory[item] = inventory.get(item, 0) + count

func remove_item(item: String, count: int) -> bool:
	if inventory.get(item, 0) < count:
		return false
	inventory[item] -= count
	if inventory[item] == 0:
		inventory.erase(item)
	return true

func _init():
	add_item("potion", 2)
	add_item("arrow", 20)
	add_item("potion", 1)
	print(inventory)
	print(remove_item("arrow", 25), " ", remove_item("arrow", 20), " ", remove_item("potion", 1))
	print(inventory)
	quit()

Exercise 3: A Health component with signals

Topics: Signals, components

Health is a reusable child node: it knows nothing about the player, it only reports changes. Fix hurt() so health stops at 0, changed fires only while the value still changes, and died fires exactly once. Expected output:

text
health: 2
health: 1
health: 0
died!
gdscript · try it yourself
extends Node

# frames: 0
class Health extends Node:
	signal changed(value: int)
	signal died

	var max_value := 3
	var value := 3

	func hurt(amount: int) -> void:
		value -= amount
		changed.emit(value)
		# TODO: never go below 0, emit changed(value) when the value really changes,
		# and emit died exactly once when it reaches 0

func _ready():
	var health := Health.new()
	add_child(health)
	health.changed.connect(func(v: int): print("health: ", v))
	health.died.connect(func(): print("died!"))
	for hit in [1, 1, 5, 1]:
		health.hurt(hit)
health: 2
health: 1
health: -4
health: -5
Show solution
gdscript
extends Node

# frames: 0
class Health extends Node:
	signal changed(value: int)
	signal died

	var max_value := 3
	var value := 3

	func hurt(amount: int) -> void:
		if value == 0:
			return
		value = maxi(value - amount, 0)
		changed.emit(value)
		if value == 0:
			died.emit()

func _ready():
	var health := Health.new()
	add_child(health)
	health.changed.connect(func(v: int): print("health: ", v))
	health.died.connect(func(): print("died!"))
	for hit in [1, 1, 5, 1]:
		health.hurt(hit)

Exercise 4: Acceleration with move_toward

Topics: CharacterBody2D & move_and_slide, delta

Instant full speed feels stiff. Make the velocity approach MAX_SPEED by at most ACCEL * delta per physics frame with move_toward(). With an acceleration of 1800 px/s² and 60 physics frames per second, full speed takes 4 frames. Expected output:

text
v= 30.0 x= 0.50
v= 60.0 x= 1.50
v= 90.0 x= 3.00
v=120.0 x= 5.00
v=120.0 x= 7.00
v=120.0 x= 9.00
gdscript · try it yourself
extends Node2D

# frames: 6
const MAX_SPEED := 120.0
const ACCEL := 1800.0   # px/s² while the key is held
var velocity := Vector2.ZERO
var input_dir := 1.0     # pretend the player holds Right

func _physics_process(delta: float) -> void:
	# TODO: accelerate velocity.x towards input_dir * MAX_SPEED by at most ACCEL * delta
	velocity.x = input_dir * MAX_SPEED
	position += velocity * delta
	print("v=%5.1f x=%5.2f" % [velocity.x, position.x])
v=120.0 x= 2.00
v=120.0 x= 4.00
v=120.0 x= 6.00
v=120.0 x= 8.00
v=120.0 x=10.00
v=120.0 x=12.00
Show solution
gdscript
extends Node2D

# frames: 6
const MAX_SPEED := 120.0
const ACCEL := 1800.0   # px/s² while the key is held
var velocity := Vector2.ZERO
var input_dir := 1.0     # pretend the player holds Right

func _physics_process(delta: float) -> void:
	velocity.x = move_toward(velocity.x, input_dir * MAX_SPEED, ACCEL * delta)
	position += velocity * delta
	print("v=%5.1f x=%5.2f" % [velocity.x, position.x])

Exercise 5: Settings with ConfigFile

Topics: Saving: FileAccess, ConfigFile & JSON

Save the volume and the fullscreen flag to user://settings.cfg in two sections, then load them back with defaults for missing values. Expected output (the solution also prints the file):

text
{ "volume": 0.4, "fullscreen": true }
gdscript · try it yourself
extends SceneTree

const PATH := "user://settings.cfg"

func save_settings(volume: float, fullscreen: bool) -> void:
	var cfg := ConfigFile.new()
	# TODO: store volume under [audio] and fullscreen under [video], then save to PATH

func load_settings() -> Dictionary:
	var cfg := ConfigFile.new()
	# TODO: load PATH (if it fails, keep the defaults) and read the two values
	return {"volume": 1.0, "fullscreen": false}

func _init():
	save_settings(0.4, true)
	print(load_settings())
	quit()
{ "volume": 1.0, "fullscreen": false }
Show solution
gdscript
extends SceneTree

const PATH := "user://settings.cfg"

func save_settings(volume: float, fullscreen: bool) -> void:
	var cfg := ConfigFile.new()
	cfg.set_value("audio", "volume", volume)
	cfg.set_value("video", "fullscreen", fullscreen)
	cfg.save(PATH)

func load_settings() -> Dictionary:
	var cfg := ConfigFile.new()
	cfg.load(PATH)   # on error the file stays empty and the defaults below are used
	return {
		"volume": cfg.get_value("audio", "volume", 1.0),
		"fullscreen": cfg.get_value("video", "fullscreen", false),
	}

func _init():
	save_settings(0.4, true)
	print(load_settings())
	print(FileAccess.get_file_as_string(PATH).strip_edges())
	quit()

The file is plain text, so players (and you, while debugging) can read and edit it:

ini
[audio]

volume=0.4

[video]

fullscreen=true

Exercise 6: An enemy attack state machine

Topics: A State Machine in GDScript, match, enums

An enemy winds up for 0.05 s, attacks for one frame, then cools down for 0.1 s before it can attack again. Fill in the three TODO branches. Expected output:

text
frame  2: IDLE -> WINDUP
frame  5: WINDUP -> ATTACK
frame  6: ATTACK -> COOLDOWN
frame 13: COOLDOWN -> IDLE
gdscript · try it yourself
extends Node

# frames: 16
enum State { IDLE, WINDUP, ATTACK, COOLDOWN }

var state := State.IDLE
var time_in_state := 0.0
var frame := 0

func _physics_process(delta: float) -> void:
	frame += 1
	time_in_state += delta
	match state:
		State.IDLE:
			if frame == 2:   # the player came into range
				change_state(State.WINDUP)
		State.WINDUP:
			pass  # TODO: after 0.05 s, go to ATTACK
		State.ATTACK:
			pass  # TODO: go straight to COOLDOWN (the hit happens on entering ATTACK)
		State.COOLDOWN:
			pass  # TODO: after 0.1 s, go back to IDLE

func change_state(new_state: State) -> void:
	print("frame %2d: %s -> %s" % [frame, State.keys()[state], State.keys()[new_state]])
	state = new_state
	time_in_state = 0.0
frame  2: IDLE -> WINDUP
Show solution
gdscript
extends Node

# frames: 16
enum State { IDLE, WINDUP, ATTACK, COOLDOWN }

var state := State.IDLE
var time_in_state := 0.0
var frame := 0

func _physics_process(delta: float) -> void:
	frame += 1
	time_in_state += delta
	match state:
		State.IDLE:
			if frame == 2:   # the player came into range
				change_state(State.WINDUP)
		State.WINDUP:
			if time_in_state >= 0.05:
				change_state(State.ATTACK)
		State.ATTACK:
			change_state(State.COOLDOWN)
		State.COOLDOWN:
			if time_in_state >= 0.1:
				change_state(State.IDLE)

func change_state(new_state: State) -> void:
	print("frame %2d: %s -> %s" % [frame, State.keys()[state], State.keys()[new_state]])
	state = new_state
	time_in_state = 0.0

Note: The cooldown ends on frame 13, seven frames after it started, not six. Adding 1/60 six times gives a number a tiny bit below 0.1, so time_in_state >= 0.1 is still false on the sixth frame. Timers measured by adding delta are exact only to about one frame: fine for gameplay, but don't expect == comparisons on accumulated time to work. For exact timing, count physics frames or use a Timer node.

Test yourself

Which call moves velocity.x towards 120 by at most ACCEL * delta, without overshooting?

  1. lerp(velocity.x, 120.0, ACCEL)
  2. move_toward(velocity.x, 120.0, ACCEL * delta)
  3. clamp(velocity.x, 0, 120)
  4. velocity.x += 120 * delta

In Exercise 3, why does Health emit signals instead of calling the player's die() method?

  1. Signals are faster than method calls
  2. So the component works on any parent: whoever cares connects to died
  3. Godot forbids calling methods on a parent
  4. Signals are saved with the scene

ConfigFile.load() fails because the file doesn't exist yet. What does cfg.get_value("audio", "volume", 1.0) return?

  1. null
  2. It throws an error
  3. The default, 1.0
  4. 0.0