BlueGit

timfa questward

Files

questward / docs / SCRIPTS.md

SCRIPTS.md

SCRIPTS.md 12.9 KiB Download Raw

Player scripts (AFK / offline)

Status: not implemented (design only) Related: tile_mmo_server_technical_design_v0.6.md §18 (controller abstraction, offline entity, sandbox rules)

Scripts are a sandboxed language interpreted on the server. They never mutate world state directly; they emit the same player intents as a human client (moveTo, gather, craft, attack, shop, equip, …). The server validates every step.

This document is the product + language spec for implementation.

---

1. Goals

  • Automate simple loops: gather → bank/craft → fight → recover.
  • Run while online (watch + stop bar), while AFK (idle 5+ minutes), or while offline (character stays in the world, max 1 hour).
  • Keep the language small, readable, and hard to misuse.
  • Fail loudly: toast (online) or pigeon letter (offline), with line + operation + reason.

---

2. Player UI

2.1 Scripts button

  • HUD control Scripts opens the Scripts panel.
  • Panel lists the player’s saved scripts (name + badges for Offline / AFK flags).
  • Actions per script: Edit, Delete, Run (online).
  • New script creates an empty script and opens the editor.

2.2 Script editor

  • Name field.
  • Text area with syntax highlighting (keywords, strings, numbers, comments, labels).
  • Flags (mutually independent; at most one script should be marked for each role — marking one clears that flag on others):
  • Run this while offline — eligible on logout confirmation.
  • Run while AFK — auto-starts after 5 minutes with no player actions.
  • Save / Cancel.

2.3 Online run bar

When a script is running (started manually, AFK auto-start, or resumed after re-login onto an offline script):

  • Fixed bar at the bottom of the screen.
  • Shows: script name, current line (number + source text), Stop.
  • Manual player intents (move, attack, gather, …) stop the script (treat as cancel), except pure camera/UI (open bag, zoom, settings).

2.4 Logout confirmation

On logout while in the world:

1. Modal: Are you sure you want to log out?

  • No — stay.
  • Yes — log out.
  • Checkbox (default unchecked): Run offline script
  • Enabled only if the player has a script marked Run this while offline.

2. If the checkbox is checked, show an extra red line: Running a script means your character remains in the world and can still be attacked! 3. Confirming with the checkbox checked starts/continues the offline script on that character (see §4).

---

3. Modes

ModeHow it startsCharacter in worldClient
OnlineScripts panel → RunYesConnected; run bar visible
AFKNo gameplay intents for 5 minutes, and an AFK-marked script existsYesStill connected; run bar appears when script starts
OfflineLogout with offline checkboxYes (no NetworkIdentity; keeps ChunkLoader)Disconnected

AFK timer: reset on any gameplay intent sent by the player (move, attack, gather, craft, shop, equip, cast, pickup, talk, …). Opening UI / scrolling chat does not reset AFK if those are not intents; prefer resetting on any outbound play command for simplicity.

Offline duration: max 1 hour from offline-script start (or remaining time after restart rehydrate). Then: stop script, despawn character, persist as a normal logout.

Re-login during offline script: attach the client to the existing entity; keep the script running; show the run bar so the player can Stop.

---

4. Errors

4.1 Message shape

Always:

Line <n>: <operation> — <reason>

Example:

Line 12: mine — No reachable iron ore nearby.

4.2 Online / AFK (client connected)

  • Stop the script.
  • Show a persistent toast (stays until the player dismisses it) with the error message.

4.3 Offline (no client)

  • Stop the script.
  • Remove the character from the world (normal offline persist).
  • Queue a pigeon letter:
  • Author display name: Frederick
  • Role flavour: manager of Idle Gaming (author line / signature as other system letters do)
  • Body:

Unfortunately, your script encountered an error. then a blank line, then the error message from §4.1.

---

5. Language overview

  • Line-oriented, case-insensitive keywords.
  • One statement per line (blank lines and comments allowed).
  • Comments: # ... to end of line.
  • Strings: "double quotes" (names of blocks, mobs, items). Matching is case-insensitive display-name match unless noted.
  • Numbers: integers (10, 100).
  • Labels: label name_here — name is letters, digits, underscore.
  • No variables in v1 except implicit targets (current block / mob / ground item) and loop counters internal to for / while.
  • No user-defined functions in v1.
  • Sandbox: not JavaScript; custom interpreter only (§18.7 design doc).

