Level Editor/Scripting/Language

From TeamSpec Wiki
Jump to navigation Jump to search

Map scripts are written in GDScript, Godot's scripting language. When you export or run the map, the editor compiles your scripts into the form the game runs. It checks them the same way while you type: each script tab lists its errors under the code and marks their lines. A script that does not compile stops the export, and the run, with every error listed at its line.

The game supports a part of GDScript: everything a gamemode needs, and nothing that reaches outside the match. This page says what is in it, what error you get for what is not, and what limits a running script has.

What a script can use

Declarations

  • The first line names the script's base class: extends GamemodeServerScript, extends GamemodeClientScript or extends GamemodeBotScript.
  • const, and var with a type (var score: int = 0), an inferred type (var score := 0) or none.
  • enum, named or not.
  • func, with typed parameters, default values and a return type.
  • @warning_ignore is accepted and does nothing.

Statements

  • if, elif, else, while, break, continue, return, pass.
  • for over a number (for i in 3), range() with one to three arguments, an Array, a Dictionary (its keys) or a String.
  • match with literal and constant patterns, several patterns per branch, _, var x to bind the value, and when guards.
  • Assignment and compound assignment (+=, -= and the rest) to local variables, the script's variables, self.x, a[i], d[k], d.k and a vector's v.x.

Expressions

  • Arithmetic, comparison and logic: + - * / % **, == != < <= > >=, and or not, and the conditional x if condition else y.
  • in and not in; is against String, StringName, bool, Vector3, Array, Dictionary or Callable; as.
  • % formatting: "%d souls" % count.
  • Array and Dictionary literals, with either key syntax ({"a": 1} or {a = 1}).
  • Lambdas, func(x): return x * 2, handed to sort_custom, filter, map, reduce, any or all, or called with .call().
  • super() and super.name() in a hook you override, and self.name.

Types

bool, int, float, String, StringName, Vector3, Array and typed arrays such as Array[int], Dictionary (a typed Dictionary is treated as a plain one), the packed arrays, Callable for a lambda, Variant, and your script's own enums.

Functions, constants and methods

Math, random numbers, str, len, range and print; PI, TAU, INF, NAN and Vector3.ZERO, Vector3.UP and the other vector constants; and the common methods of Arrays, Dictionaries, Strings and vectors, including a Dictionary's get(key, default). The complete list is on What a script may use.

Everything the game lets a script do, it does through api: see the reference.

Numbers

GDScript keeps whole numbers (int) and decimals (float) apart, and a running map script works out which is which from the types you wrote. Give your numbers types and every answer is the one GDScript gives:

  • int / int drops the remainder: with var a: int = 7, a / 2 is 3. When the editor cannot tell whether a division is between whole numbers, for example a value read from a Dictionary, it is an error asking you for a type. The same goes for **.
var half: int = _store["count"] / 2    # error: give the left side a type
var count: int = _store["count"]
var half: int = count / 2              # fine
  • % between two floats is an error, as in GDScript. Use fmod.
  • A match on number patterns needs the value it matches to have a type, because 1 does not match 1.0.
  • is int, is float and typeof are not available, for the same reason. Use typed variables instead.
  • A whole decimal kept where it has no type (in an untyped Array, as a Dictionary value, or in an untyped variable that is assigned more than once) prints without its .0: 5, not 5.0. A float variable prints 5.0.
  • In an Array or a Dictionary, 1 and 1.0 count as the same value for has, find, count and as Dictionary keys.

String and StringName are one kind of text in a running script: is String is true for both, and a StringName inside an Array or Dictionary prints as plain text.

Reading server.gd from bot.gd

In bot.gd, server is your server.gd:

  • server.CARRY_CAP reads one of its constants, and server.setup_left one of its variables, as it is right now.
  • server.may_take(handle, bot) calls one of its functions. The function runs as part of server.gd, so the bots ask the rules instead of keeping a copy of them. Call only functions that answer a question: whatever a function changes, it changes in the rules.
  • Nothing can be assigned through server. server.setup_left = 0.0 is an error: a bot script reads the server script through server, and cannot change it.
  • server works in every hook, but not while bot.gd's own variables get their first values: server is not there yet while the bot script's members are set up; read it in a hook.
  • The Bot tab checks every server. name against the Server tab: the server script has no member nope.

