Scripting Guide
The GoNorth script language — from basics to advanced patterns.
Overview
Scripts are short programs that respond to events in your adventure. They're written in a simple language designed to be readable even if you've never programmed before.
Scripts are attached to locations, items, NPCs, and the game itself. Each script has an event — the event that causes it to run. You write scripts in the Script Editor, which you can open by double-clicking a location or item and choosing the Scripts tab, or via right-click → Edit Scripts on the map.
Programming for Beginners
If you've never written code before, don't worry — GoNorth scripts are designed to read almost like plain English. This section explains the ideas behind scripting so you feel confident writing your first script.
What is a script?
A script is a set of instructions that the game follows, one line at a time, from top to bottom. Each line either does something (like show text to the player) or makes a decision (like "if the player has a key, unlock the door").
Think of it like a recipe: the game reads each step in order and carries it out. Scripts run automatically when something happens — when the player enters a room, picks up an item, talks to a character, and so on.
Commands
A command tells the game to do something. Most commands look like this:
OutputText("You enter the dark cave.")
OutputText is the name of the command. The text inside the brackets
is what gets shown to the player. The quotes tell the game it's a piece of text
(not a number or a variable name).
You'll use OutputText constantly — it's how your adventure
communicates with the player. An empty call OutputText("") outputs
a blank line, useful for spacing.
Decisions — the if statement
Most interesting scripts need to make decisions. In GoNorth you use an
if statement:
if Player.HasItem("torch") then
OutputText("The torch lights the cave.")
else
OutputText("It is pitch dark. You can barely see a thing.")
endif
The game checks the condition (does the player have the torch?).
If it's true, it runs the then block. If it's false, it runs
the else block. Either way it then continues past endif.
Remembering things — variables
A variable is like a named box that holds a piece of information. You can put a value in, read it back later, and change it. For example:
# Store the player's hit points
Player.Variable(HitPoints) = 100
# Later, when a monster attacks
Player.Variable(HitPoints) -= 10
# Check if the player is still alive
if Player.Variable(HitPoints) <= 0 then
GameOver("You have been defeated.")
endif
Variables on Player, Location, NPC, and Global
are saved with the game, so they remember their value between turns and sessions.
Comments
Lines starting with # are comments — notes you write for yourself.
The game ignores them completely. Use them to explain what your script does:
# This script runs when the player enters the dungeon for the first time
if Location.VisitCount = 1 then
OutputText("A chill runs down your spine as you step inside.")
endif
Maths
You can use standard maths operators, or spell them out in plain English — both styles work identically:
| Symbol | English word | Meaning | Example |
|---|---|---|---|
+ | Add | Add | Player.Variable(HP) += 10 or Player.Variable(HP) Add 10 |
- | Subtract | Subtract | Player.Variable(HP) -= 5 or Player.Variable(HP) Subtract 5 |
* | Multiply | Multiply | damage *= 2 or damage Multiply 2 |
/ | Divide | Divide | damage /= 2 or damage Divide 2 |
% | — | Modulo (remainder) | if Daemon.TurnCount("x") % 8 = 0 then — true every 8th turn. A % with nothing after it is just the percent suffix in chance(30%). |
# Symbol style
Player.Score("task") = 10
Player.Variable(HitPoints) -= 5
Global.Variable(Multiplier) *= 2
# English word style — same result, more readable
Player.Variable(HitPoints) Subtract 5
Global.Variable(Multiplier) Multiply 2
# You can also use arithmetic in expressions
let damage = Randomise(6) + 2
let half = Player.Score.Total / 2
Order matters
The game runs your script line by line, in order. If you set a variable on
line 3, line 1 can't see it yet. And if you write GameOver()
on line 5, lines 6 and below will never run.
Use the Validate button in the Script Editor at any time — it checks your script for mistakes without running the game.
Variables
Variables store values that your scripts can read and change. There are three types:
| Type | Example values | Colour in editor |
|---|---|---|
| Number | 0, 42, 3.14 | ■ Peach |
| String | "Hello", "North" | ■ Green |
| Boolean | true, false | ■ Red |
Local variables
Local variables exist only during the current script run:
let score = 10
let greeting = "Hello, world!"
let isDone = false
# You can also write assignment without 'let':
score = 20
# Or use 'set...to' style:
set score to 30
Persistent variables
To store values that survive between turns, use variables on game objects. These are saved with the game.
# On a specific location
Location.Variable(DoorLocked) = true
Location(4).Variable(HideGold) = false
# On the player
Player.Variable(HitPoints) = 100
Player.Score("bonus") = 50
Player.Name = "Alice"
# On an NPC
NPC("George").Variable(Damage) = 5
# Global (anywhere in the game)
Global.Variable(RoomsVisited) = 0
Reading variables
if Location.Variable(DoorLocked) = true then
OutputText("The door is locked.")
endif
let hp = Player.Variable(HitPoints)
if hp < 20 then
OutputText("You are near death!")
endif
Compound assignment
Player.Variable(HitPoints) += 10 # add 10
Player.Variable(HitPoints) -= 5 # subtract 5
Global.Variable(Multiplier) *= 2 # multiply by 2
Player.Variable(Gold) Add 50 # natural language form of +=
Player.Variable(HitPoints) Subtract 10
String joining
Use AND to join text together. Numbers convert automatically:
OutputText("Hello, " AND Player.Name AND "!")
OutputText("Your score is: " AND Player.Score.Total AND " points.")
Control Flow
If statements — two forms
GoNorth supports two forms of if statement. The rule is simple:
if the statement follows then on the same line,
no endif is needed. If the body is on the next line,
the block must be closed with endif.
Inline form — single statement, no endif
if Player.HasItem("key") then OutputText("You have the key.")
if Player.Score.Total > 99 then OutputText("You are doing well!")
if chance(30) then OutputText("A bat swoops past!")
else.
If you need an else branch, use the block form below.
Block form — multiple statements, requires endif
if Player.HasItem("key") then
OutputText("You unlock the door.")
Location.ExitEnabled("North", true)
Player.Score("unlock_north") = 10
endif
Block form with else
if Player.HasItem("torch") then
OutputText("The torch lights the way.")
else
OutputText("It is pitch dark. You may be eaten by a grue.")
endif
Chained conditions — inline ifs together
Multiple inline ifs in a row are a clean way to handle mutually exclusive outcomes, like random message selection:
let r = Randomise(4)
if r = 1 then OutputText("The wind howls.")
if r = 2 then OutputText("Something creaks.")
if r = 3 then OutputText("A distant bell rings.")
if r = 4 then OutputText("Silence.")
Nested ifs
if NPC("George").IsAlive then
if NPC("George").Variable(GreetingGiven) = false then
NPC("George").Variable(GreetingGiven) = true
NPC("George").Say("Welcome, traveller!")
else
NPC("George").Say("Good to see you again.")
endif
else
OutputText("George lies dead. He cannot help you now.")
endif
Elseif chains
Use elseif (also elsif or elif) for
multi-branch conditions. One endif closes the whole chain:
if Player.Score.Total >= 200 then
OutputText("Hero of the realm!")
elseif Player.Score.Total >= 100 then
OutputText("A seasoned adventurer.")
elseif Player.Score.Total >= 50 then
OutputText("You've survived, at least.")
else
OutputText("Room for improvement.")
endif
Combining conditions
# and / or / not
if Player.HasItem("key") and Location.Variable(DoorLocked) = true then
OutputText("You unlock the door.")
endif
if not Player.HasItem("torch") then
OutputText("You can barely see anything.")
endif
if Player.Score.Total > 49 or Global.Variable(CheatEnabled) = true then
OutputText("The gate opens before you.")
endif
Comparison operators
| Operator | Meaning | Example |
|---|---|---|
= | Equal to | Player.Score.Total = 100 |
!= | Not equal to | npc.Name != "George" |
< | Less than | hp < 20 |
<= | Less than or equal | hp <= 0 |
> | Greater than | Player.Score.Total > 100 |
>= | Greater than or equal | weight >= 10 |
Quick reference
| Form | Syntax | else? | endif? |
|---|---|---|---|
| Inline | if cond then stmt | No | No (optional) |
| Block | if cond then … endif | Yes | Required |
Repeat loop
repeat 3 times
OutputText("The ground shakes!")
endrepeat
Foreach loop
# Loop over items in the current location
foreach item in Items
OutputText("You see: " AND item.Name)
endforeach
# Loop over NPCs in the current location
foreach npc in NPCs
if npc.IsAlive then
NPC(npc.Name).Say("Hello!")
endif
endforeach
# Items the player is carrying
foreach item in CarriedItems
OutputText(item.Name AND " — weight: " AND item.Weight)
endforeach
# Enabled exits from the current location
foreach link in Links
OutputText("Exit: " AND link.Direction)
endforeach
# Every location in the adventure
foreach loc in Locations
if loc.Visited then
OutputText(loc.Name AND " — visited")
endif
endforeach
Available collections: Items and NPCs (current location),
CarriedItems (player inventory), Links (current location's
enabled exits), Locations (every location in the adventure). Loop-variable
properties by collection:
| Collection | Loop variable properties |
|---|---|
Items / CarriedItems | Name, Weight, Size, IsPickable, IsVisible, IsOpen, ContentsVisible, IsCarried, IsInLocation, Description, ShortDesc, Id, Variable("name") |
NPCs | Name, ShortDescription/ShortDesc, Description, IsHere, IsAlive, IsEnabled, Id, LocationId, Variable("name") |
Links | Direction, ExitDescription, Description, IsEnabled, IsVisible (alias for IsEnabled) |
Locations | Name, Id, Visited, Variable("name") |
Looping over what the player can see
Besides Items and NPCs (everything in the current location,
hidden or not), loops can use the visible collections:
VisibleItems | Visible items here, including the contents of open containers. |
VisibleNPCs | NPCs here that are enabled and visible (dead NPCs are included — test npc.IsAlive). |
AllItems, AllNPCs | Every item or NPC in the adventure, wherever it is. |
Location.Items, Location.VisibleItems, Location.NPCs,
Location.VisibleNPCs and Player.Items are accepted as alternative
spellings. Loop variables also expose .IsHere and .LocationId
(-1 when carried), and NPC loop variables expose .IsVisible.
Location.VisibleItemCount and Location.VisibleNPCCount give the counts.
if Location.VisibleItemCount > 0 then
OutputText("You can see:")
foreach item in VisibleItems
OutputText(" " AND item.ShortDesc)
endforeach
endif
An NPC with Visible turned off in the NPC editor is still in the game, still runs
its scripts and still moves, but it is not in VisibleNPCs and the player can't
target it by name until you reveal it: NPC("Thief").IsVisible = true.
Sorted loops
Any foreach loop can process its collection in a chosen order by adding
sort by after the collection:
foreach npc in NPCs sort by npc.Variable("Agility") descending
OutputText(npc.Name AND " — Agility " AND str(npc.SortKey))
endforeach
Omit ascending/descending for ascending order (the default).
Inside the loop, <variable>.SortKey holds the value the loop was sorted
by for that element, so you don't need to repeat the sort expression. This is the
building block for things like initiative order in a combat script — sort NPCs by an
Agility variable, then compare each one's SortKey against the player's own
stat to decide who acts first.
Call another script
call, run, gosub, and RunScript("name") are all aliases for the same operation — they execute a named script by name and return when it finishes. The first three are keyword forms; RunScript is the function-call form (useful in inline pattern scripts).
# All four forms are identical — use whichever reads most naturally
call "ShowInventoryMessage"
run "ShowInventoryMessage"
gosub "ShowInventoryMessage"
RunScript("ShowInventoryMessage") # function-call form
# Lookup order:
# 1. The current location's Events dictionary (local override)
# 2. The adventure's GlobalEvents or GlobalProcedures dictionaries
# A local script with the same name shadows the global version.
Scripts can call other scripts to a maximum depth of 16. Deeper calls are silently ignored with an error line in the output. Recursion is possible but use it carefully.
Calling a global event from a local script
Automatic descriptions: the default global OnLocationEnter
script describes every room that has no OnEnter of its own
(if not Location.Script("OnEnter").Exists). Give a location an
OnEnter, or replace the global script, and you are responsible for the
description — use Location.Describe() / Location.DescribeExits()
to reuse the standard text.
When a location has its own OnEnter script it shadows the global one entirely.
Use call "OnEnter" to explicitly invoke the global version, so you can add
location-specific behaviour without copying the entire default script:
# Location OnEnter — play a sound, then run the standard global description
Audio("Howling").Play
call "OnEnter" # runs GlobalEvents["OnEnter"] if defined
The global script runs in a sub-interpreter and its output is
appended to the current result. call searches the current location's Events, then GlobalEvents, then GlobalProcedures — the local script is not re-entered.
Exit a script early
if Player.Score.Total < 0 then
GameOver("You ran out of luck.")
exit
endif
# This line only runs if the player is still alive
OutputText("You're still in the game.")
Leaving a loop early
Use BreakLoop inside a foreach or repeat loop
to stop iterating immediately — the rest of the script after the loop still runs. This
is different from exit (above), which ends the whole script,
not just the loop.
foreach npc in NPCs sort by npc.Variable("Agility") descending
if npc.SortKey < Player.Variable("Agility") then
BreakLoop
endif
OutputText(npc.Name AND " is faster than you.")
endforeach
OutputText("The rest of the script keeps running.")
BreakLoop has two aliases, StopLoop and ExitLoop
— all three behave identically. Note that StopLoop is not
the same as exit's own stop alias: stop (like
exit) ends the whole script, while StopLoop ends only the
current loop. Pick whichever name reads best in context.
How long a script can run
To keep games responsive, GoNorth limits how much work the scripts can do in a single turn. This includes every script that runs that turn: the command's script, location and NPC scripts, and all daemons. Normal adventures never get close to the limit.
If a script goes over it, usually because loops are nested so deeply that they multiply
(three repeat 100 times loops inside each other is a million passes), GoNorth stops it
and undoes the whole turn, so the game is left exactly as it was. The player sees
a short message and the turn does not count. In the Designer's play panel you'll see which script
stopped and which limit it hit. Verify Adventure points out nested repeats that can run more than
10,000 passes.
Retreating — Location.PreviousID
Location.PreviousID is the id of the location the player was in before the current one (0 if none).
Combine it with Player.Move() to send the player back the way they came — ideal for a flee command:
if Player.Variable(InCombat) then
Player.Variable(InCombat) = false
Player.Move(Location.PreviousID) # full move: OnExit, description, OnEnter
endif
Also readable as Player.PreviousLocationId. Player.GoTo() does not update it.
Hints — HINT command, two-tier resolution
The player types HINT (or HINTS) to get a contextual nudge
— a separate command from HELP, which shows general instructions. Resolution
checks two script hooks in order, both using the same key, OnHint:
Location.Events["OnHint"]— runs first, if present. If it callsHint.Continue, or produces no output at all, resolution falls through to step 2. Otherwise, whatever it output is the hint — done.Adventure.GlobalEvents["OnHint"]— runs if reached (either because there was no Location script, or the Location script fell through). Whatever it outputs is the hint.- Built-in fallback —
"You're not sure what to do next."— only if neither script exists, or neither produced any output.
# Location "Sitting Room" — Events["OnHint"]
if not Player.HasItem("Key") then
OutputText("Have you looked really hard for the key? How about looking under things — like THE RUG?")
else
Hint.Continue
endif
# Adventure Settings — Global Scripts — Events["OnHint"]
if not Global.Variable("TalkedToGeorge") then
OutputText("You need to speak to George to learn more.")
else
OutputText("You seem to be making good progress. Keep exploring.")
endif
Player.Score("hint_" AND Player.HintsUsed) = 0 - 1
No new scoring mechanic is needed — both OnHint scripts are ordinary
scripts, so "reduce score" and "check complex conditions" are just author code. The
example above uses a per-hint key ("hint_" AND Player.HintsUsed) so each
hint attempt deducts its own point rather than risking a double-deduction on a retry —
see Score Object for why named entries are the safe way to do this.
Player.HintsUsed is an auto-incrementing counter, bumped by the engine
the moment HINT fires — before either script runs — the same way
Location.VisitCount increments before OnEnter:
if Player.HintsUsed > 3 then
OutputText("(You've asked for quite a few hints already.)")
endif
When an NPC Isn't Here
Write conversation on the NPC, not on each location. An NPC's own
commands and OnTalk only run when the NPC is present, so the
player can't talk to someone who isn't there.
When the player names an NPC who is somewhere else, GoNorth answers for you, in this order:
- The NPC's
OnAbsentscript, if it has one. - An
absentoutcome for the command in the language file. - The NPC's
Whereaboutstext, if set. - "Sarah isn't here. You last saw them in the Lobby." (tracked automatically)
- "You don't see Sarah here." if the player has never met them.
Most of the time, setting Whereabouts in the NPC's own
dialogue is all you need:
NPC("Tom").Whereabouts = "Tom went to the shop for wine."
Items work the same way, but only once the player has seen or carried them
(so the reply never reveals that an item exists). An item's OnAbsent
script runs first; otherwise the player hears where they last saw it. Inside
OnAbsent, Input.Continue falls back to the built-in reply.
Cyclic Adventure Timers
A Timer is a named clock — configured on the Timers tab in Adventure
Settings — whose value cycles automatically as turns pass. TurnsPerStep is
how many turns each value is held for; CycleLength / TurnsPerStep gives the
number of distinct values in the loop. Unlike a Daemon, a Timer has no script of its own
— scripts just read Timer.Value("name") and branch on it directly.
# Timers tab: Name="DayClock", Cycle Length=24, Turns Per Step=1, Start Value=8
# -> 24 distinct values, one per turn, starting at 8 ("starts at 8am")
if Timer.Value("DayClock") >= 22 or Timer.Value("DayClock") < 6 then
OutputText("It's the dead of night.")
endif
# Name="DayPeriod", Cycle Length=24, Turns Per Step=6, Start Value=1
# -> 4 values (24/6), each held for 6 turns: morning, afternoon, evening, night
if Timer.Value("DayPeriod") = 1 then OutputText("It's morning.")
elseif Timer.Value("DayPeriod") = 2 then OutputText("It's afternoon.")
elseif Timer.Value("DayPeriod") = 3 then OutputText("It's evening.")
else OutputText("It's night.")
endif
Timer.Start("name") resumes advancing from wherever it left off,
Timer.Stop("name") pauses it (its Value stays frozen),
and Timer.Reset("name") returns it to its configured Start Value. The
Adventure Verifier warns (non-fatally) if a timer's Cycle Length doesn't divide evenly
by Turns Per Step — the engine still runs fine, it'll just hold the wrapping value
slightly longer than the others.
Topics, the Journal, and RECAP
ASK NPC ABOUT X / TELL NPC ABOUT X resolve against the target
NPC's Topics list (the Topics tab on the NPC editor) rather than the
freeform OnTalk script that plain TALK TO NPC uses. Each Topic
has a Keyword, optional Aliases, an IsVisible flag (unchecked = locked, not
yet askable), a static Response, and an optional Script. Resolution is three-tier:
- A visible Topic matches — its Response is output, then its Script
runs (if present). The very first time a given Topic is asked about, the engine also
appends an entry to the player's Journal automatically
(
"{NpcName} told you about {Keyword}.") — no author code needed for that. - No Topic matches — the NPC's own
Events["OnAsk"]catch-all script runs, if present. - Built-in fallback —
"{NpcName} doesn't seem to know anything about that."— only if neither a Topic nor anOnAskscript produced anything.
# Topics tab, keyword "the murder", aliases "killing, victim"
# Response: "The innkeeper leans in. \"Terrible business, that was.\""
# Script:
if Topic.Current.IsDiscussed then
OutputText("\"Like I told you,\" he says, \"terrible business.\"")
endif
Topic.Current.IsDiscussed reads the value from before this ask —
so the check above reads false the first time (only the Response shows) and
true on every ask after that (the Script's own line replaces the Response as
the more natural "as I told you" follow-up). Topic.Current.Keyword is the
matched Topic's own keyword, for scripts shared across several Topics via a Function.
A locked Topic (unchecked "Visible" in the editor, or set via script) is invisible to
both ASK matching and the TOPICS command until unlocked:
# Somewhere else — e.g. after the player learns the innkeeper had a daughter
NPC("Innkeeper").Topic("his daughter").IsVisible = true
NPC("name").Topic("keyword").IsVisible and
.IsDiscussed are both readable and settable the same way —
NPC("name").HasUndiscoveredTopics is a convenience bool (true if that NPC has
any visible, not-yet-discussed topic) for e.g. an idle NPC that hints
"There's something on their mind...". Player types
TOPICS NPC (or SUBJECTS NPC) to see a spoken-style list of what
they could still ask about and what they've already asked, generated automatically from
each visible Topic's IsDiscussed state — no author script needed for that
either.
The Journal itself can also be added to manually — for clues that aren't tied to a conversation Topic, e.g. finding a note:
Journal.Add("Found a bloodstained key under the floorboards.")
Players read it back with three distinct commands, each its own built-in action so an adventure can override any of them individually the same way any other built-in can be overridden via its own commands:
| Player types | Shows |
|---|---|
RECAP / JOURNAL |
every entry, oldest first |
QUICK RECAP / QUICK JOURNAL |
the last 4 entries only |
LAST ENTRY / RECAP LAST / LAST JOURNAL ENTRY |
the single most recent entry |
An empty Journal shows "Nothing to recap yet." for all three. The
in-fiction name of the journal — "journal" reads like a book; a sci-fi adventure might
want a wrist-worn "pip" device instead — is just wording, and needs no engine change:
add your own synonym to each command's VERB=[...] list via your adventure's
own commands, the same mechanism used to customise any other built-in command
(e.g. status):
# Adventure command override — adds "pip" alongside the defaults
recap - VERB=[recap|journal|pip]
quickrecap - VERB=[quick recap|quick journal|quick pip]
lastentry - VERB=[last entry|recap last|last journal entry|last pip entry]
Journal.Count reads the number of entries, for scripts that want to branch
on how much the player has learned (e.g. a late-game NPC who only opens up
if Journal.Count >= 5).
Functions
Functions let you write reusable, named blocks of code with parameters and a return value.
Unlike call (which runs a named script and shares scope), functions have
isolated local scope — all variables declared inside them are cleaned up
automatically when the function returns.
Defining a function
function.Add(A, B)
let result = A + B
return result
endfunction
- Use
function.Name(param1, param2, ...)to open the definition - Close with
endfunction return valueexits the function and sends the value back to the callerreturnwith no value returns null (treated as 0 in numeric context)- Definitions can appear anywhere in the script — they are always available
- Nested
functiondefinitions inside another function are not allowed
Calling a function
# In any expression — assign the return value
let total = function.Add(3, 4)
OutputText("Sum: " AND function.Add(10, 5))
# In a condition
if function.CanCarry(Item("Sword").Weight, Item("Sword").Size) then
OutputText("You pick it up.")
endif
# As a standalone statement (return value discarded)
function.TriggerAlarm()
# Alternate string-name syntax
let x = function("Add", 3, 4)
Variable scope and persistence
- All variables declared inside a function (including parameters) are local — they do not affect the caller's scope
- Parameters are passed by value
- Use
Global.Variable()for data that must survive the function call
function.TrackVisit(LocationName)
# Global.Variable persists; let counter is local and cleaned up on return
Global.Variable("TotalVisits") += 1
let counter = Global.Variable("TotalVisits")
return counter
endfunction
Recursion
Functions can call themselves recursively. The maximum call depth is 16 (shared with call). Exceeding this prints an error line and returns null.
Full example: combat helper
# Define functions at the top of a global script
function.RollDamage(BaseDamage)
let roll = Randomise(6)
return BaseDamage + roll
endfunction
function.EnemyIsAlive()
return Global.Variable("EnemyHP") > 0
endfunction
# Use them in a location's OnEnter script
if function.EnemyIsAlive() then
let dmg = function.RollDamage(5)
Global.Variable("EnemyHP") -= dmg
OutputText("You strike for " AND dmg AND " damage!")
endif
Probability and random numbers
# chance(n) — true n% of the time
if chance(30) then
OutputText("A bat swoops past your head!")
endif
# Randomise(n) — returns a random integer from 1 to n
let roll = Randomise(6) # simulates a dice roll
if roll > 4 then
OutputText("You land a critical hit!")
endif
# random(a,b,c) — picks one value from a list
let msg = random("The wind howls.", "Something creaks.", "Silence.")
# DiceRoll("NdM") — standard tabletop dice notation, summed
let attack = DiceRoll("2D6") + Player.Variable("Skill") # the classic Fighting Fantasy roll
let trapDamage = DiceRoll("1D6-1") # optional +/- modifier; can go to 0 or negative
let fireball = DiceRoll("2D6+1D4+3") # compound: multiple dice terms plus a flat modifier
Custom failure responses
When the player types something the game doesn't understand, GoNorth runs
Scripts/Default_Failed.script. You can override this
per-adventure by adding a default_failed script in
Adventure Settings → Global Scripts, or add a per-action
script like get_failed for when a specific action fails:
# In Adventure Settings → Global Scripts, key: "get_failed"
let r = Randomise(3)
if r = 1 then OutputText("There's nothing like that here.")
if r = 2 then OutputText("You can't pick that up.")
if r = 3 then OutputText("That's not something you can take.")
How Player Input Reaches Scripts
When a player types a command, GoNorth parses it and makes the result
available to every script through the Input object. This
unifies command matching and scripting — you no longer need to split logic
across a command file, a response template, and a separate script.
The Input object
Every script that runs during a turn can read what the player typed:
| Property | Type | Example value |
|---|---|---|
Input.Action | String | "get", "pray", "examine" |
Input.Verb | String | "take", "grab", "kneel" |
Input.Noun | String | "silver coin", "key" |
Input.NounItem.Exists | Bool | true if an item was matched |
Input.NounItem.Name | String | The matched item's name |
Input.NounItem.IsPickable | Bool | |
Input.NounItem.IsVisible | Bool | |
Input.Target | String | "priest", "chest" |
Input.TargetItem.Exists | Bool | |
Input.TargetItem.Name | String | |
Input.TargetNPC.Exists | Bool | |
Input.TargetNPC.Name | String | |
Input.TargetNPC.IsEnabled | Bool | |
Input.TargetNPC.IsAlive | Bool | |
Input.Adjective | String | "silver", "old rusty" |
Input.HasAdjective("gold") | Bool | Was this qualifier word in the input? |
Input.Raw | String | Complete unmodified input |
Input.IsAmbiguous | Bool | Multiple items matched |
Partial word matching
GoNorth uses partial word matching for items and NPCs — players don't need to type exact full names:
| Player types | Matches |
|---|---|
get key | Item named "Silver Key" ✔ |
examine rusty sword | Item named "Old Rusty Sword" ✔ |
talk to father | NPC named "Father John" ✔ |
examine earth | Item named "soil" with alias earth ✔ |
Item aliases
Each item has an Aliases field in the Item Editor (comma-separated). Any alias is treated identically to the primary name for both player input and scripts:
- Item name:
soil— Aliases:earth, dirt - Player can type examine soil, examine earth, or examine dirt — all match.
- Scripts:
Item("earth").IsPickable = falseworks just likeItem("soil").IsPickable = false.
If more than one item matches, GoNorth asks:
> get key
Which did you mean — the silver key or the gold key?
Using Input in scripts
# OnEnter script — react to how the player arrived
if Input.Action = "pray" and NPC("Priest").IsHere then
NPC("Priest").Say("The gods smile upon you, traveller.")
else
OutputText("Nothing answers your prayers.")
endif
# GlobalProcedures["get"] — economy-aware item pickup
if not Input.NounItem.Exists then
OutputText("You can't see any " AND Input.Noun AND " here.")
exit
endif
if Input.Noun = "coin" then
if Input.HasAdjective("gold") then
Global.Variable(Money) += 10
OutputText("You pocket the gold coin. (+10 gold)")
elseif Input.HasAdjective("silver") then
Global.Variable(Money) += 1
OutputText("You pocket the silver coin.")
endif
Player.GiveItem(Input.NounItem.Name)
exit
endif
Input.Continue # not a coin — let the engine handle it normally
The Handler Chain
When the player types a command, GoNorth works through a priority chain until something handles the input. Each layer can either handle the command (and stop) or pass it down to the next layer.
- Location commands — inline script attached to one of this room's commands
- Item commands — items in the room or carried
- NPC commands — NPCs present in this room
- Adventure commands — your adventure's own commands (
AdventurePatternsin the file) - GlobalProcedures["action"] — named override for a built-in action
- Built-in handler — engine default (always runs if nothing stopped it)
Input.Continue — passing control down
Any script in the chain can call Input.Continue to pass
control to the next layer. Scripts that don't call it stop the chain.
# Location command inline script — block one specific item, let engine handle the rest
if Input.NounItem.Name = "Sacred Chalice" then
OutputText("A force repels your hand.")
exit # handled — stop here
endif
Input.Continue # not the chalice — pass to engine default
Input.Redirect — change the action
Re-interpret the player's input as a completely different action:
# "push button" becomes "use button"
if Input.Action = "push" and Input.NounItem.Name = "Big Red Button" then
Input.Redirect("use")
endif
Input.Continue
Input.Override — change the matched item
Replace the item the engine matched with a different one:
Input.Override("Gold Coin") # swap the matched item
Input.Continue
Overriding a built-in action globally
Add a key to Adventure Settings → Global Procedures with the
action name (e.g. get, drop, examine).
Your script runs before the engine's default handler. Call
Input.Continue for cases you don't want to handle:
# GlobalProcedures["examine"] — custom examine that notes what you've seen
if Input.NounItem.Exists then
Global.Variable(ExamineCount) += 1
endif
Input.Continue # let the engine show the normal description
Game.NoTurn() — free commands
Normally every command the player types is a turn: daemons and timers tick, NPCs move and
the turn counter goes up. The built-in meta commands (look, inventory,
score, hint, help and so on) are free. A custom command
you add yourself, such as status or objectives, is a turn unless its
script calls Game.NoTurn(). It works in global procedures, action overrides and
location, item and NPC command scripts. Call it anywhere in the script; the command
still prints its output as usual.
# GlobalProcedures["ShowStatus"] — run by the "status" command
Game.NoTurn() # checking your objectives shouldn't cost oxygen
OutputText("Find a fuel cell and restart the reactor.")
Script Libraries
A script library (a .gnl file) holds named scripts (procedures) that GoNorth uses for built-in output, such as the room description shown by
look. GoNorth ships with a default library. You can write your own to change how
descriptions are worded and ordered, in one place, for the whole adventure, instead of
overriding commands one at a time. A library is plain text, so you can paste one into a forum
post and anyone can save it as a file.
library: Terse
language: en-GB
format: 1
# Runs when the player types LOOK
script look
call "DescribeRoom"
endscript
script DescribeRoom
if Input.Action = "look" or Location.VisitCount <= 1 then
OutputText(Location.LongDescription)
else
OutputText(Location.ShortDescription)
endif
if length(Location.VisibleItemsText) > 0 then
OutputText("You can see " AND Location.VisibleItemsText AND ".")
endif
endscript
function Plural(n, word)
if n = 1 then return word endif
return word AND "s"
endfunction
Scripts, procedures and functions
| Block | Run with | Notes |
|---|---|---|
script Name … endscript | call "Name" | No parameters or return value. Also the form for command scripts such as look. |
procedure Name … endscript | call "Name" | Same as script; the word the Designer uses for a subroutine. |
function Name(a, b) … endfunction | function.Name(x, y) | Has parameters and may return a value. A function can't be run with call. |
When a script is called by name, GoNorth looks in this order:
- The adventure's own scripts (Global Events, Global Procedures, Global Functions).
- The adventure's script library, if it has one.
- GoNorth's default library.
A library only needs the scripts you want to change. Anything it doesn't define falls back to the default.
One script for LOOK and for entering a room
The reason to keep the room description in a procedure is that you can run it from more than one
place. Put it in your library (or in Global Procedures) and call it from
On Location Enter, from a location's OnEnter, and let look use it too:
# Library: make LOOK use it
script look
call "DescribeRoom"
endscript
# Global Events → On Location Enter: the same text on entry
if not Location.Script("OnEnter").Exists then
call "DescribeRoom"
endif
A look in your Global Procedures (the Commands window's action override) works the
same way and always wins over the library. A location's own OnExamine still takes
priority over a library look.
Game.RunCommand — run LOOK from a script
Instead of calling a procedure you can run the command itself:
Game.RunCommand("look") does what the player's look does, including your
override and the library, and prints the result at that point in your script. It only runs read-only
commands (look, examine, read, listen, inventory, topics, recap) and costs no turn; anything else prints a warning
and is not run. If a look override calls Game.RunCommand("look") it gets the built-in
look, so it can add text before or after without looping.
# GlobalProcedures["look"]
OutputText("The lamplight flickers.")
Game.RunCommand("look") # the normal description follows
Standard scripts
DescribeRoom |
Prints the description, then calls the three scripts below. Long text for look and a first visit, short text on a revisit. |
DescribeItems | "You can see:" and the visible items, one per line (identical items stacked). |
DescribeNPCs | The characters the player can see, one line each. |
DescribeExits | "You can go:" and the exits. |
DescribeContents | What is inside the container in Input.NounItem. |
The built-in look stays in charge until you write a look script. Its output is
built by the same code as DescribeRoom, so switching to the library changes nothing you can see.
Spoken lists
These return a list ready to read aloud, such as "a brass key, a lamp and three coins", or an empty string if there is nothing:
Location.VisibleItemsText
Location.VisibleNPCsText
Location.ExitsText
Player.CarriedItemsText
Item("Chest").ContentsText
Loop position
Inside a foreach loop, .Index (starting at 1), .IsFirst and .IsLast let you format a list yourself:
foreach item in VisibleItems
OutputText(" " AND str(item.Index) AND ". " AND item.ShortDesc)
next
Handing a command back
A library script for a command can call Input.Continue to let GoNorth's built-in version handle it instead.
Strings — Multi-line, Inline Codes and Interpolation
Multi-line strings
Strings can span multiple lines naturally — just press Enter inside the quotes. The line breaks become part of the string:
OutputText("Welcome, {Player.Name}!
Your SKILL is {Player.Variable(Skill)}.
Your STAMINA is {Player.Variable(Stamina)}.
Type HELP for guidance.")
Inline escape codes
Short codes inside a string produce special characters. They work anywhere inside a quoted string, including multi-line strings:
| Code | Meaning | Example |
|---|---|---|
<NL> / <BR> / <CR> | New line | "Line one<NL>Line two" |
<TAB> or <T> | Tab character | "Name:<TAB>{Player.Name}" |
<PARA> | Paragraph break (double new line) | "End of scene.<PARA>New scene." |
<HR> | Horizontal rule ──────────────── | "<HR><NL>Score: {Player.Score.Total}<NL><HR>" |
<SP> | Non-breaking space | "A<SP>B" |
<Q> | Double-quote character " | "He said <Q>Run!<Q>" |
<B> / </B> | Bold text on/off | "<B>WARNING</B>: low health" |
<I> / </I> | Italic text on/off | "<I>The figure whispers...</I>" |
<s> / </s> | Silent — shown on screen but not read by TTS | "HP:<s> 45/80</s>" |
String interpolation {expression}
Put any expression inside {...} in a string and it will be
evaluated and substituted. The expression must contain a .
(member access) or ( (function call) — bare words in braces
are left as literal text:
# These ARE interpolated (contain dot or bracket):
OutputText("Welcome, {Player.Name}!")
OutputText("You rolled {Randomise(6)} on the die!")
OutputText("Gold: {Player.Variable(Gold)} Score: {Player.Score.Total}")
OutputText("{Text.Bold(Player.Name)} stands at the gates.")
# These are NOT interpolated (no dot, no bracket — literal text):
OutputText("The {old chest} creaks.") # → The {old chest} creaks.
OutputText("He said {hello}.") # → He said {hello}.
Layout object
The Layout object provides whitespace and structure values for use with AND concatenation:
| Property | Value |
|---|---|
Layout.NewLine | New line character |
Layout.Tab | Tab character |
Layout.Para | Double new line (paragraph break) |
Layout.Line | ──────────────────────────────── |
Layout.Line(width) | Horizontal rule of specified width |
Layout.Quote | A literal " character |
Layout.Space | Non-breaking space |
OutputText("He said " AND Layout.Quote AND "Run!" AND Layout.Quote)
OutputText(Layout.Line)
OutputText("Score: " AND Player.Score.Total)
OutputText(Layout.Line)
OutputText("SKILL: " AND Player.Variable(Skill) AND Layout.Tab AND
"STAMINA: " AND Player.Variable(Stamina))
Text formatting
The Text object wraps content in formatting markup for the player app to render:
| Function | Effect |
|---|---|
Text.Bold("content") | Bold text |
Text.Italic("content") | Italic text |
Text.Upper("content") | UPPERCASE (no markup — pure string transform) |
Text.Lower("content") | lowercase |
Text.Colour("content", "red") | Coloured text. Colours: red, green, blue, yellow, orange, white, grey, gold |
Text.Font("content", size) | Font size (e.g. 18) |
Text.Quote | A literal " character |
Text.DoubleQuote | Alias for Text.Quote |
OutputText(Text.Bold("WARNING: ") AND "Your Stamina is critically low!")
OutputText(Text.Colour("CRITICAL HIT!", "red"))
OutputText(Text.Bold("SKILL") AND ": " AND Player.Variable(Skill) AND
Layout.Tab AND
Text.Bold("STAMINA") AND ": " AND Player.Variable(Stamina))
# Inline with interpolation:
OutputText("{Text.Bold(Player.Name)} has fallen.")
Audio
Audio is controlled through Audio("alias") where alias is the
name you gave the file in the Media Manager. Music, Sound
and Sounds are all identical aliases for Audio — use
whichever reads most naturally.
Files must be registered in the Media Manager before use. The registered volume
is the base volume you set there; commands that take a vol% argument
override it for that call only.
| Command | Description |
|---|---|
Audio("x").Play | Play once at registered volume |
Audio("x").Play(vol%) | Play once at override volume (0–100) |
Audio("x").PlayLoop | Loop at registered volume |
Audio("x").PlayLoop(vol%) | Loop at override volume |
Audio("x").FadeIn(ms) | Start at 0, ramp to registered vol over ms |
Audio("x").FadeIn(vol%, ms) | Start at 0, ramp to vol% over ms |
Audio("x").Stop | Stop immediately |
Audio("x").FadeOut(ms) | Ramp to 0 over ms then stop |
Audio("x").Pause | Pause, preserving position |
Audio("x").Resume | Resume from pause |
Audio("x").Volume(vol%) | Set volume immediately |
Audio("x").VolumeTo(vol%, ms) | Ramp to vol% over ms |
Audio("x").Reset | Restore registered volume immediately |
Audio("x").Reset(ms) | Ramp back to registered volume over ms |
Audio("x").IsPlaying | True if currently playing (no parentheses) |
Audio.StopAll | Stop all audio immediately |
# Start background music
Audio("ForestAmbience").PlayLoop
# Fade in over 2 seconds
Audio("ForestAmbience").FadeIn(2000)
# Quiet music during dialogue, restore after
Audio("ForestAmbience").Volume(20)
NPC("Guard").Say("The password is... Moonrise.")
Audio("ForestAmbience").Reset(500)
# One-shot sound effect
Audio("SwordHit").Play
# Check before starting a looping sound
if not Audio("Rain").IsPlaying then
Audio("Rain").PlayLoop
endif
# Music is just an alias for Audio
Music("BattleTheme").FadeIn(1500)
Sounds("Footsteps").Play(50)
Inline Audio Tags
Audio commands can be embedded directly in description strings and NPC speech
using <AUDIO:alias,command> tags. Tags are stripped before
screen display and TTS — the player never sees or hears them as text.
When TTS is off, tags fire after a delay based on where they appear in the string.
OutputText("The wolf circles you, then howls.<AUDIO:WolfHowl,play> Distant wolves answer.<AUDIO:PackHowl,loop,30>")
| Tag | Equivalent |
|---|---|
<AUDIO:alias,play> | Audio("alias").Play |
<AUDIO:alias,play,60> | Audio("alias").Play(60) |
<AUDIO:alias,loop> | Audio("alias").PlayLoop |
<AUDIO:alias,loop,60> | Audio("alias").PlayLoop(60) |
<AUDIO:alias,stop> | Audio("alias").Stop |
<AUDIO:alias,pause> | Audio("alias").Pause |
<AUDIO:alias,resume> | Audio("alias").Resume |
<AUDIO:alias,fadein,500> | Audio("alias").FadeIn(500) |
<AUDIO:alias,fadein,60,500> | Audio("alias").FadeIn(60, 500) |
<AUDIO:alias,fadeout,500> | Audio("alias").FadeOut(500) |
<AUDIO:alias,vol,60> | Audio("alias").Volume(60) |
<AUDIO:alias,vol,60,500r> | Audio("alias").VolumeTo(60, 500) |
<AUDIO:alias,reset> | Audio("alias").Reset |
<AUDIO:alias,reset,500r> | Audio("alias").Reset(500) |
<AUDIO_STOP_ALL> | Audio.StopAll |
Shorthand — number as second parameter
When the second parameter is a number it is treated as a volume shorthand. If the sound is already playing, volume is adjusted rather than restarting it.
| Shorthand | Meaning |
|---|---|
<AUDIO:alias,60> | Start or adjust to 60% |
<AUDIO:alias,60,loop> | Loop at 60% |
<AUDIO:alias,60,500r> | Ramp to 60% over 500ms |
# Math
let x = min(Player.Score.Total, 100)
let y = max(Player.Variable(HitPoints), 0)
let z = abs(-42) # 42
let r = round(Player.Score.Total / 3, 2) # 2 decimal places
# String
let name = upper(Player.Name)
let title = proper("the old lighthouse. a dark place.") # "The old lighthouse. A dark place."
let len = length("hello") # 5
let has = contains(Player.Name, "Al") # true/false
Loops
Sometimes you want to run the same code several times. Use repeat:
# Ring a bell three times
repeat 3
OutputText("Clang!")
Audio("Bell").Play
endrepeat
You can also loop over every item in a location, every NPC, or every exit:
# List everything in the current room
foreach item in Items
OutputText("You see: " AND item.Name)
endforeach
# Loop over items in player's pockets
foreach item in CarriedItems
OutputText(item.Name AND " (weight: " AND item.Weight AND ")")
endforeach
Calling other scripts
You can split your logic into named scripts and call them from other scripts.
This keeps things tidy when the same behaviour is needed in multiple places.
Use call, run, or gosub — they all do the same thing:
# In an OnEnter script for many rooms:
call "CheckPlayerHealth"
call "RunAmbientSound"
GoNorth looks for the script by name — first on the current object (location, item, NPC), then in the global scripts list.
Stopping a script early
Use exit to stop the current script immediately.
Lines after exit are skipped:
# If the player is already dead, don't process the rest of this script
if Player.Variable(HitPoints) <= 0 then
GameOver("You collapse, defeated.")
exit
endif
# ... rest of the script only runs if player is alive
OutputText("You press on bravely.")
String interpolation
You can embed expressions inside text strings using {curly braces}.
The expression is evaluated and its result is inserted into the text automatically.
This works for any expression that contains a . (property access)
or ( (function call):
OutputText("Welcome, {Player.Name}!")
OutputText("You rolled {Randomise(6)} on the die.")
OutputText("Health: {Player.Variable(HitPoints)} / 100")
OutputText("{Text.Bold(Player.Name)} stands at the gates.")
Bare words in braces (no dot or bracket) are kept as-is — writing
"The {old chest}" outputs The {old chest} without any substitution.
Silent text (not read aloud)
When GoNorth is played on a device with text-to-speech, some text shouldn't be
spoken — for example, item names in a list, or visual formatting. Wrap that text
in <s>...</s> tags and it will be shown on screen but not read aloud:
OutputText("You see a <s>(shiny)</s> coin on the floor.")
# Player reads: "You see a (shiny) coin on the floor."
# TTS speaks: "You see a coin on the floor."
Voice & TTS
GoNorth supports text-to-speech narration on platforms that provide a voice engine
(Windows SAPI, Web Speech API). The TTS layer sits on top of the normal text output —
you don't need to change how you write scripts. Everything in OutputText()
is spoken automatically when TTS is enabled.
Voice Profiles
A Voice Profile is a named, abstract voice description (gender, age, locale, texture, pitch, rate, volume) defined in Adventure Settings → Voice. Profiles are matched to actual platform voices at runtime, so the same adventure works on Windows SAPI and Web Speech API without any script changes.
Assign a profile to an NPC in the NPC editor — the NPC's speech will automatically use
that voice when NPC.Say() outputs text.
Voice script object
The Voice object lets scripts control the active TTS voice mid-output:
| Call | Effect |
|---|---|
Voice.Set("ProfileName") | Switch to named profile for subsequent output this turn |
Voice.Reset() | Revert to the narrator / default voice |
Voice.Pause() | Pause any in-progress TTS speech |
Voice.Resume() | Resume paused speech |
Voice.IsEnabled | True if TTS is currently enabled (read-only boolean) |
Voice.Set("WitchVoice")
OutputText("Double, double, toil and trouble.")
Voice.Reset()
OutputText("The witch cackles and disappears.")
Inline voice tags
Use <VOICE:name>...</VOICE> directly inside an output string to
apply a voice profile to part of the text without extra script calls:
OutputText("The sign reads: <VOICE:SignVoice>DANGER — do not enter.</VOICE> You shudder.")
Silent text <s>...</s>
Text inside <s> tags is shown on screen but not spoken by TTS —
useful for stats, UI annotations, or formatting that would sound odd aloud:
OutputText("You see a <s>(shiny)</s> coin on the floor.")
# Player reads: "You see a (shiny) coin on the floor."
# TTS speaks: "You see a coin on the floor."
Player TTS meta-commands
When TTS is enabled, the player can type these commands at any time to control speech. They do not consume a game turn:
| Command | Effect |
|---|---|
repeat | Re-speak the last turn's output |
pause | Pause speech mid-sentence |
resume | Resume paused speech |
voice on | Enable TTS for this session |
voice off | Disable TTS for this session |
Note: When TTS is off, typing repeat behaves as
the normal game "redo last command" shortcut.
Script Events
Location, Item and NPC events
| Event | Object | When it runs |
|---|---|---|
OnEnter | Location | Player enters this location |
OnExit | Location | Player leaves this location |
OnTurn | Location, NPC | Every turn while in this location / NPC is present |
OnExamine | Location, Item, NPC | Player examines this object |
OnPickUp | Item | Player picks up this item. The script is in charge — call DefaultPickUp() to allow it; leave it out to refuse (examples) |
OnDrop | Item | Player drops this item — call DefaultDrop() to allow it |
OnWear | Item | Player wears this item — call DefaultWear() to allow it |
OnRemove | Item | Player takes this item off — call DefaultRemove() to allow it |
OnPutIn | Item (container) | Player puts something in this container — call DefaultPutIn() to allow it |
OnUse | Item | Player uses this item |
OnUseOn | Item | Player uses this item on something |
OnBreak | Item | Player breaks this item |
OnEat | Item | Player eats this item |
OnDrink | Item | Player drinks this item |
OnTalk | NPC | Player talks to this NPC |
OnPlayerEnter | NPC | Player enters the NPC's current location |
OnPlayerExit | NPC | Player leaves the NPC's current location |
OnGive | NPC | Player gives something to this NPC — call DefaultGive() to accept it; leave it out to refuse |
OnAttack | NPC | Player attacks this NPC |
OnLeave | NPC | This NPC's location changes — any movement mode, or a script Move(). Fires after the departure message (if any). |
OnEnter | NPC | This NPC arrives at its new location, right after OnLeave — before the player's next input, so it's the right place for an ambush. Fires after the arrival message (if any). |
Global events (GlobalEvents)
Global events live in the GlobalEvents dictionary and are managed via File → Scripts in the Designer. They fire automatically for the entire adventure:
| Event | When it runs |
|---|---|
OnGameStart | Once, when the game begins — use for intro text and Game.Ask() setup |
OnTurn | Every turn, after all location and NPC scripts have run |
OnGameEnd | When the game ends (win / lose / quit) |
OnLocationEnter | Every time the player enters any location — fires first, before the location's own OnEnter |
OnLocationEnterFinal | Every time the player enters any location — fires last, after both OnLocationEnter and the location's own OnEnter have run. Use for wrap-up logic that must see the location's own script's effects already applied. |
OnLocationExit | Every time the player leaves any location (fires after the location's own OnExit) |
OnInputError | When the player types something the engine cannot understand — use to give a custom "I don't know that" response |
OnHelp | When the player types HELP — replaces the default help text if defined. Also fires for the [HINT_SCRIPT] response template token. |
Examples
Scoring Points
Player.Score tracks named score contributions so that each action can award
points at most once. Setting Player.Score("chest") = 10 records the value under
the key "chest". Running the same line again simply replaces it with 10 again — the total
never grows no matter how many times the player repeats the action. This removes the need for a
"has the player done this yet?" guard variable.
| Expression | What it does |
|---|---|
Player.Score("key") = value | Set the named entry to value. Case-insensitive key. Replaces any previous value — never double-counts. |
Player.Score("key") | Read the current value for key (0 if not yet set). |
Player.Score.Total | The player's current total score — the sum of every named entry. |
Player.Score.Reset | Clear all entries (sets total back to 0). |
# OnUse script on the treasure chest
Player.Score("chest") = 10
OutputText("You find a handful of coins! +10 points.")
# Opening the chest again — Player.Score("chest") is still 10, total unchanged
Player.Score("chest") = 10 # no-op: value replaced with same value
# Award larger rewards for harder tasks
Player.Score("dragon") = 50
# Display running total
OutputText("Score so far: " AND Player.Score.Total)
# OnGameEnd — show a rank based on total score
let rank = "Novice"
if Player.Score.Total >= 50 then rank = "Explorer" endif
if Player.Score.Total >= 100 then rank = "Adventurer" endif
if Player.Score.Total >= 200 then rank = "Hero" endif
OutputText("Final score: " AND Player.Score.Total AND " — Rank: " AND rank)
Scoring points on first visit
# OnEnter script on a location — old style (needs a guard variable)
if Player.HasVisited(5) = false then
OutputText("You discover the ancient library. +10 points!")
endif
OutputText("The ancient library, lined with crumbling books.")
# New style — no guard needed, Player.Score handles it
Player.Score("library") = 10
OutputText("The ancient library, lined with crumbling books.")
A torch that burns out
# OnTurn script on the torch item
if Item("torch").IsCarried then
Item("torch").Variable(Fuel) -= 1
if Item("torch").Variable(Fuel) <= 0 then
Item("torch").Description = "A burnt-out torch, now useless."
Item("torch").IsPickable = false
OutputText("Your torch sputters and dies. Darkness closes in.")
endif
endif
Killing an NPC and dropping their items
# Part of an OnTalk or custom command script for George
if InputText("kill") then
NPC("George").IsAlive = false
NPC("George").Enabled = false
NPC("George").ItemDrop("sword")
NPC("George").ShortDesc = "George lies dead."
OutputText("You strike down George. He crumples to the floor, dropping his sword.")
Player.Score("defeat_george") = 5
endif
A puzzle with multiple steps
# OnUse on the lever — requires the stone to be placed first
if Location.Variable(StoneInPlace) = false then
OutputText("The lever won't budge. Something is missing.")
exit
endif
if Location.Variable(LeverPulled) = true then
OutputText("You've already pulled the lever.")
exit
endif
Location.Variable(LeverPulled) = true
Location.ExitEnabled("Down", true)
Audio("rumble").Play(90)
OutputText("The floor shudders. A staircase descends into the darkness below!")
Player.Score("lever_puzzle") = 20
NPC dialogue with state tracking
# OnTalk script — George the blacksmith
if Player.HasItem("key") then
NPC("George").Say("You already have what you need. Go!")
exit
endif
if NPC("George").Variable(KeyGiven) = false then
NPC("George").Variable(KeyGiven) = true
NPC("George").Say("Here, take this. Don't lose it.")
Player.GiveItem("key")
Location.RemoveItem("key")
Player.Score("george_gives_key") = 10
else
NPC("George").Say("I already gave you the key!")
endif
Checking multiple items at once
# HasAll — true only when player carries every listed item
if Player.HasAll("sword", "shield", "helmet") then
OutputText("You are fully armoured and ready for battle.")
endif
# HasAny — true when player carries at least one of the listed items
if Player.HasAny("torch", "lantern", "candle") then
OutputText("A faint light guides your way.")
else
OutputText("It is pitch dark. You may be eaten by a grue.")
endif
Container contents check
# OnExamine on a chest item
if Item("chest").Contents.HasItem("gold coin") then
OutputText("Inside the chest: a gleaming gold coin.")
else
OutputText("The chest is empty.")
endif
Creating a new item at runtime
Item.Create(name, shortDesc, longDesc, isPickable) makes a brand-new item and adds
it to the adventure. It returns the item's actual name as a string — if the
requested name collides with an existing item, the engine appends " (2)",
" (3)" and so on until it finds one that's free, so always capture the return
value with let rather than assuming the literal string you passed in comes back
unchanged. A freshly created item isn't placed anywhere yet — it exists in the adventure but
isn't in any location, NPC, or the player's inventory until you explicitly place it with
Location.AddItem, Player.GiveItem, or NPC("x").GiveItem.
Always place it before the script ends.
# OnUse on the "torch" — a burnt-out torch can be relit into a fresh one
let freshTorch = Item.Create("Torch", "a blazing torch", "A torch, freshly lit and burning bright.", true)
Item("torch").Destroy()
Player.GiveItem(freshTorch)
OutputText("You strike a new torch. Light floods the passage.")
Combining two items into a new one uses the same two building blocks — there's no dedicated
"combine" verb built into the engine. You add your own command
(e.g. combine NOUN with TARGET) the same way any two-object command works, and
the outcome script creates the result and destroys the ingredients:
# "combine key with gem" — succeed script
let fused = Item.Create("Fused Key-Gem", "a key fused with a glowing gem", "A rusty key, now fused to a faintly glowing gem.", true)
Item("key").Destroy()
Item("gem").Destroy()
Player.GiveItem(fused)
OutputText("The key and the gem fuse together with a soft hum.")
Creating a new NPC at runtime
NPC.Create(name, shortDesc, longDesc, locationId) makes a brand-new NPC and places
it directly at locationId — unlike items, an NPC always needs a starting place, so
both NPC.CurrentLocationId and the destination location's NPC list are wired in
one call. Like Item.Create, it returns the NPC's actual (possibly disambiguated)
name — capture it with let. Once created, move it around normally with
NPC("x").Move(id), and remove it entirely with NPC("x").Destroy().
# OnUse on a summoning circle — conjures a hostile spirit into the current room
let spirit = NPC.Create("Restless Spirit", "a pale, flickering shape", "A restless spirit, bound here by the circle you just disturbed.", Location.Id)
NPC(spirit).Say("Who... disturbs... my rest?")
OutputText("The air grows cold. A spirit rises from the circle!")
# Later — the spirit is banished for good
if InputText("banish") then
NPC("Restless Spirit").Destroy()
OutputText("The spirit shrieks and dissolves into mist.")
endif
NPC reacting when player enters the room
# OnPlayerEnter script on an NPC — fires after room description
if NPC("Guard").Variable(AlertedPlayer) = false then
NPC("Guard").Variable(AlertedPlayer) = true
NPC("Guard").Say("Halt! Who goes there?")
endif
NPC patrols and movement
NPCs with the Random From List movement mode walk around the game world on their own — no script required for basic patrolling. Instead of ping-ponging randomly, they use directional momentum: they tend to keep going the way they were heading, occasionally turn, and rarely double back. This makes them feel like they actually have somewhere to be.
To set up a patrol, open the NPC's properties and:
- Set Movement Mode to Random From List.
- Add the location IDs the NPC is allowed to visit in the Movement Locations list.
That's it — the engine takes care of the rest each turn. The NPC will only move through exits that connect to one of its permitted locations, so it stays within the area you've defined. If every exit to a permitted location is currently blocked, the NPC simply waits.
Changing a patrol territory at runtime
You can shrink, expand, or completely change where an NPC is allowed to go using scripts. A common use is a guard who covers a different area at night:
# In a Daemon or OnTurn script — change the guard's patrol at nightfall
if Global.Variable(TimeOfDay) = "Night" then
NPC("Guard").Locations = "1,2,3,4" # night patrol area
else
NPC("Guard").Locations = "14,21,18,16" # day patrol area
endif
Setting Locations replaces the entire permitted list and also resets the
NPC's directional memory, so the first move into the new area is a fresh start.
Adding or removing individual locations
If you only need to add or remove one location — for example, unlocking a gate that lets
an NPC into a new area — use AddLocation and RemoveLocation:
# When the player opens the east gate:
NPC("Merchant").AddLocation(22) # the market square is now accessible
# When the bridge collapses:
NPC("Thief").RemoveLocation(8) # the thief can no longer cross
Stopping an NPC from moving
To freeze an NPC in place temporarily — perhaps during a cutscene — set its Movement Mode to Stationary. The permitted-location list stays intact, so switching back to Random From List immediately resumes the patrol:
# Freeze the merchant during a cutscene
NPC("Merchant").MovementMode = 0 # 0 = Stationary
# Resume patrol when the cutscene ends (Locations list unchanged)
NPC("Merchant").MovementMode = 1 # 1 = Random From List
To stop an NPC permanently until further notice, clear its location list instead:
# Prisoner locked in — clear movement entirely
NPC("Prisoner").ClearLocations
A simpler alternative that works regardless of movement mode (and doesn't disturb whatever
mode/route/weights are already configured) is IsStatic: while true, the NPC
never moves under any mode. IsAlive = false has the same effect — a
dead NPC never moves itself, however it's configured:
# Freeze without touching the movement mode itself
NPC("Merchant").IsStatic = true
...
NPC("Merchant").IsStatic = false # resumes exactly where it left off
Weighted Random and Patrol Route (teleport-style)
Unlike Random From List/Wander, these two modes ignore map adjacency entirely — the NPC jumps straight to the chosen location each turn, so list locations that make narrative sense together (the engine won't check that they're connected by an exit).
# Weighted Random — configured via the Movement tab's "Location Weights" box,
# format "id:weight, id:weight, ...". 0 = forbidden, unlisted = weight 1.
# e.g. "3:8, 5:3, 7:0" — location 3 is frequent, 5 occasional, 7 never visited.
# Patrol Route — an ordered, cycling list configured via the Movement tab's
# "Patrol Route" box, e.g. "1, 5, 7, 15" — advances one waypoint per turn,
# wrapping back to the start. The current position (PatrolIndex) is saved
# with the game, so a guard resumes mid-patrol after loading a save.
# Switch a patrolling guard into pursuit mode, then back again:
if Global.Variable(AlarmRaised) = true then
NPC("Guard").MovementMode = "WeightedRandom"
else
NPC("Guard").MovementMode = "PatrolRoute" # restarts the route from waypoint 0
endif
Departure & arrival messages, and an ambush example
Whenever an NPC's location changes — any movement mode, or an explicit
NPC("x").Move(id) — the engine outputs LeaveMessage then fires
OnLeave, then outputs EnterMessage and fires OnEnter.
Both messages default to "{NpcName} leaves."/"{NpcName} enters.";
clear them (in the Movement tab, or via script) for silent movement — the events still fire.
OnEnter runs before the player can type anything, making it the right place for
an ambush. Set the message once, before the move — not inside OnEnter itself,
since that move's message has already been output by the time OnEnter runs:
# NPC "Gollum", MovementMode = Scripted — OnTurn or MovementScript:
if not Player.HasItem("ring of power") and not NPC("Gollum").IsHere then
NPC("Gollum").EnterMessage = "An angry Gollum enters!"
NPC("Gollum").Move(Location.Id("Cave"))
endif
# NPC "Gollum" — OnEnter script (fires immediately after the move above):
if NPC("Gollum").IsHere then
NPC("Gollum").Say("We hatesss it!")
# ...attack logic here
endif
Reading the patrol territory in a script
You can read the current permitted-location list as a comma-separated string. This is mainly useful for debugging or displaying information to the player:
let territory = NPC("Scout").Locations
OutputText("The scout's patrol covers location IDs: " AND territory)
OnGameStart with player name
Player.Name = Global.Ask("What is your name?")
OutputText("Welcome to the adventure, " AND Player.Name AND ".")
OutputText("Type HELP if you need guidance. Good luck!")
OnGameEnd score display
OutputText("Game over, " AND Player.Name AND ".")
let grade = "Novice"
if Player.Score.Total > 49 then grade = "Explorer" endif
if Player.Score.Total > 99 then grade = "Adventurer" endif
if Player.Score.Total > 199 then grade = "Hero" endif
OutputText("Final score: " AND Player.Score.Total AND " — Rank: " AND grade)
NPC and Item variables
# Read or write a variable on an NPC
NPC("George").Variable(Damage) = 5
if NPC("George").Variable(GreetingGiven) = false then
NPC("George").Variable(GreetingGiven) = true
NPC("George").Say("Well met, traveller!")
endif
# Read or write a variable on an Item
Item("torch").Variable(Fuel) = 20
Item("torch").Variable(Fuel) -= 1
if Item("tome").Variable(Read) = false then
Item("tome").Variable(Read) = true
OutputText("You read the tome carefully.")
endif
String escape sequences
Inside quoted strings you can use backslash escapes:
| Escape | Meaning |
|---|---|
\" | A literal quote character |
\n | New line |
\t | Tab |
\\ | A literal backslash |
NPC("Guard").Say("He growled, \"Halt!\"")
OutputText("Line one\nLine two\nLine three")
OutputText("") # blank line — useful for spacing
🧑 Player, 📍 Location etc.) lets you click to insert
any API call at the cursor position, so you don't have to remember exact syntax.