# 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 | Mode | How it starts | Character in world | Client | |------|---------------|--------------------|--------| | **Online** | Scripts panel → Run | Yes | Connected; run bar visible | | **AFK** | No gameplay intents for **5 minutes**, and an AFK-marked script exists | Yes | Still connected; run bar appears when script starts | | **Offline** | Logout with offline checkbox | Yes (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: ```text Line : — ``` Example: ```text 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): | Target | Set by | Used by | |--------|--------|---------| | **Block** | `find block "..."` | `go`, `mine`, `chop`, `harvest`, `craft`, `in range block` | | **Mob** | `find mob "..."` | `go`, `attack`, `buy`, `sell`, `in range mob` | | **Ground** | `find 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 | Statement | Meaning | |-----------|---------| | `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 | Statement | Meaning | |-----------|---------| | `go` | Path to the last set target (block / mob / ground). **Blocks** until arrived or fails (blocked / lost / unreachable). | | `go block` / `go mob` / `go ground` | Same, explicit target kind. Also **blocks** until arrival. | | `run on` / `run off` | Toggle 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). Any other `move`-style path the script starts uses the same **wait-until-arrived** rule. ### 6.3 Gathering & world interact | Statement | Meaning | |-----------|---------| | `mine` | Gather/mine the targeted **block** (ore boulder, etc.). **Blocks** until finished or fails. | | `chop` | Fell the targeted tree block. **Blocks** until finished. | | `harvest` | Pick/harvest the targeted plant/herb/flower/cotton block. **Blocks** until finished. | | `take` | Pick up the targeted **ground** item into the bag. | | `use` | Interact 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 stations & alchemy **Principle:** script steps mirror what a player does in the UI. No free shortcuts that skip materials, skill, adjacency, or recipe knowledge. #### Crafting stations (furnace, anvil, woodworking, bench, spinning wheel, loom, tailor, leatherworking, …) | Statement | Meaning | |-----------|---------| | `craft "Bronze bar"` | At the targeted station **block**, start the same craft the player would (one product). **Blocks** until finished or fails (not at station, unknown recipe, missing mats, skill too low). | | `can craft "Bronze bar"` | Condition only. True if that craft would succeed **right now**. | | `craft "Cotton sweater" dye` | **Tailor only:** craft with dyeing on. Uses a **random** dye charge from the bag (no colour picker). **Fails** if dyeing is requested and the bag has no dye uses left. | | `craft "Cotton sweater"` | Tailor (or other station) **without** dyeing. | #### Alchemy cauldron — manual steps (1:1 with UI) Require a targeted cauldron (find + go / adjacency), same as opening the cauldron as a player. | Statement | Meaning | |-----------|---------| | `cauldron insert "Thyme"` | Insert that ingredient from the bag. | | `cauldron heat` | Heat. | | `cauldron stir` | Stir. | | `cauldron cool` | Cool. | | `cauldron bottle` | Bottle into an empty glass bottle. **Blocks** until done. | | `cauldron clear` | Clear/abandon the brew if the UI allows it. | Step order and outcomes match humans: correct sequence → potion (with Alchemy skill roll); wrong sequence → unstable brew. Scripts get **no** easier success path. Example (same steps a player would click): ```text find block "Cauldron" go block cauldron insert "Thyme" cauldron heat cauldron insert "Mint" cauldron stir cauldron bottle ``` #### Named `brew` — only with a recipe paper in the bag | Statement | Meaning | |-----------|---------| | `brew "Lesser health tonic"` | Allowed **only** if the inventory contains a **recipe paper** for that potion. Then run that paper’s recorded steps and bottle (consume herbs, bottle, skill checks as usual). **Fails immediately** if no matching recipe is in the bag (`brew — No recipe for that in your bag.`). | Without a recipe item, authors must write the `cauldron …` steps themselves. `brew` is “follow this paper,” not free knowledge of the recipe. #### Dyes (flower list, same as dye tab) | Statement | Meaning | |-----------|---------| | `cauldron dye ["White flower", "Yellow flower", "Yellow flower"]` | Make dye from that multiset of flowers (here: 1 white + 2 yellow). List order = insert order; repeat a name for more of the same flower. Consumes flowers from the bag; colour/yield rules match the normal dye UI. Fails if flowers missing, not at cauldron, or bottling not possible. | List syntax: `[ "...", "..." ]`. ### 6.5 Combat & shops | Statement | Meaning | |-----------|---------| | `attack` | Attack the targeted mob (player Attack intent). Does **not** wait for the kill by itself — use `wait until target dead` (§6.11). | | `stop attack` | Cancel the current attack engage (player cancel-attack). | | `buy "Feather" 10` | Buy quantity from targeted shop mob. Fails if no shop, not in range, can’t afford, or not stocked. | | `sell "Soft leather" 5` | Sell quantity to targeted shop mob (if it buys). | **Follow** is intentionally **not** supported. ### 6.6 Inventory, gear & vitals | Statement | Meaning | |-----------|---------| | `equip "Bronze pickaxe"` | Equip a matching item from the bag into its proper slot. Fails if missing or not equippable. | | `unequip weapon` | Clear that equipment **slot** into the bag. Slots: `head`, `chest`, `legs`, `boots`, `weapon`, `offhand` (same as game). **Fails if the bag has no free space.** | | `drink "Lesser health tonic"` | Drink a matching consumable from the bag. | | `eat "Apple"` | Eat a matching food from the bag. | | `drop "Tin ore" 5` | Drop quantity from the bag onto the ground. | | `read "Spark spellbook"` | Read a spellbook from the bag to learn its spell (same as player). Fails if missing, already known, or requirements not met. | | `if health below 30` … | See control flow. | | `if stamina below 5` … | See control flow. | ### 6.7 Range checks & queries | Statement | Meaning | |-----------|---------| | `if in range block "Furnace"` | True if a matching block exists within interaction/path range. | | `if in range mob "Deer"` | True if a matching living mob is within **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 (quantity ≥ 1). | | `if bag has "Tin ore" at least 10` | Bag quantity check. | | `if bag has "Tin ore" below 10` | Bag quantity check. | | `if target health below 20` | Targeted **mob** current HP below N. Fails the condition (false) if no mob target; does not hard-error. | | `if target dead` | Targeted mob is gone or at 0 HP. | ### 6.8 Bank, cheques, market, social economy Requires being at / having path-interacted with the right block where the game requires it (bank counter, bounty office, marketplace). | Statement | Meaning | |-----------|---------| | `bank deposit "Tin ore" 20` | Move quantity from bag → vault. | | `bank withdraw "Tin ore" 20` | Move quantity from vault → bag. | | `write cheque "Tin ore" 50` | Write a cheque reserving that item+qty from the **bank (vault)**. Fails if the vault lacks enough. | | `redeem cheque` | Redeem a written cheque from the bag at a bank (goods → vault), same as player. | | `market sell "Tin ore" 10 for 8` | Place sell order (qty, min unit price). Escrows goods + listing fee like the UI. | | `market buy "Tin ore" 10 for 12` | Place buy order (qty, max unit price). Escrows coins like the UI. | | `market cancel sell` / `market cancel buy` | Cancel the character’s open order of that side (or nearest matching — prefer cancelling by item name if multiple: `market cancel sell "Tin ore"`). | | `raise bounty on "Ada Worker" 100` | Raise bounty (near bounty office, pays from bag). | | `send pigeon to bank` | Courier cargo to own bank (same rules as UI). | | `send pigeon to "Ada Worker"` | Courier to that character (payload from current letter/cheque/item selection rules — see open choices). | | `write letter "..."` | Write letter body onto a blank letter/cheque flow as the game allows. | | `say "hello"` | Local chat say. | ### 6.9 Spells | Statement | Meaning | |-----------|---------| | `cast "Light"` | Cast on the targeted **block** tile (tile-target spells). Approaches into range if needed (same as player cast). **Blocks** until cast attempt resolves (success or fizzle still continues unless you `wait until` something else). | | `cast "Spark" on mob` | Cast entity-target spell on the mob target. | | `cast "Light" on block` | Explicit tile target = targeted block’s tile. | Fails if unknown spell, not learned, on cooldown, out of range with no path, or wrong target kind. ### 6.10 Labels & jumps | Statement | Meaning | |-----------|---------| | `label camp` | Declare label `camp`. | | `goto camp` | Jump to that label. | Forward and backward jumps allowed. Jumping into/out of loops is **disallowed** (error if attempted). ### 6.11 Control flow ```text 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 wait until target dead end ``` Rules: - Blocks end with `end`. - `if` body runs when the condition is true; no `else` (use a second `if` / `goto`). - `for N` — repeat body **N** times (N ≥ 1, max **1000**). - `while ` — repeat while condition true; **max 1000** iterations per `while` then error (`while — Too many repeats.`). - Conditions: `health below N` · `stamina below N` · `can craft "..."` · `in range block|mob|ground|item "..."` · `bag has "..." at least|below N` · `target health below N` · `target dead` ### 6.12 Waiting (`wait` / `wait until`) | Statement | Meaning | |-----------|---------| | `wait 2` | Pause **2 seconds** (server time). Max **60** per wait. | | `wait until arrived` | Block until the current path finishes (usually redundant after `go`, which already waits). | | `wait until gathered` | Block until the active mine/chop/harvest completes. | | `wait until crafted` | Block until the active station craft / `brew` / `cauldron bottle` completes. | | `wait until target dead` | Block until the mob target is dead or despawned. Fails if no mob target. | | `wait until health at least 50` | Block until own HP ≥ N (or timeout — see below). | | `wait until stamina at least 5` | Block until stamina ≥ N. | | `wait until in range item "Bronze bar"` | Block until bag has that item. | | `wait until in range mob "Deer"` | Block until such a mob is in range. | | `wait until bag has "Tin ore" at least 10` | Block until quantity met. | | `wait until can craft "Bronze bar"` | Block until craft would succeed at current station target. | **Principle:** every boolean condition usable in `if` / `while` is also valid after `wait until`. Extend this set whenever new conditions ship. Optional timeout (recommended): `wait until target dead or 60` — fail with timeout error after N seconds so offline scripts cannot hang forever on one line. `go` / gather / `craft` / `brew` already **block** like a built-in `wait until` for their own completion. ### 6.13 Utility | Statement | Meaning | |-----------|---------| | `stop` | End the script successfully (no error letter). | --- ## 7. Death while a script is running If the character **dies** for any reason while a script is active (online, AFK, or offline): 1. **Stop** the script immediately (not an “error letter” unless death was caused mid-op failure — death itself is a clean stop). 2. **Fully log the instance out** of the world (despawn entity, persist dead flag / position as normal death logout). 3. When the player next connects, they see the normal **respawn** screen — no auto-respawn from scripts. There is **no** `respawn` script command. --- ## 8. Example script ```text # 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 drink "Lesser health tonic" stop attack find block "Bank" go block bank deposit "Tin ore" 999 stop ``` --- ## 9. Syntax highlighting (editor) Highlight at least: | Class | Examples | |-------|----------| | Keyword | `find`, `go`, `mine`, `chop`, `harvest`, `craft`, `brew`, `cauldron`, `attack`, `buy`, `sell`, `equip`, `unequip`, `drink`, `eat`, `drop`, `read`, `cast`, `bank`, `market`, `write`, `redeem`, `raise`, `send`, `say`, `label`, `goto`, `if`, `end`, `for`, `while`, `wait`, `stop`, `run`, `take`, `use`, `can` | | Subkeyword | `block`, `mob`, `ground`, `item`, `health`, `stamina`, `below`, `at`, `least`, `in`, `range`, `on`, `off`, `until`, `arrived`, `gathered`, `crafted`, `target`, `dead`, `deposit`, `withdraw`, `cheque`, `pigeon`, `bounty`, `sell`, `buy`, `cancel`, `insert`, `heat`, `stir`, `cool`, `bottle`, `clear`, `dye` | | String | `"..."` | | List | `[ "...", "..." ]` (flower lists for `cauldron dye`) | | Number | `10`, `30` | | Comment | `# ...` | | Label name | after `label` / `goto` | | Slot name | after `unequip` (`weapon`, `head`, …) | Invalid lines can be marked with a subtle error underline on Save (optional v1). --- ## 10. 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 (at most one **blocking** wait/path/gather/craft at a time; non-blocking lines burst with a low cap). --- ## 11. 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; **any manual gameplay intent stops** the script. - Offline `say` / pigeon / bounty: same validation as players; add rate limits if abused. --- ## 12. Implementation plan (phased) 1. **Data + UI shell** — CRUD scripts, flags, editor with highlighting, no execution. 2. **Online runner** — interpreter + run bar + stop; `find` / `go` (blocking) / `wait` / `wait until` / `label` / `goto` / `stop`. 3. **Gather + gear + vitals** — `mine` / `chop` / `harvest` / `equip` / `unequip` / `drink` / `eat` / `if health|stamina`. 4. **Combat + shops + craft/alchemy** — stations via `craft` (tailor `dye` flag); cauldron via step verbs + recipe-gated `brew` + `cauldron dye [...]`. 5. **Loops + range + bag/target queries**. 6. **Bank, cheques, market, spells, pigeon, chat, bounty, spellbooks**. 7. **AFK auto-start** — 5-minute idle. 8. **Offline logout flow** — modal, entity retention, 1-hour cap, re-login attach, error pigeon, **death → full logout**. --- ## 13. Open choices (resolve during implementation) - Exact radius for `in range mob/ground` (proposed **15**). - AFK timer: opening Scripts panel does **not** reset idle (only gameplay intents). - Display-name collisions: **closest** wins. - `send pigeon to "Name"` payload: letter only, or also item/cheque from bag — match the pigeon UI’s current options. - `wait until … or N` timeout syntax — recommended for all `wait until` forms. - `market cancel` when multiple orders exist: require item name disambiguation. --- ## 14. Out of scope | Area | Reason | |------|--------| | **Follow** | Not needed for scripts | | **Friends** | Social; low AFK value | | **Barber / hair** | Cosmetics | | **Inspect / social panel** | Not needed for AFK | | **Graphics settings** | Client-only | | **World editor** | Admin | | **`respawn` command** | Death always full-logout; player uses respawn UI on next login | - Script steps should stay aligned with player UI actions; never add a verb that skips a check the human UI enforces (recipe paper for `brew`, random dye only for tailor, etc.). ### Still fine to add later if play gains new intents Dye-clothing-from-bag (if not covered by cauldron), inheritance claim, blank-cheque get/return — add a matching verb when useful. When a new player-facing intent ships, add a matching script statement in the same feature commit.