A pickup someone has taken is gone: it is no longer in api.pickups(). What a player holds is whatever server.gd recorded when _pickup_collected ran. Below it is a player counter, which every script can read with api.get_player (the client script too, to show it). A record kept in a server.gd variable works as well, and bot.gd reads it through server.

extends GamemodeServerScript

const CARRY_CAP := 5
const DEPOSIT_ZONE := &"Deposit Zone"

## Seconds of setup left. Nobody can take a soul until it runs out.
var setup_left: float = 30.0


func _declare() -> void:
	api.declare_player_counter(&"souls_carried", 0, 0, CARRY_CAP)


func _tick(delta: float) -> void:
	setup_left = maxf(0.0, setup_left - delta)


func _player_died(entity_id: int, _killer_id: int, default_seconds: float) -> void:
	api.set_player(entity_id, &"souls_carried", 0)
	api.respawn_in(entity_id, default_seconds)


## Whether this player may take this soul. _can_collect asks, and so does bot.gd.
func may_take(handle: int, entity_id: int) -> bool:
	if setup_left > 0.0 or api.get_player(entity_id, &"souls_carried") >= CARRY_CAP:
		return false
	return api.pickup_team(handle) != api.team_of(entity_id)


func _can_collect(handle: int, entity_id: int) -> bool:
	if api.pickup_kind(handle) != &"soul":
		return true
	return may_take(handle, entity_id)


func _pickup_collected(handle: int, entity_id: int) -> void:
	if api.pickup_kind(handle) == &"soul":
		api.add_player(entity_id, &"souls_carried", 1)
extends GamemodeBotScript

const REVIEW_SECONDS := 1.0

var _review: float = 0.0


func _tick(delta: float) -> void:
	_review -= delta
	if _review > 0.0:
		return
	_review = REVIEW_SECONDS
	for bot in api.bots():
		if not api.is_alive(bot):
			continue
		if server.setup_left > 0.0:
			api.bot_roam(bot)
		elif api.get_player(bot, &"souls_carried") >= server.CARRY_CAP:
			_go_home(bot)
		elif not _take_a_soul(bot):
			_hunt_a_carrier(bot)


## Full: walk to our own deposit zone.
func _go_home(bot: int) -> void:
	for zone in api.zones_labeled(server.DEPOSIT_ZONE):
		if api.zone_team(zone) == api.team_of(bot):
			api.bot_move_to(bot, api.zone_position(zone))
			return


## The first soul the rules would let this bot take.
func _take_a_soul(bot: int) -> bool:
	for handle in api.pickups():
		if api.pickup_kind(handle) == &"soul" and server.may_take(handle, bot):
			return api.bot_collect(bot, handle)
	return false


## Nothing to pick up: go after an enemy who is holding souls.
func _hunt_a_carrier(bot: int) -> void:
	for entity_id in api.players():
		if api.team_of(entity_id) != api.team_of(bot) and api.is_alive(entity_id) \
				and api.get_player(entity_id, &"souls_carried") > 0:
			api.bot_attack(bot, entity_id)
			return
	api.bot_roam(bot)

More about bot orders is on Bots.

What is not supported

Each of these is an error at the line that uses it, in the script tab and when you export.