5.1 Implicit targets

The script keeps three optional targets (cleared when a new target of that kind is set, or on error/stop):

TargetSet byUsed by
Blockfind block "..."go, mine, chop, harvest, craft, in range block
Mobfind mob "..."go, attack, buy, sell, in range mob
Groundfind ground "..."go, take, use, in range ground

go without a kind uses the most recently set target. Prefer explicit forms when ambiguous: go block, go mob, go ground.

---

6. Statements (v1)

6.1 Targeting

StatementMeaning
find block "Iron ore"Closest reachable block whose display name matches. Sets block target. Fails if none.
find mob "Shopkeeper"Closest living mob/NPC whose name matches. Sets mob target. Fails if none.
find ground "Log"Closest ground item whose display name matches. Sets ground target. Fails if none.

“Closest” = Chebyshev distance from the player, then path-reachable. Unreachable candidates are skipped.

6.2 Movement

StatementMeaning
goPath to the last set target (block / mob / ground). Waits until arrived or fails (blocked / lost).
go block / go mob / go groundSame, explicit target kind.
run on / run offToggle run gait (same rules as player: needs stamina).

Arrival = standing on the tile (ground item / interactable) or adjacent where the game requires adjacency (stations, melee, gather nodes).

6.3 Gathering & world interact

StatementMeaning
mineGather/mine the targeted block (ore boulder, etc.). Waits for finish or fails.
chopFell the targeted tree block.
harvestPick/harvest the targeted plant/herb/flower/cotton block.
takePick up the targeted ground item into the bag.
useInteract with the targeted ground item if it has a use (e.g. light a log).

Exact gather verb must match what the block supports; wrong verb → error (chop — That is not a tree.).

6.4 Crafting

StatementMeaning
craft "Bronze bar"At the targeted crafting block (station), try to craft one of that recipe output (or recipe display name). Fails if not at station, recipe unknown, missing mats, or skill too low.
can craft "Bronze bar"Does not craft. Used only inside if (see §6.9). True if the targeted station can craft it right now with current bag + skills.

6.5 Combat & shops

StatementMeaning
attackAttack the targeted mob (same as player Attack intent). Does not wait for kill; continues next line. Optional later: wait until dead — not in v1.
buy "Feather" 10Buy quantity from targeted shop mob. Fails if no shop, not in range, can’t afford, or not stocked.
sell "Soft leather" 5Sell quantity to targeted shop mob (if it buys).

6.6 Inventory & vitals

StatementMeaning
equip "Bronze pickaxe"Equip a matching item from the bag into its proper slot. Fails if missing or not equippable.
if health below 30 …See control flow.
if stamina below 5 …See control flow.

6.7 Range checks

StatementMeaning
if in range block "Furnace"True if a matching block exists within interaction/path range (same rules as find + adjacent/interact).
if in range mob "Deer"True if a matching living mob is within a small radius (e.g. combat/script range, document as 15 tiles Chebyshev).
if in range ground "Bones"True if a matching ground item is within 15 tiles.
if in range item "Bronze bar"True if the bag contains that item (any quantity ≥ 1).

6.8 Labels & jumps

StatementMeaning
label campDeclare label camp.
goto campJump to that label.

Forward and backward jumps allowed. Jumping into/out of loops is disallowed in v1 (error if attempted).

6.9 Control flow

if health below 30
  goto heal
end

if stamina below 5
  run off
end

if can craft "Bronze bar"
  craft "Bronze bar"
end

if in range item "Bronze pickaxe"
  equip "Bronze pickaxe"
end

for 10
  find block "Tin ore"
  go block
  mine
end

while in range mob "Rat"
  find mob "Rat"
  go mob
  attack
end

Rules:

  • Blocks end with end.
  • if body runs when the condition is true; no else in v1 (use a second if / goto).
  • for N — repeat body N times (N ≥ 1, max 1000).
  • while <condition> — repeat while condition true; max 1000 iterations per while then error (while — Too many repeats.).
  • Conditions for while / if:

health below N · stamina below N · can craft "..." · in range block|mob|ground|item "..."

6.10 Utility

