Document player AFK/offline scripting language and UI.
Add docs/SCRIPTS.md with modes, logout modal, statement list, control flow, errors, highlighting, and a phased plan. Point FEATURES.md at the new spec.
@@ -350,8 +350,8 @@ Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3
350
350
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free; closing the UI or walking away from that counter releases the clerk so wander resumes, unless another player is still using the same staff station. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
351
351
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
352
352
353
## Player scripting hooks
353
## Player scripting (AFK / offline)
354
354
355
355
**Status:** not implemented
356
**Spec:** Reserved control abstraction; not in the initial release.
357
**Code:** —
356
**Spec:** Full language + UI + online/AFK/offline behaviour is documented in [`docs/SCRIPTS.md`](SCRIPTS.md). Scripts are a sandboxed, server-interpreted language that emits normal player intents. Players manage scripts in a Scripts panel (create/edit/delete, Run, Offline/AFK flags), see a bottom run bar while a script executes, confirm logout with an optional offline-script checkbox and danger line, auto-start an AFK script after 5 minutes idle, and get persistent toast or Frederick (Idle Gaming) pigeon letters on errors. Offline scripts keep the character in the world up to 1 hour; re-login attaches to the same instance. Architecture hooks remain in design doc §18.
357
**Code:** — (planned: `shared/scripts/`, `server/src/scripts/`, `client/src/play/scripts.js`, state DB script rows)
@@ -350,8 +350,8 @@ Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3350
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free; closing the UI or walking away from that counter releases the clerk so wander resumes, unless another player is still using the same staff station. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp. 350
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free; closing the UI or walking away from that counter releases the clerk so wander resumes, unless another player is still using the same staff station. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp. 351
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`351
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`352
352
353
## Player scripting hooks353
## Player scripting (AFK / offline)354
354
355
**Status:** not implemented 355
**Status:** not implemented 356
**Spec:** Reserved control abstraction; not in the initial release. 356
**Spec:** Full language + UI + online/AFK/offline behaviour is documented in [`docs/SCRIPTS.md`](SCRIPTS.md). Scripts are a sandboxed, server-interpreted language that emits normal player intents. Players manage scripts in a Scripts panel (create/edit/delete, Run, Offline/AFK flags), see a bottom run bar while a script executes, confirm logout with an optional offline-script checkbox and danger line, auto-start an AFK script after 5 minutes idle, and get persistent toast or Frederick (Idle Gaming) pigeon letters on errors. Offline scripts keep the character in the world up to 1 hour; re-login attaches to the same instance. Architecture hooks remain in design doc §18. 357
**Code:** —357
**Code:** — (planned: `shared/scripts/`, `server/src/scripts/`, `client/src/play/scripts.js`, state DB script rows)@@ -0,0 +1,348 @@
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
6
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.
7
8
This 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
41
When 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
49
On logout while in the world:
50
51
1. 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**.
56
2. 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!**
58
3. 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
82
Always:
83
84
```text
85
Line <n>: <operation> — <reason>
86
```
87
88
Example:
89
90
```text
91
Line 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
126
The 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
158
Arrival = 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
170
Exact 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
211
Forward 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
216
if health below 30
217
goto heal
218
end
219
220
if stamina below 5
221
run off
222
end
223
224
if can craft "Bronze bar"
225
craft "Bronze bar"
226
end
227
228
if in range item "Bronze pickaxe"
229
equip "Bronze pickaxe"
230
end
231
232
for 10
233
find block "Tin ore"
234
go block
235
mine
236
end
237
238
while in range mob "Rat"
239
find mob "Rat"
240
go mob
241
attack
242
end
243
```
244
245
Rules:
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
267
label start
268
equip "Bronze pickaxe"
269
run on
270
271
for 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
283
end
284
stop
285
286
label flee
287
run on
288
find mob "Town Guard"
289
go mob
290
stop
291
```
292
293
---
294
295
## 8. Syntax highlighting (editor)
296
297
Highlight 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
308
Invalid 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
333
1. **Data + UI shell** — CRUD scripts, flags, editor with highlighting, no execution.
334
2. **Online runner** — interpreter + run bar + stop; subset: `find` / `go` / `wait` / `label` / `goto` / `stop`.
335
3. **Gather + equip + vitals if** — `mine` / `chop` / `harvest` / `equip` / `if health|stamina`.
336
4. **Combat + shops + craft** — `attack` / `buy` / `sell` / `craft` / `can craft`.
337
5. **Loops + range checks** — `for` / `while` / `in range *`.
338
6. **AFK auto-start** — 5-minute idle.
339
7. **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.
@@ -0,0 +1,348 @@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
6
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.7
8
This document is the product + language spec for implementation.9
10
---11
12
## 1. Goals13
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 UI22
23
### 2.1 Scripts button24
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 editor31
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 bar40
41
When 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 confirmation48
49
On logout while in the world:50
51
1. 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**.56
2. 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!**58
3. Confirming with the checkbox checked starts/continues the offline script on that character (see §4).59
60
---61
62
## 3. Modes63
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. Errors79
80
### 4.1 Message shape81
82
Always:83
84
```text85
Line <n>: <operation> — <reason>86
```87
88
Example:89
90
```text91
Line 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 overview113
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 targets125
126
The 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 Targeting141
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 Movement151
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
158
Arrival = standing on the tile (ground item / interactable) or adjacent where the game requires adjacency (stations, melee, gather nodes).159
160
### 6.3 Gathering & world interact161
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
170
Exact gather verb must match what the block supports; wrong verb → error (`chop — That is not a tree.`).171
172
### 6.4 Crafting173
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 & shops180
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 & vitals188
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 checks196
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 & jumps205
206
| Statement | Meaning |207
|-----------|---------|208
| `label camp` | Declare label `camp`. |209
| `goto camp` | Jump to that label. |210
211
Forward and backward jumps allowed. Jumping into/out of loops is **disallowed** in v1 (error if attempted).212
213
### 6.9 Control flow214
215
```text216
if health below 30217
goto heal218
end219
220
if stamina below 5221
run off222
end223
224
if can craft "Bronze bar"225
craft "Bronze bar"226
end227
228
if in range item "Bronze pickaxe"229
equip "Bronze pickaxe"230
end231
232
for 10233
find block "Tin ore"234
go block235
mine236
end237
238
while in range mob "Rat"239
find mob "Rat"240
go mob241
attack242
end243
```244
245
Rules: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 Utility255
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 script264
265
```text266
# Tin loop with panic flee267
label start268
equip "Bronze pickaxe"269
run on270
271
for 20272
if health below 25273
goto flee274
end275
find block "Tin ore"276
go block277
mine278
if in range ground "Tin ore"279
find ground "Tin ore"280
go ground281
take282
end283
end284
stop285
286
label flee287
run on288
find mob "Town Guard"289
go mob290
stop291
```292
293
---294
295
## 8. Syntax highlighting (editor)296
297
Highlight 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
308
Invalid lines can be marked with a subtle error underline on Save (optional v1).309
310
---311
312
## 9. Persistence & limits313
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
333
1. **Data + UI shell** — CRUD scripts, flags, editor with highlighting, no execution.334
2. **Online runner** — interpreter + run bar + stop; subset: `find` / `go` / `wait` / `label` / `goto` / `stop`.335
3. **Gather + equip + vitals if** — `mine` / `chop` / `harvest` / `equip` / `if health|stamina`.336
4. **Combat + shops + craft** — `attack` / `buy` / `sell` / `craft` / `can craft`.337
5. **Loops + range checks** — `for` / `while` / `in range *`.338
6. **AFK auto-start** — 5-minute idle.339
7. **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.