You wrote The error
signal scored signal: signals are not in the map script language
class Thing: class: inner classes are not in the map script language
static var, static func static: a map script's functions and variables belong to the script
class_name MyMode class_name: a map script cannot register a global class
extends anything but the script's own base class a server script starts with: extends GamemodeServerScript
@export, @onready and other annotations @export: annotations are not in the map script language
A variable with get: or set: properties with get/set are not in the map script language
await, yield, assert, breakpoint await is not in the map script language here
preload(), load() preload is not in the map script language
$Node, %Node node references ($Node, %Node) are not in the map script language
^"Path" node paths (^"...") are not in the map script language
get_tree(), OS, Engine or any other engine name identifier "get_tree" is not declared
Another type: Color, Vector2, Node and the rest the type Color is not in the map script language
&, |, ^, ~, <<, >> the bitwise operator & is not in the map script language
A lambda with a name, func named(): named lambdas are not in the map script language
A lambda parameter with a default value a lambda's parameters have no default values in the map script language
An Array or Dictionary pattern in match array and dictionary patterns are not in the map script language
value is int, value is float is int cannot be answered in a compiled script: int and float are one number type there
A method that is not on the list, such as to_upper String has no method to_upper in the map script language
A method called on a type, such as String.num() String.num is not in the map script language
A server call in the client script api.set_global is not available to a client script
An api name that does not exist, or api.call() the api has no method or constant call
A division the editor cannot settle (see Numbers) cannot tell whether this is an integer division (GDScript's int / int drops the remainder): give the left side a type (int or float)
A whole number longer than 15 digits the integer 1234567890123456 is too large: a map script's integers stay within 15 digits
A name with a letter outside A to Z, such as café 'é': a map script's names are ASCII letters, digits and underscores

Some GDScript functions are not available, each with its own message:

Function The error
push_error, push_warning, printerr push_error is not in the map script language; use api.log
prints, printt, print_rich prints is not in the map script language; use print
typeof typeof is not in the map script language: int and float are one number type in a compiled script
var_to_str var_to_str is not in the map script language; use str
Callable() constructing a Callable is not in the map script language; use a lambda
load, ease, seed, randomize, hash, str_to_var, type_string, is_instance_of, instance_from_id, weakref seed is not in the map script language

Each mistake is one error, at its cause. var v := Vector2(1, 2) gives identifier "Vector2" is not declared and nothing about v, and a number or string written wrong is reported once without disturbing the code after it.

Limits

A running script cannot hold up the match:

  • Time. Each hook has a time budget for one call. A hook that runs past it, such as a while true: loop that never ends, is stopped with ran past its time budget of ... ms, and the next tick runs as usual.
  • Memory. server.gd and bot.gd share a memory limit, and client.gd has its own. A script that holds more than that is stopped with ran out of memory, followed by the limit.
  • Errors. A hook that fails (an error such as an index out of range, the time budget or the memory limit) is skipped and the match goes on. A hook that answers a question takes the default answer: _can_collect and _can_join_team allow, and a failed _spawn_position puts the player at the center of the map. The game prints the error once for each hook and line, naming your script and its line, then the calls that led there:
Map script server.gd, _tick failed and was skipped: server.gd:6: Out of bounds get index '3' (on base: 'Array')
stack traceback:
	server.gd:6 in _tick
  • Size. A script that is enormous, or nests blocks or brackets extremely deep, is refused with an error that says which limit it reached.

Testing a mode shows where to read what the game prints.

Exported maps

A map carries its scripts compiled. Each export is compiled for the game version the editor belongs to. If the game and the map were built for different versions of the scripting runtime, the game refuses the map and names both versions; export the map again with an editor that matches the game.

TeamSpec Level Editor
Basics Getting started · Interface · Viewport and camera · Selecting and hiding · Keyboard shortcuts · Settings · Map Config · Troubleshooting
Menus File · Edit · View · Tools · Functional
Panels Scene tree · Inspector · Materials · Props · Snapping · UV editor · Displacement · Terrain
Tools Move, Rotate and Scale · Box · Sphere · Cylinder · Prism · Stairs · Spiral Stairs · Spiral Tower · Arch · Path Brush · Plane · Terrain · Clip · Duplicate · Ruler and Cordon · Edit Vertex and Edge · Edit Face · Loop Cut · Material Brush · Vertex Color Brush · Displacement · Prop Path
Entities Brush · Zone · Group · Mirror Node · Prop · Spawn Point · Supply Pickup · World Boundary · Lights · Fog Volume · Water · Sounds · Anchor Platform · Payload Track · Boss Spawn · Map Marker · World Text · Decal · Door · Button · Logic entities · 3D Skybox · Nav Region
Workflows Your first map · Brushes and CSG · Materials and UVs · Lighting and lightmaps · Bots and navigation · Mirrored maps · Outputs and logic · Custom assets · Playtesting · Exporting and publishing · Importing Source maps
Scripting Overview · Server rules · Client HUD · Bots · Teams and spawning · Zones · Pickups · Payload tracks · Map entities · Language · Sandbox limits · Testing · King of the Hill · Team Deathmatch · Payload · Conquer · Soul Banking · Service · Training Range · API reference · What a script may use