StatementMeaning
wait 2Pause 2 seconds (server time). Max 60 per wait.
stopEnd the script successfully (no error letter).

---

7. Example script

# Tin loop with panic flee
label start
equip "Bronze pickaxe"
run on

for 20
  if health below 25
    goto flee
  end
  find block "Tin ore"
  go block
  mine
  if in range ground "Tin ore"
    find ground "Tin ore"
    go ground
    take
  end
end
stop

label flee
run on
find mob "Town Guard"
go mob
stop

---

8. Syntax highlighting (editor)

Highlight at least:

ClassExamples
Keywordfind, go, mine, chop, harvest, craft, attack, buy, sell, equip, label, goto, if, end, for, while, wait, stop, run, take, use, can
Subkeywordblock, mob, ground, item, health, stamina, below, in, range, on, off, craft (in can craft)
String"..."
Number10, 30
Comment# ...
Label nameafter label / goto

Invalid lines can be marked with a subtle error underline on Save (optional v1).

---

9. Persistence & limits

  • Scripts stored per character in state DB (name, source text, flags, updatedAt).
  • Soft caps (suggested): 20 scripts / character, 200 lines / script, 4 KB source.
  • Offline script runtime state: program counter, targets, loop stack, offlineUntil timestamp — rehydrated on server restart (§18.6).
  • Instruction budget: small per simulation tick (e.g. advance at most one blocking wait/path/gather at a time; non-blocking lines burst with a low cap).

---

10. Authority & safety (implementation notes)

  • Interpreter runs only on the server.
  • Every gameplay effect goes through existing command handlers.
  • No filesystem, network, eval, or shared mutable globals across characters.
  • Name matching uses the same display names players see in tooltips / shops.
  • Script controller and client controller: only one produces intents at a time; starting a script disables manual gameplay intents until Stop (or manual intent cancels script — pick one policy and stick to it; recommended: any manual gameplay intent stops the script).

---

11. Implementation plan (phased)

1. Data + UI shell — CRUD scripts, flags, editor with highlighting, no execution. 2. Online runner — interpreter + run bar + stop; subset: find / go / wait / label / goto / stop. 3. Gather + equip + vitals if — mine / chop / harvest / equip / if health|stamina. 4. Combat + shops + craft — attack / buy / sell / craft / can craft. 5. Loops + range checks — for / while / in range *. 6. AFK auto-start — 5-minute idle. 7. Offline logout flow — modal, entity retention, 1-hour cap, re-login attach, error pigeon.

---

12. Open choices (resolve during implementation)

  • Exact radius for in range mob/ground (proposed 15).
  • Whether attack should block until the mob dies (v1: no).
  • Whether opening the Scripts panel resets the AFK timer (proposed: no, only gameplay intents).
  • Display-name collisions (multiple “Humanoid”): always closest wins.
