GDScript language reference for Market Day London

Look up an instruction and trace what it changes at the market. These small examples assume some names and functions come from your lesson project.

Back to Market Day London

Read the first line

extends

Build on Godot's Control type. It provides a screen region that can show children such as labels and buttons.

extends Control

Comments

Godot skips the text after the hash. Use it to record why a decision was made.

# A full basket holds three items.

Blocks and indentation

The colon opens a block. The indented instruction only runs when Nia is at the counter.

if at_counter:
	show_order()

Assignment

Name a value. To add a turn, read the old number, add one, and put the result back into turns.

var turns = 0
turns = turns + 1

Constants and names

Use one fixed value for the three slots. The uppercase name helps a reader spot a fixed game rule.

const CAPACITY := 3

Types

An int stores whole numbers and a String stores text. Type hints catch some mistakes as you write.

var turns: int = 0
var item_name: String = "bread"

Inferred types

Godot works out the type from the first value. Here it sees text and keeps the variable a String.

var title := "First Crate"

Booleans

A Boolean is one of two values, true or false. Use it for facts a test can answer with yes or no.

var has_gold: bool = false

Null and Variant

Null means no value is present. A Variant can hold several kinds of values. Check the type before treating it as a number or dictionary.

var saved_value: Variant = null

String formatting

%d takes a whole number and %s takes text. This slip becomes 2 × bread.

var slip = "%d × %s" % [2, "bread"]

Integer and decimal maths

Subtract whole turns. Use decimals when a quarter second is useful.

var budget = 18 - turns
var transition_seconds = 1.0 / 4.0

Make decisions and repeat work

Comparison

Two equals signs compare positions. The result is true only if both coordinates match.

var at_counter = tile == counter_tile

Logic

and needs both parts. not flips a Boolean. or succeeds if at least one part is true.

if at_counter and not basket.is_empty():
	check_order()

if, elif and else

The first matching branch runs. If neither condition matches, the else block runs.

if symbol == "#":
	show_barrier()
elif symbol == "A":
	show_apple_stall()
else:
	show_paving()

Conditional expression

Check the middle condition and take the left value if true. Take the right value otherwise.

var sky = "rainy" if rainy else "clear"

match

Use match to look for a pattern. The underscore catches any value the earlier patterns missed.

match symbol:
	"B":
		return "Bakery"
	_:
		return "Check the map"

for and range

Repeat the block for x from zero to six. range stops before seven.

for x in range(7):
	draw_tile(Vector2i(x, 0))

while, continue and break

Check the condition before each pass. continue skips the rest of a pass. break leaves the loop.

while not queue.is_empty():
	var candidate = queue.pop_front()
	if candidate in visited:
		continue
	if candidate == goal:
		break

Functions and return values

The parameters are inputs. The arrow gives the type of the answer. return hands the new position back.

func moved_tile(tile: Vector2i, direction: Vector2i) -> Vector2i:
	return tile + direction

Default arguments

Call the function with text to use your own label. Leaving the argument out uses Gold. void means there is no return value.

func show_badge(text: String = "Gold") -> void:
	badge.text = text

Static functions

A static function can run through its script class. The rule receives a count and works without any buttons or labels.

static func within_capacity(count: int) -> bool:
	return count <= 3

Early return

Leave the function immediately, before doing the work that comes after the guard.

if turns < 0:
	return

Track Nia, the basket and a route

Vector2i and Vector2

Both combine x and y. Use whole coordinates for tiles and decimals for positions on the screen.

var tile = Vector2i(3, 2)
var screen_point = Vector2(300.0, 160.0)

Indexing

Read row zero, then character one. The symbol is A. Always make sure the index exists.

var rows = ["CA.", "..."]
var symbol = rows[0][1]

Arrays and changes

An Array stores values in order. append adds one at the end. pop_back removes and returns the last item.

var basket: Array[String] = ["apple"]
basket.append("bread")
var last = basket.pop_back()

Membership and counts

in answers whether an apple appears at least once. size counts every item, including repeated pieces.

var has_apple = "apple" in basket
var pieces = basket.size()

Dictionaries and get

A dictionary links keys to values. A missing key uses the supplied fallback here, so flowers is zero.

var order = {"apple": 2, "bread": 1}
var flowers = order.get("flower", 0)

Counts and equality

Compare apple, bread and flower counts in the same fixed order. Two loaves require a bread count of two.

var exact = load_counts == wanted_counts

