Look up an instruction and trace what it does in the studio. Examples use names and functions from the lesson projects. Read each with the matching lesson when you want to run it.
Read your first script
extends
Start with Godot's Control type. Your script can use its area, receive input and show controls such as labels and buttons.
extends Control
Comments
Godot skips the text after a hash. Use comments to record the reason for a rule.
# This shelf has four columns.
Indentation
The colon opens a block. Indent the next instruction so it runs only when the slot is empty.
if slot_is_empty:
show_stock()
Variables and assignment
Give a value a name. The second line reads the old number, adds one and stores the result under edits.
var edits = 0
edits = edits + 1
Constant values
This setting keeps one value throughout play. A named width makes the row calculation easier to read.
const COLUMNS := 4
Type hints
An int holds whole numbers and a String holds text. A type hint tells Godot what each variable can hold.
var edits: int = 0
var label_text: String = "Lemon Fizz"
Type inference
Colon and equals ask Godot to work out the type from the first value. Quotes make this one a String.
var selected_id := "moon_milk"
Booleans
A Boolean has the value true or false. Store a fact like whether the display meets every clue.
var all_clues_match: bool = false
Strings and formatting
%s inserts text and %d inserts a whole number, in the same order as the list of values.
var tag = "%s ×%d" % ["Lemon Fizz", 2]
Null and Variant
Null means no value is available. A Variant can hold different kinds of values. Check its type before using it.
var loaded_data: Variant = null
Whole numbers and decimals
Four columns times three rows make twelve slots. Decimal division gives a quarter of a second for animation.
var slots = 4 * 3
var slide_seconds = 1.0 / 4.0
Integer division and remainder
With whole numbers, the division gives row one. The remainder from the percent sign gives column two. Together they locate slot six on a four-column shelf.
var column = 6 % 4
var row = 6 / 4Turn a display idea into a rule
Assignment or comparison
One equals sign stores a value. Two equals signs ask if the values match.
selected_slot = 4
var is_selected = selected_slot == 4
and, or and not
and needs both tests to pass. or needs at least one. not reverses true and false.
if selected_slot >= 0 and not shelf.is_empty():
inspect_selection()
if, elif and else
Godot reads the tests from the top and runs the first match. The else block runs if all tests fail.
if product_id == "":
show_empty()
elif remaining == 0:
show_out_of_stock()
else:
show_product()
Conditional expression
Check the middle condition. Take the value on the left if true and the one on the right otherwise.
var label_text = "Empty" if product_id == "" else product_id
match
Compare a value against patterns. An underscore catches anything that reaches it.
match category:
"crafts":
return "Craft supplies"
_:
return "Check the catalogue"
for and range
Repeat for each number from zero to three. The end of a range is excluded.
for column in range(4):
show_slot(column)
while, break and continue
while checks before each pass. continue skips ahead to the next pass. break exits the loop.
while index < shelf.size():
var item = shelf[index]
index += 1
if item == "":
continue
if item == wanted:
break
Parameters and return values
A caller passes a row and column. The arrow says the output is a whole number. Row one, column two gives index six.
func slot_index(row: int, column: int) -> int:
return row * 4 + column
Default arguments and void
The caller can leave out the text to use the default. void means the function sends no value back.
func show_message(text: String = "Choose a miniature") -> void:
status.text = text
Early return
Leave immediately if the slot number is outside the valid range. This guard protects later shelf reads.
if slot < 0 or slot >= shelf.size():
return
Static functions
Call the helper through its script. It calculates a value from its input without creating a screen node.
static func row_start(row: int) -> int:
return row * 4Track stock and solve a display
Array indices
Arrays store values in order. The first value is at index zero. Here empty strings mark unused positions.
var row: Array[String] = ["lemon_fizz", "", "moon_milk", ""]
var first = row[0]
Size, membership and count
count includes every match. in asks only whether there is a match. size counts all positions.
var filled_drinks = row.count("lemon_fizz")
var stocked = "moon_milk" in row
Changing an array
Append adds a snapshot at the end. pop_back takes the latest snapshot out, which is the one Undo needs.
var history: Array = []
history.append(shelf.duplicate())
var previous = history.pop_back()
Dictionaries and get
Look up a value by its key. When a key is missing, get returns the supplied default.
var stock = {"lemon_fizz": 2, "moon_milk": 1}
var has_paints = stock.get("pocket_paints", 0)
Arrays inside dictionaries
Read the value under slots first. That value is an array, so use its first index to get zero.
var brief = {"slots": [0, 4], "category": "drinks"}
var first_slot = brief["slots"][0]
Deep copies
Copy the nested arrays and dictionaries as well as the outside collection. A practice placement can then change the candidate without modifying the current display.
var candidate = brief_state.duplicate(true)
Coordinates and neighbours
Measure how many steps apart two grid points are using only left, right, up and down. A total of one means they share an edge.
var touches = absi(a.x - b.x) + absi(a.y - b.y) == 1
Count and compare
Subtract the number already displayed from the number supplied. Use the result to decide whether there is a piece left.
var left = int(stock.get(id, 0)) - shelf.count(id)
Backtracking
Try a place and let the same function try the next one. If that route fails, remove the choice and continue trying. The full function needs a stopping condition and a loop over possible choices for this slot.
shelf[slot] = choice
if search(slot + 1):
return true
shelf[slot] = ""
Reject an impossible branch early
A partial shelf can already have too many drinks. Return now so the solver can try a different branch.
if placed_drinks > target_drinks:
return false
Assertions
A debug test can compare a result with an expected answer and report a useful failure message.
assert(slot_index(2, 3) == 11, "Last shelf slot changed")Connect the shelf to the screen
_ready, nodes and add_child
Godot calls _ready when the node is ready. Put the new label in the scene tree so Godot can show it.
func _ready() -> void:
var slip = Label.new()
add_child(slip)
preload
Load a script resource with this script so its game calculations are available through Rules. Use the file name in your checkpoint.
const Rules = preload("res://scripts/shelf_rules.gd")
@onready and node paths
Wait for the scene to be ready, then store the child named DisplayTitle in a variable.
@onready var display_title: Label = $DisplayTitle
Signals and emit
A signal carries news that something occurred. A listener can update its selection to slot four.
signal slot_selected(slot: int)
func choose_slot() -> void:
slot_selected.emit(4)
connect, Callable and bind
Connect a button's signal to a callable function. bind keeps the slot number so the function receives it when the button is pressed.
tile_button.pressed.connect(choose_slot.bind(4))
Lambdas
A lambda is a short function with no name. Godot calls this one when the hint button is pressed.
hint_button.pressed.connect(func(): show_hint())
InputEvent
Godot passes the input event into the function. Respond to the mapped right action after earlier controls have had a chance to use it.
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed("ui_right"):
move_focus_right()
Focus
Allow a control to receive keyboard focus. grab_focus starts keyboard navigation from that control.
product_button.focus_mode = Control.FOCUS_ALL
product_button.grab_focus()
Vector2, Rect2 and Color
Use points for screen coordinates and a rectangle for position plus size. A hexadecimal colour describes the paper shade.
var frame = Rect2(Vector2(16, 24), Vector2(84, 60))
var paper = Color("#ffe7ce")
_draw and queue_redraw
Godot calls _draw when the canvas must update. Use queue_redraw after a selection changes, and compute rules outside drawing.
func _draw() -> void:
draw_rect(frame, paper)
Tween
Show a marker sliding to the new position. The animation displays a move the rules have already accepted.
create_tween().tween_property(marker, "position", target, 0.2)
Touch and feedback
Give visible feedback as well as any sound. A player can confirm the clue even on a muted phone.
func announce() -> void:
status.text = "Clue matched"
chime.play()Save your work, check it and share it
Resource and user paths
res:// finds packaged game resources. user:// locates a folder the game can write to on the current device.
const BRIEFS = "res://levels/briefs.json"
const SAVE = "user://tiny_shelf_studio.cfg"
FileAccess
Check that the file opened. Read its text and close it after you finish.
var source = FileAccess.open(BRIEFS, FileAccess.READ)
if source != null:
var text = source.get_as_text()
source.close()
JSON and is
Parse structured text, then check what kind of value came back before trying to use it.
var value: Variant = JSON.parse_string(text)
if value is Array:
load_briefs(value)
ConfigFile
Save a value under a section and key. Check the returned error code before showing a saved message.
var progress = ConfigFile.new()
progress.set_value("album", "badges", 3)
var saved = progress.save(SAVE)
Versioned saves
Read a stored format version and supply one for an older save. Convert older data before loading fields introduced later.
var schema = int(progress.get_value("meta", "schema", 1))
Lifecycle callbacks
Godot can send a pause notice when the player leaves the app. Save after important events as well, such as finishing a brief.
func _notification(what: int) -> void:
if what == NOTIFICATION_APPLICATION_PAUSED:
save_progress()
Print and warnings
Send a value to Output while you investigate it. A warning reports a problem without ending play.
print("Current shelf: ", shelf)
push_warning("Progress could not be read")See the complete GDScript language reference and the Godot class reference.