Source
1# Player scripts (AFK / offline)
2
3**Status:** not implemented (design only)
4**Related:** `tile_mmo_server_technical_design_v0.6.md` §18 (controller abstraction, offline entity, sandbox rules)
5
6Scripts are a **sandboxed language** interpreted on the **server**. They never mutate world state directly; they emit the same player **intents** as a human client (`moveTo`, gather, craft, attack, shop, equip, …). The server validates every step.
7
8This document is the product + language spec for implementation.
9
10---
11
12## 1. Goals
13
14- Automate simple loops: gather → bank/craft → fight → recover.
15- Run **while online** (watch + stop bar), **while AFK** (idle 5+ minutes), or **while offline** (character stays in the world, max 1 hour).
16- Keep the language **small**, readable, and hard to misuse.
17- Fail loudly: toast (online) or pigeon letter (offline), with line + operation + reason.
18
19---
20
21## 2. Player UI
22
23### 2.1 Scripts button
24
25- HUD control **Scripts** opens the Scripts panel.
26- Panel lists the player’s saved scripts (name + badges for Offline / AFK flags).
27- Actions per script: **Edit**, **Delete**, **Run** (online).
28- **New script** creates an empty script and opens the editor.
29
30### 2.2 Script editor
31
32- Name field.
33- Text area with **syntax highlighting** (keywords, strings, numbers, comments, labels).
34- Flags (mutually independent; at most one script should be marked for each role — marking one clears that flag on others):
35 - **Run this while offline** — eligible on logout confirmation.
36 - **Run while AFK** — auto-starts after 5 minutes with no player actions.
37- **Save** / **Cancel**.
38
39### 2.3 Online run bar
40
41When a script is running (started manually, AFK auto-start, or resumed after re-login onto an offline script):
42
43- Fixed bar at the **bottom** of the screen.
44- Shows: script name, **current line** (number + source text), **Stop**.
45- Manual player intents (move, attack, gather, …) **stop** the script (treat as cancel), except pure camera/UI (open bag, zoom, settings).
46
47### 2.4 Logout confirmation
48
49On logout while in the world:
50
511. Modal: **Are you sure you want to log out?**
52 - **No** — stay.
53 - **Yes** — log out.
54 - Checkbox (default **unchecked**): **Run offline script**
55 - Enabled only if the player has a script marked **Run this while offline**.
562. If the checkbox is checked, show an extra **red** line:
57 **Running a script means your character remains in the world and can still be attacked!**
583. Confirming with the checkbox checked starts/continues the offline script on that character (see §4).
59
60---
61
62## 3. Modes
63
64| Mode | How it starts | Character in world | Client |
65|------|---------------|--------------------|--------|
66| **Online** | Scripts panel → Run | Yes | Connected; run bar visible |
67| **AFK** | No gameplay intents for **5 minutes**, and an AFK-marked script exists | Yes | Still connected; run bar appears when script starts |
68| **Offline** | Logout with offline checkbox | Yes (no NetworkIdentity; keeps ChunkLoader) | Disconnected |
69
70**AFK timer:** reset on any **gameplay intent** sent by the player (move, attack, gather, craft, shop, equip, cast, pickup, talk, …). Opening UI / scrolling chat does not reset AFK if those are not intents; prefer resetting on any outbound play command for simplicity.
71
72**Offline duration:** max **1 hour** from offline-script start (or remaining time after restart rehydrate). Then: stop script, despawn character, persist as a normal logout.
73
74**Re-login during offline script:** attach the client to the existing entity; keep the script running; show the run bar so the player can Stop.
75
76---
77
78## 4. Errors
79
80### 4.1 Message shape
81
82Always:
83
84```text
85Line <n>: <operation> — <reason>
86```
87
88Example:
89
90```text
91Line 12: mine — No reachable iron ore nearby.
92```
93
94### 4.2 Online / AFK (client connected)
95
96- Stop the script.
97- Show a **persistent toast** (stays until the player dismisses it) with the error message.
98
99### 4.3 Offline (no client)
100
101- Stop the script.
102- Remove the character from the world (normal offline persist).
103- Queue a **pigeon letter**:
104 - Author display name: **Frederick**
105 - Role flavour: manager of Idle Gaming (author line / signature as other system letters do)
106 - Body:
107 `Unfortunately, your script encountered an error.`
108 then a blank line, then the error message from §4.1.
109
110---
111
112## 5. Language overview
113
114- Line-oriented, case-insensitive **keywords**.
115- One statement per line (blank lines and comments allowed).
116- Comments: `# ...` to end of line.
117- Strings: `"double quotes"` (names of blocks, mobs, items). Matching is **case-insensitive** display-name match unless noted.
118- Numbers: integers (`10`, `100`).
119- Labels: `label name_here` — name is letters, digits, underscore.
120- No variables in v1 except **implicit targets** (current block / mob / ground item) and loop counters internal to `for` / `while`.
121- No user-defined functions in v1.
122- Sandbox: **not** JavaScript; custom interpreter only (§18.7 design doc).
123
124### 5.1 Implicit targets
125
126The script keeps three optional targets (cleared when a new target of that kind is set, or on error/stop):
127
128| Target | Set by | Used by |
129|--------|--------|---------|
130| **Block** | `find block "..."` | `go`, `mine`, `chop`, `harvest`, `craft`, `in range block` |
131| **Mob** | `find mob "..."` | `go`, `attack`, `buy`, `sell`, `in range mob` |
132| **Ground** | `find ground "..."` | `go`, `take`, `use`, `in range ground` |
133
134`go` without a kind uses the **most recently set** target. Prefer explicit forms when ambiguous: `go block`, `go mob`, `go ground`.
135
136---
137
138## 6. Statements (v1)
139
140### 6.1 Targeting
141
142| Statement | Meaning |
143|-----------|---------|
144| `find block "Iron ore"` | Closest **reachable** block whose display name matches. Sets block target. Fails if none. |
145| `find mob "Shopkeeper"` | Closest living mob/NPC whose name matches. Sets mob target. Fails if none. |
146| `find ground "Log"` | Closest ground item whose display name matches. Sets ground target. Fails if none. |
147
148“Closest” = Chebyshev distance from the player, then path-reachable. Unreachable candidates are skipped.
149
150### 6.2 Movement
151
152| Statement | Meaning |
153|-----------|---------|
154| `go` | Path to the last set target (block / mob / ground). Waits until arrived or fails (blocked / lost). |
155| `go block` / `go mob` / `go ground` | Same, explicit target kind. |
156| `run on` / `run off` | Toggle run gait (same rules as player: needs stamina). |
157
158Arrival = standing on the tile (ground item / interactable) or adjacent where the game requires adjacency (stations, melee, gather nodes).
159
160### 6.3 Gathering & world interact
161
162| Statement | Meaning |
163|-----------|---------|
164| `mine` | Gather/mine the targeted **block** (ore boulder, etc.). Waits for finish or fails. |
165| `chop` | Fell the targeted tree block. |
166| `harvest` | Pick/harvest the targeted plant/herb/flower/cotton block. |
167| `take` | Pick up the targeted **ground** item into the bag. |
168| `use` | Interact with the targeted **ground** item if it has a use (e.g. light a log). |
169
170Exact gather verb must match what the block supports; wrong verb → error (`chop — That is not a tree.`).
171
172### 6.4 Crafting
173
174| Statement | Meaning |
175|-----------|---------|
176| `craft "Bronze bar"` | At the targeted crafting **block** (station), try to craft one of that recipe output (or recipe display name). Fails if not at station, recipe unknown, missing mats, or skill too low. |
177| `can craft "Bronze bar"` | Does **not** craft. Used only inside `if` (see §6.9). True if the targeted station can craft it **right now** with current bag + skills. |
178
179### 6.5 Combat & shops
180
181| Statement | Meaning |
182|-----------|---------|
183| `attack` | Attack the targeted mob (same as player Attack intent). Does not wait for kill; continues next line. Optional later: `wait until dead` — **not in v1**. |
184| `buy "Feather" 10` | Buy quantity from targeted shop mob. Fails if no shop, not in range, can’t afford, or not stocked. |
185| `sell "Soft leather" 5` | Sell quantity to targeted shop mob (if it buys). |
186
187### 6.6 Inventory & vitals
188
189| Statement | Meaning |
190|-----------|---------|
191| `equip "Bronze pickaxe"` | Equip a matching item from the bag into its proper slot. Fails if missing or not equippable. |
192| `if health below 30` … | See control flow. |
193| `if stamina below 5` … | See control flow. |
194
195### 6.7 Range checks
196
197| Statement | Meaning |
198|-----------|---------|
199| `if in range block "Furnace"` | True if a matching block exists within interaction/path range (same rules as find + adjacent/interact). |
200| `if in range mob "Deer"` | True if a matching living mob is within a small radius (e.g. combat/script range, document as **15 tiles** Chebyshev). |
201| `if in range ground "Bones"` | True if a matching ground item is within **15 tiles**. |
202| `if in range item "Bronze bar"` | True if the bag contains that item (any quantity ≥ 1). |
203
204### 6.8 Labels & jumps
205
206| Statement | Meaning |
207|-----------|---------|
208| `label camp` | Declare label `camp`. |
209| `goto camp` | Jump to that label. |
210
211Forward and backward jumps allowed. Jumping into/out of loops is **disallowed** in v1 (error if attempted).
212
213### 6.9 Control flow
214
215```text
216if health below 30
217 goto heal
218end
219
220if stamina below 5
221 run off
222end
223
224if can craft "Bronze bar"
225 craft "Bronze bar"
226end
227
228if in range item "Bronze pickaxe"
229 equip "Bronze pickaxe"
230end
231
232for 10
233 find block "Tin ore"
234 go block
235 mine
236end
237
238while in range mob "Rat"
239 find mob "Rat"
240 go mob
241 attack
242end
243```
244
245Rules:
246
247- Blocks end with `end`.
248- `if` body runs when the condition is true; no `else` in v1 (use a second `if` / `goto`).
249- `for N` — repeat body **N** times (N ≥ 1, max **1000**).
250- `while <condition>` — repeat while condition true; **max 1000** iterations per `while` then error (`while — Too many repeats.`).
251- Conditions for `while` / `if`:
252 `health below N` · `stamina below N` · `can craft "..."` · `in range block|mob|ground|item "..."`
253
254### 6.10 Utility
255
256| Statement | Meaning |
257|-----------|---------|
258| `wait 2` | Pause **2 seconds** (server time). Max **60** per wait. |
259| `stop` | End the script successfully (no error letter). |
260
261---
262
263## 7. Example script
264
265```text
266# Tin loop with panic flee
267label start
268equip "Bronze pickaxe"
269run on
270
271for 20
272 if health below 25
273 goto flee
274 end
275 find block "Tin ore"
276 go block
277 mine
278 if in range ground "Tin ore"
279 find ground "Tin ore"
280 go ground
281 take
282 end
283end
284stop
285
286label flee
287run on
288find mob "Town Guard"
289go mob
290stop
291```
292
293---
294
295## 8. Syntax highlighting (editor)
296
297Highlight at least:
298
299| Class | Examples |
300|-------|----------|
301| Keyword | `find`, `go`, `mine`, `chop`, `harvest`, `craft`, `attack`, `buy`, `sell`, `equip`, `label`, `goto`, `if`, `end`, `for`, `while`, `wait`, `stop`, `run`, `take`, `use`, `can` |
302| Subkeyword | `block`, `mob`, `ground`, `item`, `health`, `stamina`, `below`, `in`, `range`, `on`, `off`, `craft` (in `can craft`) |
303| String | `"..."` |
304| Number | `10`, `30` |
305| Comment | `# ...` |
306| Label name | after `label` / `goto` |
307
308Invalid lines can be marked with a subtle error underline on Save (optional v1).
309
310---
311
312## 9. Persistence & limits
313
314- Scripts stored per character in state DB (name, source text, flags, updatedAt).
315- Soft caps (suggested): **20** scripts / character, **200** lines / script, **4 KB** source.
316- Offline script runtime state: program counter, targets, loop stack, `offlineUntil` timestamp — rehydrated on server restart (§18.6).
317- Instruction budget: small per simulation tick (e.g. advance at most one **blocking** wait/path/gather at a time; non-blocking lines burst with a low cap).
318
319---
320
321## 10. Authority & safety (implementation notes)
322
323- Interpreter runs only on the server.
324- Every gameplay effect goes through existing command handlers.
325- No filesystem, network, `eval`, or shared mutable globals across characters.
326- Name matching uses the same display names players see in tooltips / shops.
327- Script controller and client controller: only one produces intents at a time; starting a script disables manual gameplay intents until Stop (or manual intent cancels script — pick one policy and stick to it; **recommended:** any manual gameplay intent **stops** the script).
328
329---
330
331## 11. Implementation plan (phased)
332
3331. **Data + UI shell** — CRUD scripts, flags, editor with highlighting, no execution.
3342. **Online runner** — interpreter + run bar + stop; subset: `find` / `go` / `wait` / `label` / `goto` / `stop`.
3353. **Gather + equip + vitals if** — `mine` / `chop` / `harvest` / `equip` / `if health|stamina`.
3364. **Combat + shops + craft** — `attack` / `buy` / `sell` / `craft` / `can craft`.
3375. **Loops + range checks** — `for` / `while` / `in range *`.
3386. **AFK auto-start** — 5-minute idle.
3397. **Offline logout flow** — modal, entity retention, 1-hour cap, re-login attach, error pigeon.
340
341---
342
343## 12. Open choices (resolve during implementation)
344
345- Exact radius for `in range mob/ground` (proposed **15**).
346- Whether `attack` should block until the mob dies (v1: **no**).
347- Whether opening the Scripts panel resets the AFK timer (proposed: **no**, only gameplay intents).
348- Display-name collisions (multiple “Humanoid”): always **closest** wins.