Copying nested state

A deep copy gives a route search its own nested arrays and dictionaries. Mutating a trial basket leaves the live basket alone.

var draft = state.duplicate(true)

Queue with a cursor

Read the oldest waiting entry, then advance the cursor. Appending new entries behind it visits near positions before far ones.

var current = queue[head]
head += 1

Visited state

Include location, basket and which order is active. Nia can be at the same stall with two different baskets and need different actions.

var key = "%s|%s|%d" % [str(tile), str(load_counts), order_index]

Packed keys

Turn each row and column pair into one unique number on a rectangular board. The finished rules combine that index with basket counts and the order number.

var tile_index = tile.y * width + tile.x

Replay

Follow the route one action at a time using the ordinary game rule. This checks that the advice works in play.

for action in route:
	state = Rules.step(shift, state, action)

Assertions

In a debug test, stop and report a broken expectation. Here the basket should contain two apples and one bread.

assert(load_counts == [2, 1, 0], "Check replay counts")

Connect the controls and visuals

_ready and the scene tree

Godot calls _ready when a node is ready. add_child gives the new label a place in its scene tree.

func _ready() -> void:
	add_child(Label.new())

preload

Bring in another script when Godot loads this one, so you can call its static game rules through Rules.

const Rules = preload("res://scripts/market_rules.gd")

@onready and node paths

Wait until the scene is ready, then find the child named OrderSlip. This is useful in scenes drawn in the editor.

@onready var order_slip: Label = $OrderSlip

Signals and emit

Announce a choice and carry the action number with it. A listener can attempt to pick up an item.

signal action_selected(action: int)

func send_action() -> void:
	action_selected.emit(4)

connect, Callable and bind

A function you can call later is a Callable. bind gives that function an argument to use when the button is pressed.

east_button.pressed.connect(take_action.bind(1))

Lambdas

This small unnamed function runs after the press. The parentheses describe the arguments it receives.

hint_button.pressed.connect(func(): show_hint())

InputEvent

Godot supplies an event. Check the mapped right action and call the movement instruction.

func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("ui_right"):
		try_east()

_draw and redraw

Godot runs this function for drawing. queue_redraw asks it to draw again after the state changes.

func _draw() -> void:
	draw_rect(Rect2(0, 0, 56, 40), Color("#294f54"))

Signals from touch or mouse

Check what kind of event reached the control and whether the button went down. Godot can turn a touch into the same kind of event.

func _gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.pressed:
		check_tapped_tile(event.position)

Keyboard focus

Make it possible to navigate to the button and set it as the current keyboard target when the menu opens.

start_button.focus_mode = Control.FOCUS_ALL
start_button.grab_focus()

Tween and animation

Show the marker sliding for a fifth of a second. Calculate and store the valid destination in the rule first.

create_tween().tween_property(marker, "position", destination, 0.2)

Sound and text cues

Play the chime and show the result in text, so the update still reaches people playing in silence.

bell.play()
status.text = "Order collected!"

Save progress, debug and ship

Resource paths

res:// names a game resource. user:// names a writable folder for that game on the device.

const LEVELS := "res://levels/shifts.json"
const SAVE := "user://market_day_progress.cfg"

FileAccess

A file may fail to open. After checking, read its text and close the handle.

var file = FileAccess.open(LEVELS, FileAccess.READ)
if file != null:
	var text = file.get_as_text()
	file.close()

JSON and type tests

Turn a JSON string into values. Check the result's shape before treating it as a list of shifts.

var parsed: Variant = JSON.parse_string(text)
if parsed is Array:
	load_shifts(parsed)

ConfigFile

Put a value under a named section and key. The return code tells you whether the save succeeded.

var cfg = ConfigFile.new()
cfg.set_value("market", "gold", 2)
var outcome = cfg.save(SAVE)

Version tags and defaults

Read the version of a stored file. Here a missing version counts as version one.

var schema = int(cfg.get_value("meta", "schema", 1))

Call order and pause

A phone can pause a game when the player switches apps. The example receives that event. Save progress after important gameplay events too.

func _notification(what: int) -> void:
	if what == NOTIFICATION_APPLICATION_PAUSED:
		save_progress()

Output and warning

print shows a value in the Output panel. A warning records a problem so you can track down its cause.

print("Turns remaining: ", budget)
push_warning("Progress file could not be read")

Use the official GDScript reference for the full language and the Godot class reference for its built-in tools.