# pickupsKit 2.3.14
Coins, gems, hearts, shields, keys, letters and power-ups for any game: one `Pickup` component, 47 looks in five styles, each tagged with its size, and multiplayer claims where a simultaneous grab has exactly one winner.
Built for platformers, arena shooters, kart racers and adventure games. Every pickup also has its own synthesised sound.
## Guides
Two guides ship inside this package, in `pickupsKit.package/guides/`, and install with it. Open them from the Docs panel, or ask your agent for them by name:
- **[How to add coins, gems and power-ups to my game](pickupsKit.package/guides/how-to-add-coins-gems-and-power-ups-to-my-game)**: the how-to. What the kit is and what to do first, placing pickups, picking and swapping a look (one setting swaps it for every player), what each kind of pickup gives, pickups that come back or vanish with a blink, magnet pull, chests and coin bursts, what happens when several players go for the same pickup, reading and spending what a player collected, and scoring pickups with scoreKit.
- **[Make a coin and gem collecting game with power-ups and respawning pickups](pickupsKit.package/guides/make-a-coin-and-gem-collecting-game-with-power-ups-and-respawning-pickups)**: the example. From an empty world, a small game with a ring of coins, rubies, a speed power-up and a gem fountain where emeralds keep coming back, with every grab scored by scoreKit.
Both link the guides of the kits pickups go with. SecondWind's [How to add health and damage to your game](SecondWind.package/how-to-add-health-and-damage-to-your-game) and juiceKit's [How to add screen shake, hitstop and hit feedback to your game](juiceKit.package/how-to-add-screen-shake-hitstop-and-hit-feedback-to-your-game) and [Make your game feel juicy step by step with hit feedback, explosions and damage numbers](juiceKit.package/make-your-game-feel-juicy-step-by-step-with-hit-feedback-explosions-and-damage-numbers) come into your world with pickupsKit. scoreKit's [How to add a score and combo system to my game](scoreKit.package/guides/how-to-add-a-score-and-combo-system-to-my-game) and [Make an arcade game with a score, combos and a leaderboard](scoreKit.package/guides/make-an-arcade-game-with-a-score-combos-and-a-leaderboard) come with scoreKit, a separate install.
## Install
One install: `zeromind_install guid=0d70dd00-9297-45d5-a290-5a51b9f9e262`, or search ZeroMind for "pickupsKit" and install it from the ZeroMind panel.
That one install also brings the kits pickupsKit builds on as its own dependencies under `/source/deps/`, each in its current release. Your world ends up with `/source/pickupsKit.package` and nothing else to set up. While the files land, the log can show passing lines such as `waiting for content it requires` or `which is being fetched`; they stop once the install is done.
## Builds on
- **SecondWind 1.2.0** or newer (the "Second Wind" world): hearts, medkits and potions heal through it, shields top up its shield, and the damage and invincible power-ups go through its damage filter. SecondWind is itself built on **Lifeline 1.0.1** and **MatchFlow**, which come along too. Installs in November 2026 brought SecondWind 1.3.1 and Lifeline 1.0.1, and MatchFlow 1.3.1 or 1.0.0: the MatchFlow release an install picks has varied from one day to the next, and both work with pickupsKit.
- **juiceKit 1.2.1** or newer (the "Juicebox" world): the sparkle, flash and pop when something is picked up, spawns or expires. pickupsKit 2.3.13 brings juiceKit 1.2.10.
pickupsKit 2.3.1 and 2.3.2 were checked against exactly those versions in a brand-new world, and 2.3.3 in this showcase world once it was updated to them: the quick start below, hearts healing, power-ups, and the kit's 86 tests.
Your own scripts can use these kits directly, `require("SecondWind.api")` and `require("juiceKit.juice")`, or go through pickupsKit: `Pickups.health()` returns SecondWind's api, `Pickups.healthParts()` its `Rules`, `Health`, `HUD` and `Trap` components, and `Pickups.juice()` juiceKit's effects. Both reach the same copy.
`Pickups.dependencies()` lists each kit with the version it needs, the version installed, whether it has loaded, and `ok`, which is true when the installed one is that version or newer.
**Pickups never wait for these.** The kit loads SecondWind and juiceKit the first time it needs them, not when it starts. If one is missing or still downloading (a web build fetches packages while the world opens), pickups still appear, spin, collect and count, and the counter and chests still work; the kit logs one warning and tries again a little later. A heart taken meanwhile is still collected, with `note = "no health kit"` on its `collect` event.
## Quick start
Add these lines inside `content()` in your scene's `build.luau`, just before its closing `end`. A brand-new world already has one, `scenes/main.scene/build.luau`, with a ground, a sky and a player. (A world without a scene gets one from `tools.use("scene", "create", "level", "player", { startup = true })`; add the lines to `scenes/level.scene/build.luau` the same way.)
```lua
local Pickups = require("pickupsKit.api")
-- the coin counter in the corner of the screen
entity.spawn("PickupHUD").component.add(Pickups.HUD, { style = "pixel" })
-- five pixel gems in a line in front of where the player starts
for i = 1, 5 do
Pickups.spawn({ (i - 3) * 1.5, 0, 4 }, { prefab = "pixelGem" })
end
```
Press **Play** and walk forward. Each gem you touch pops with a sparkle and a coin sound, and the counter adds 1. Each gem comes back 5 seconds later. The host makes the synced ledger that holds the counts by itself, so there is nothing else to place.
## More examples
All of these go in `content()` too, after the quick start.
```lua
-- Health for players, so hearts and shields have something to heal.
local HK = Pickups.health()
entity.spawnSynced("HealthRules").component.add(HK.RULES, {})
HK.attach(body, { model = "shield" }) -- `body` is your PlayerPrototype's body entity
-- A heart that heals 25, a speed power-up and a key that never comes back.
Pickups.spawn({ -2, 0, 6 }, { prefab = "heart" })
Pickups.spawn({ 0, 0, 6 }, { prefab = "speedOrb", duration = 10 })
Pickups.spawn({ 2, 0, 6 }, { prefab = "silverKey", respawn = false })
-- Letter tokens that spell ZERO, one copy per player.
for i, l in { "Z", "E", "R", "O" } do
Pickups.spawn({ -3 + i * 1.5, 0, 8 }, { prefab = "letterToken", letter = l, mode = "perPlayer" })
end
-- A chest that spills 12 rubies when a player walks up to it.
local chest = entity.spawnSynced("Chest", { position = { 0, 0, 11 } })
chest.component.add(Pickups.CHEST, { prefab = "ruby", count = 12 })
```
Hearts and shields heal only bodies that have SecondWind health, as above. Without it a heart is still collected, but it has nothing to heal. `Pickups.health()` is nil while SecondWind is still loading; in `content()` it has loaded.
To show a word's letters lighting up, give the HUD a word: `{ style = "cartoon", word = "ZERO" }`.
**Reading and spending from your own code** (in a component or anything else that runs in play):
```lua
Pickups.on("collect", function(ev) print(ev.key, "took", ev.prefab, ev.amount) end)
if Pickups.spend(player, "coins", 10) then openDoor() end
print(Pickups.get(player, "keys"), Pickups.letters(player), Pickups.spelled(player, "ZERO"))
```
**Switching a look is one setting**, and it applies right away, for every player, also while the game runs:
```lua
pickupEntity.component.get(Pickups.PICKUP).prefab = "pixelGem" -- on the engine that owns the pickup
Pickups.setPrefab(pickupEntity, "pixelGem") -- from any engine
```
The model is rebuilt on every engine as the change arrives. The pickup keeps its other settings. With `effect = "auto"` (the default) it now does what the new look does.
**Who can write the setting.** Like every synced setting, `prefab` can only be written by the engine that owns the pickup: the host for scene pickups, or whoever spawned it. Any other engine's write is refused by the engine on the spot and changes nothing, and the kit can't catch it. `Pickups.setPrefab` works from every engine: on the owner it writes the setting, and elsewhere it asks the owner to. Both were played with two players: a coin one player owned changed to `pixelGem` for both through the plain setting, and a gallery pickup the other player's engine owned changed through `setPrefab` called by the player who wasn't hosting. Old names worked the same way, through `look = "cartoon_coin"` and `setPrefab(box, "cartoon_mystery")`.
**Coin bursts** from a defeated enemy or a broken pot:
```lua
Pickups.burst(enemy.position, { prefab = "goldCoin", count = 10, lifetime = 12 })
```
The coins fly out and bounce. Each one can only be taken once it has settled, and each blinks for its last 3 seconds before it disappears.
## The Pickup component
`pickupsKit.Pickup`. Every setting is synced: a change made on the engine that owns the pickup reaches every engine, also while the game runs.
| Setting | Default | What it does |
|---|---|---|
| `prefab` | `goldCoin` | Which of the 47 looks it wears, by its short name (the Looks table). This also sets what it does when `effect` is `auto`. |
| `look` | `goldCoin` | The older name of `prefab`, kept so existing scenes and code keep working. It takes the new names and the old ids. Whichever of the two you write, the other follows. |
| `effect` | `auto` | What touching it does: `auto`, `counter`, `heal`, `shield`, `item`, `letter`, `powerup`, `mystery` or `none`. |
| `amount` | 0 | How much it gives: coins, health, shield and so on. 0 uses the look's amount. |
| `counter` | "" | Counter for `counter`: coins, gems, stars, rings, xp, ammo, or any name of your own. |
| `item` | "" | Item for `item`: keys, keycards, or your own. It is counted like a counter. |
| `letter` | "A" | The letter shown on letter tokens. |
| `powerup`, `duration` | "", 0 | The power-up and its length in seconds: `speed`, `jump`, `damage`, `magnet` or `invincible`. |
| `radius` | 1.1 | How close a player must come to take it, in metres. |
| `magnetRange` | 0 | Within this range it flies to the player. 0 means no magnet. A `magnet` power-up triples it. |
| `respawn`, `respawnTime` | true, 5 | Whether it comes back after being taken, and after how many seconds. |
| `lifetime`, `blinkTime` | 0, 3 | It disappears after `lifetime` seconds untouched (0 = never), blinking for the last `blinkTime` of them. With `respawn` on, it then comes back after `respawnTime`. |
| `mode` | `shared` | `shared`: the first player to touch it gets it. `perPlayer`: every player can take their own copy, and it comes back for each of them separately. |
| `bob`, `spin`, `hover`, `scale` | 0.12, 1.8, 0.6, 1 | Bob height in metres, spin in turns per second, hover height and size. |
| `visible` | true | Hide it without removing it. |
| `castShadows` | false | Cast a sun shadow. Off by default, because many small spinning casters redraw the shadow map every frame, which costs most in a web browser. Turn it on for a few hero pickups. |
`available`, `taken`, `armed` and `launch` are state fields that the kit writes itself.
**Old names keep working.** Every look had a longer id before 2.2.0 (`cartoon_coin`, `real_gold_coin`, `pixel_gem_coin`...), and six looks had other short names in 2.2: `redHeart`, `speedCore`, `damageCore`, `jumpCore`, `xpShard` and `ammoBox` are now `heart`, `speedOrb`, `damageOrb`, `jumpOrb`, `xpOrb` and `ammoCrate`. Every older name still works everywhere a look goes: the `look` setting, `spawn`, `setPrefab`, `setLook`, `burst`, chests and `look()`, and it is stored as the main name. The `prefab` field's own list holds only the main names, so writing an older name straight into `prefab` is refused by the engine; use `look`, or `setPrefab`. The Looks table shows every other name a look answers to, and `looks()` returns them as `otherNames`.
**Other components:**
- `PickupChest` opens when a player comes within `radius` and spills `count` coins of any `prefab` (`look` is its older name there too). It closes again after `cooldown` seconds, or stays open if `cooldown` is 0. It draws its own chest model; set `showModel = false` to use yours.
- `PickupHUD` is the on-screen counter, with `style` set to cartoon, scifi, fantasy, pixel or realistic. Its other settings:
- `counters`: which counters it shows, in order;
- `word`: a word whose letters light up as they are collected;
- `showPowerups`: running power-ups with their time left;
- `showPlayers`: every player's coins;
- `corner`: which top corner it sits in.
- `PickupLedger` is the synced record of every player's counters and letters. The host spawns it by itself.
## Looks
There are 47 looks in five styles that a world can mix and match: cartoon 9, sci-fi 10, fantasy 10, pixel 9 and realistic 9. To list them, call `Pickups.looks()`, or filter with `Pickups.looks({ style = "pixel" })`, `Pickups.looks({ kind = "coin" })` or `Pickups.looks({ size = "small" })`; filters combine. Each entry carries its `id` (the `prefab` name), `oldId`, `name`, `style`, `kind`, `effect`, `size`, `sizeM`, `dims` and what it gives.
| Style | What it looks like |
|---|---|
| cartoon | Chunky glossy shapes with dark ink outlines. |
| scifi | Dark metal shells around glowing energy cores. |
| fantasy | Gems, potions in glass, gold and runes. |
| pixel | Voxel sprites: 8-bit pixels with real depth. |
| realistic | Brushed metal, brass, painted boxes and real-world props. |
**Sizes.** Every look carries a size tag measured from its model at `scale = 1`. `dims` is its width, height and depth in metres, and `sizeM` is the largest of the three. `Pickups.sizes()` lists the tags:
| Size | Largest side | Looks |
|---|---|---|
| `small` | up to 0.62 m | 9: gems, wisps, the realistic coins and kits |
| `medium` | 0.63 to 0.75 m | 28: most coins, hearts, keys, badges and pixel sprites |
| `large` | over 0.75 m | 10: power-up cores, potions, shields and the winged orb |
Use the tag to pick looks that sit well together, or to choose a `radius`: about 1.1 suits small and medium looks, and about 1.3 suits large ones. `pickupsKit.visual.extent(prefab)` measures a model's box directly.
| `prefab` | Also answers to | Name | Style | Kind | Effect | Size | Gives |
|---|---|---|---|---|---|---|---|
| `goldCoin` | `cartoon_coin` | Gold coin | cartoon | coin | counter | medium (0.72 m) | coins +1 |
| `goldStar` | `cartoon_star` | Star | cartoon | star | counter | large (0.78 m) | stars +1 |
| `goldRing` | `cartoon_ring` | Gold ring | cartoon | ring | counter | medium (0.72 m) | rings +1 |
| `heart` | `cartoon_heart`, `redHeart` | Heart | cartoon | heart | heal | medium (0.68 m) | heal 25 |
| `mysteryBox` | `cartoon_mystery` | Mystery box | cartoon | mystery | mystery | medium (0.65 m) | random roll |
| `letterToken` | `cartoon_letter` | Letter token | cartoon | letter | letter | medium (0.70 m) | its `letter` |
| `speedBadge` | `cartoon_speed` | Speed badge | cartoon | powerup | powerup | medium (0.70 m) | speed 8s |
| `damageBadge` | `cartoon_damage` | Damage badge | cartoon | powerup | powerup | medium (0.70 m) | damage 8s |
| `jumpBadge` | `cartoon_jump` | Jump badge | cartoon | powerup | powerup | medium (0.70 m) | jump 8s |
| `energyCredit` | `scifi_chip` | Energy credit | scifi | coin | counter | medium (0.70 m) | coins +1 |
| `shieldCell` | `scifi_shield` | Shield cell | scifi | shield | shield | large (0.77 m) | shield 30 |
| `accessCard` | `scifi_keycard` | Keycard | scifi | keycard | item | medium (0.64 m) | keycards +1 |
| `ammoCell` | `scifi_ammo` | Ammo cell | scifi | ammo | counter | medium (0.72 m) | ammo +30 |
| `speedOrb` | `scifi_speed`, `speedCore` | Speed orb | scifi | powerup | powerup | large (0.78 m) | speed 8s |
| `damageOrb` | `damageCore`, `scifi_damage` | Damage orb | scifi | powerup | powerup | large (0.78 m) | damage 8s |
| `jumpOrb` | `jumpCore`, `scifi_jump` | Jump orb | scifi | powerup | powerup | large (0.78 m) | jump 8s |
| `magnetCore` | `scifi_magnet` | Magnet core | scifi | powerup | powerup | large (0.78 m) | magnet 10s |
| `xpOrb` | `scifi_xp`, `xpShard` | XP orb | scifi | xp | counter | medium (0.66 m) | xp +10 |
| `nanoMedkit` | `scifi_medkit` | Nano medkit | scifi | medkit | heal | medium (0.64 m) | heal 50 |
| `ruby` | `fantasy_ruby` | Ruby | fantasy | gem | counter | small (0.60 m) | gems +1 |
| `emerald` | `fantasy_emerald` | Emerald | fantasy | gem | counter | small (0.54 m) | gems +3 |
| `healingPotion` | `fantasy_potion_red` | Healing potion | fantasy | potion | heal | large (0.76 m) | heal 35 |
| `wardPotion` | `fantasy_potion_blue` | Ward potion | fantasy | potion | shield | large (0.76 m) | shield 35 |
| `goldenKey` | `fantasy_key` | Golden key | fantasy | key | item | medium (0.69 m) | keys +1 |
| `silverKey` | | Silver key | fantasy | key | item | medium (0.69 m) | keys +1 |
| `crestShield` | | Crest shield | fantasy | shield | shield | large (0.81 m) | shield 40 |
| `wingedOrb` | `fantasy_jump` | Winged orb | fantasy | powerup | powerup | large (0.94 m) | jump 8s |
| `runeStone` | `fantasy_rune` | Rune stone | fantasy | letter | letter | medium (0.67 m) | its `letter` |
| `xpWisp` | `fantasy_wisp` | XP wisp | fantasy | xp | counter | small (0.47 m) | xp +25 |
| `pixelGem` | `pixel_gem_coin` | Pixel gem | pixel | coin | counter | medium (0.72 m) | coins +1 |
| `pixelCoin` | `pixel_coin` | Pixel coin | pixel | coin | counter | medium (0.68 m) | coins +1 |
| `pixelHeart` | `pixel_heart` | Pixel heart | pixel | heart | heal | medium (0.68 m) | heal 25 |
| `pixelKey` | `pixel_key` | Pixel key | pixel | key | item | medium (0.70 m) | keys +1 |
| `powerStar` | `pixel_star` | Power star | pixel | powerup | powerup | medium (0.72 m) | invincible 8s |
| `jumpMushroom` | `pixel_mushroom` | Jump mushroom | pixel | powerup | powerup | medium (0.68 m) | jump 10s |
| `pixelSword` | `pixel_sword` | Pixel sword | pixel | powerup | powerup | medium (0.72 m) | damage 8s |
| `pixelLetter` | `pixel_letter` | Pixel letter | pixel | letter | letter | medium (0.72 m) | its `letter` |
| `questionBlock` | `pixel_mystery` | Pixel ? block | pixel | mystery | mystery | medium (0.63 m) | random roll |
| `silverCoin` | `real_silver_coin` | Silver coin | realistic | coin | counter | small (0.60 m) | coins +1 |
| `goldDoubloon` | `real_gold_coin` | Gold doubloon | realistic | coin | counter | medium (0.64 m) | coins +5 |
| `goldBar` | `real_gold_bar` | Gold bar | realistic | coin | counter | small (0.62 m) | coins +25 |
| `cutDiamond` | `real_diamond` | Diamond | realistic | gem | counter | small (0.60 m) | gems +5 |
| `firstAidKit` | `real_medkit` | Medkit | realistic | medkit | heal | small (0.62 m) | heal 50 |
| `ammoCrate` | `ammoBox`, `real_ammo` | Ammo crate | realistic | ammo | counter | small (0.62 m) | ammo +30 |
| `brassKey` | `real_key` | Brass key | realistic | key | item | medium (0.69 m) | keys +1 |
| `armorPlate` | `real_armor` | Armor plate | realistic | shield | shield | medium (0.71 m) | shield 50 |
| `energyDrink` | `real_energy` | Energy drink | realistic | powerup | powerup | small (0.60 m) | speed 8s |
## Effects
| Effect | What it does |
|---|---|
| `counter` | Adds `amount` to the player's `counter`. |
| `heal` | Heals `amount` through SecondWind (`HK.heal`), on the engine of the player who took it. A player at full health still takes it: the heart is collected and counted, and heals 0. |
| `shield` | Tops up the SecondWind shield by `amount`, up to the maximum, on the engine that holds that player's health (the kit sends it there). |
| `item` | Adds `amount` of `item` (keys, keycards...). Spend it with `Pickups.spend(player, "keys", 1)`. |
| `letter` | Adds the token's letter. Check a word with `Pickups.spelled(player, "ZERO")`. |
| `powerup` | Gives a timed power-up. Taking the same one again adds to its time. |
| `mystery` | Rolls one weighted reward: coins, XP, heal, shield or any power-up. |
| `none` | Nothing but the `collect` event, so you can handle it yourself. |
**Power-ups:**
- `speed`: moveSpeed ×1.6.
- `jump`: jumpForce ×1.55.
- `damage`: deals ×2 damage through SecondWind.
- `magnet`: pickups pull from 3× further away.
- `invincible`: takes no SecondWind damage.
Each family has a speed, damage and jump look: cartoon badges (`speedBadge`, `damageBadge`, `jumpBadge`), sci-fi orbs (`speedOrb`, `damageOrb`, `jumpOrb`), and the pixel `jumpMushroom`, `pixelSword` and `powerStar`.
Speed and jump are held on the player's CharacterController, on that player's own engine, for as long as the power-up runs. If something else, such as SecondWind's chill, changes the speed meanwhile, that change is respected.
Damage and invincible work through SecondWind's damage filter. Every engine knows every player's power-ups, so the filter is right wherever the damage is decided. The kit installs the filter the first time one of those power-ups is given, or straight away through `Pickups.setup()`. SecondWind keeps a single filter, so if your world has its own, call `Pickups.setup({ damageFilter = false })` and multiply by `Pickups.damageMultiplier(attacker, victim)` inside yours.
## API
`local Pickups = require("pickupsKit.api")`. A "player" argument can be an avatar entity, any collector entity, a peer number or a ledger key (`"p3"`).
**Pickups**
- `spawn(pos, settings?, { synced = true, name }?)` returns the entity. It errors on an unknown prefab or mode. `settings.prefab` names the look (`settings.look` is its older name).
- `burst(pos, { prefab, count = 8, amount, spread = 2.4, lifetime = 12, blinkTime = 3, magnetRange, mode, synced })` returns the coins.
- `setPrefab(pickup, prefab)` (also `setLook`), `collect(pickup, collector)`, `available(pickup, collector?)`.
- `restore(target?)` puts taken pickups back for a new round: one pickup, a list, or nil for every pickup in the scene. Returns how many it restored or asked the owner to restore.
- `all()` returns `{ [id] = Pickup }`. `openChest(chest)`.
**Counters**
- `get(player, counter)`, `counts(player)`, `allCounts()`.
- `add(player, counter, n)`, `set(player, counter, v)`, `spend(player, counter, n)`, `reset(player?)`.
- `ledger()` returns the PickupLedger component in use.
**Letters**: `letters(player)`, `spelled(player, word)`, `giveLetter(player, letter)`, `clearLetters(player)`.
**Power-ups**: `givePowerup(player, name, secs)`, `powerup(player, name)`, `powerupLeft(player, name)`, `activePowerups(player)`, `damageMultiplier(attacker, victim)`.
**Catalog**: `looks(filter?)` (filter by `style`, `kind`, `effect` and `size`), `look(id)` (a new name or an old id), `styles()`, `kinds()`, `effects()`, `powerups()`, `counters()`, `sizes()`. Everything they return is a copy.
**The kits it builds on**: `dependencies()` returns `{ name, needs, installed, loaded, problem, ok, why }` for SecondWind and juiceKit. `health()` and `juice()` return each module, or nil and why not, loading it if it can. `healthParts()` returns SecondWind's `{ Rules, Health, HUD, Trap }` components.
**Identity**: `keyOf(x)`, `nameOf(x)`, `localKey()`, `localAvatar()`, `owns(x)`.
**Checking every engine**: `peerReport(seconds?)` asks every engine in the play session for its `selfReport()` and returns `{ [peer] = report }`, this engine's own included. Each report says whether SecondWind and juiceKit loaded on that engine (and why not), which platform it runs on (`native` or `browser`), whether it holds the ledger, its own player's health as SecondWind sees it, and the outcome of the last heal or shield it applied. It is how a problem on another player's engine, such as a browser, can be read from yours.
**Collectors**: `addCollector(entity)` lets a bot or a kart collect, with its counts kept under `"e<id>"`. `removeCollector(entity)` undoes it.
**Setup**: `setup({ hud = true, hudStyle = "cartoon", word = "", damageFilter = true })` is optional. It makes the ledger now rather than after the host's first second, adds the HUD and installs the damage filter. `installDamageFilter()` installs just the filter.
**Events**, through `on(event, fn)`, which returns an unsubscribe function:
| Event | Arguments |
|---|---|
| `collect` | `ev` = `{ id (event id), p (pickup id), prefab, look (the same name), style, kind, effect, amount, counter, item, letter, powerup, duration, mystery, key, cid (collector id), pos, mode }` |
| `counter` | `key, counter, value, delta` |
| `letter` | `key, letter, letters` |
| `powerup` | `key, name, seconds` |
| `powerupEnd` | `key, name` |
| `respawn` | `pickupId` |
| `expire` | `pickupId, pos` |
| `burst` | `pos, count` |
| `chest` | `chestId` |
`pickupsKit.visual` draws a look on this peer, for your own props or menus:
- `build(prefab, { letter, name, shadows }?)` returns a handle;
- `place(h, pos, yaw, scale)`, `setVisible(h, on)`, `setShadows(h, on)`, `alive(h)`, `destroy(h)`;
- `extent(prefab)` returns the model's `{ x, y, z }` box at scale 1, or nil for an unknown look;
- `release(h)` parks a visual hidden for reuse, and `acquire(prefab, opts?)` takes a parked one of that look back, or builds a new one. `poolSize()` and `clearPool()` look after the pool, which holds up to `POOL_PER_LOOK` (16) per look and `POOL_MAX` (96) in all.
`pickupsKit.logic` holds the rules as pure functions you can reuse or test: `canClaim`, `applyClaim`, `settle`, `addCount`, `spelled`, `rollMystery`, `burstVelocity`, `stepCoin`, `magnetStep`, `blinkVisible`, `versionAtLeast` and more. `pickupsKit.catalog` is the raw data: `LOOKS`, `BY_ID`, `IDS`, `SIZES`, `REQUIRES`, `ALIASES` (old id to new name), `OLD_ID` (new name to old id) and `canonical(id)`, which turns any old id into the current name.
## How multiplayer works
- **The owner decides.** Every pickup is a synced entity, and the engine that owns it (the host, for scene pickups) is the only one that decides who gets it. Each engine runs the touch test for the players and collectors it moves, then asks the owner. The owner checks that the pickup is still available to that player and that the player is really within reach, then marks it taken in the same step, so when two players touch the same coin the first claim to arrive wins and it is counted once.
- **Entities travel as entities.** The kit never relies on an entity's id string matching on another engine: pickups, chests and players go over the network as entity references, which each engine receives as its own, and become local ids on arrival. As a safeguard the kit also sends each entity's sync id, which every engine shares, and can resolve an entity from it if a reference ever arrives as raw data. (Before 2.2.0 the kit sent id strings, so a claim from a player who wasn't hosting named a pickup the host didn't know, and none of their pickups did anything.)
- **One announcement per collect.** The owner announces the result as one event with an id. Every engine records the power-ups and plays the pop, and the engine of the player who took it applies their heal, shield, speed and jump, exactly once per event.
- **Every message counts once.** Every kit message carries an id of its own, and a repeat is dropped, so a message that reaches an engine twice is handled once. After a live edit of the kit, the old copy's handlers stay registered (#19348), so they check that their copy is still the current one and stand down otherwise; an edit never leaves two copies answering.
- **The counts live in one place.** Counters and letters live in the synced `PickupLedger`, and only its owner writes it. The host makes it. When the player who started play leaves, nobody counts as host any more (#19347), so then the lowest-numbered player in the play room makes it after `Pickups.LEDGER_FALLBACK_S` (2.5) seconds. As a safeguard, a moment after a new player appears in the play room, the ledger's owner makes it again with the same counts (`Pickups.LEDGER_REPUBLISH_S`, 1 second), so a late joiner always receives a fresh one. If two ledgers ever meet, every engine keeps the one with the lower sync id, and the other's counts are folded into it.
- **Shared or per-player.** A `shared` pickup has one `available` flag. A `perPlayer` pickup keeps a synced `taken` map of who has had it, so each player has their own copy.
- **Settings are synced.** `prefab` and the other settings are written by the pickup's owner and sync to every engine. From any other engine, `setPrefab` asks the owner to make the change.
**Seen with two players.** 2.2.0 and 2.2.1 were played with two engines in one play session, the host and a player who wasn't hosting:
- Each kind of pickup was dropped at the other player's feet, and their own engine picked it up, sending the pickup and their player as entity references.
- Coins, keys, a letter and XP were counted once under their name in the host's ledger.
- Heals and shields reach the player who isn't hosting: a heart healed them 20 → 45, and a shield cell took their shield 0 → 30.
- Speed and jump took their controller from 2.5 to 4 and from 5 to 7.75.
- With damage, their hit on the host counted double. With invincible, 30 damage to them changed nothing.
- With the magnet, a pickup out of reach flew to them.
- One coin under both players was taken exactly once.
- When the host left play, the other engine took over the pickups and kept deciding them.
- `prefab = "pixelGem"` written by a coin's owner reached the other engine, and `setPrefab` called by the player who wasn't hosting changed a pickup the host owned. Old names worked the same way.
- With the other engine hosting, a player joining late read everyone's counts as they were: the host's player had 2 coins, 1 key, 10 XP and the letter Z, exactly as before the join.
- A coin taken from the host's gallery disappeared on the player's own engine, came back when the host respawned it, and played its pop and sound there.
- On a per-player gem, the player took their own copy while the host's player kept theirs, and their copy came back on its own timer.
- A blinking coin's expiry, decided by the host, reached the other engine.
- Walking up to a chest the host owned opened it, and all 12 burst coins appeared on both engines.
- The counter on the screen of the player who wasn't hosting showed their own counts from the host's ledger (7 coins, 3 gems, 1 key, 10 XP, Z), with both players listed.
- **In a web browser.** The same check, with the person's browser hosting (`platform = "browser"`) and an editor as the other player, passed 12 of 12 for the browser player: coins, keys, a letter and XP counted once under their name; a heart healed them 60 → 85; a shield cell took their shield 0 → 30; speed 2.5 → 4 and jump 5 → 7.75; their hit counted double with damage; invincible stopped 30 damage; the magnet pulled a pickup to them; one coin under both players was taken once. SecondWind and juiceKit both loaded in the browser from the copies that come with pickupsKit.
**How it is tested.** One engine can't be two real players (#18688, #19114), so the tests play both ends of the network through the same handlers the relay runs (`_deliver`). As the host: the other player's claims for every kind of pickup, naming the pickup and their avatar by entity, are each decided once, counted under their key, refused the second time, and announced with entity references. As the other player's engine: the host's announcements heal and shield their own player on the next frame, boost speed and jump on their CharacterController, double their damage, make them invincible and give them a magnet. The "two players" test runs 20 coins and a heart through two players whose claims arrive early, late and twice; every coin is taken once.
**For testing your own game's netcode** (internal, not a stable API): `_deliver(channel, fromPeer, ...)` runs one of the kit's network handlers (`pk:claim`, `pk:got`, `pk:ledger`, …) as if a message had arrived from `fromPeer`. `_tap(fn)` calls `fn(channel, ...)` for everything this engine broadcasts and returns an unsubscribe function.
## Performance in the browser
The kit is built to keep a busy level smooth in a web browser:
- **No pickup shadows by default.** Turning them off cut the gallery's sun shadow drawing from about 4.9 ms to 2.2 ms a frame and its frame spikes from 29 to 3. Use `castShadows` only where it matters.
- **Visuals are reused.** A pickup that is removed or changes look parks its model, and the next pickup of that look takes it back instead of building a new one. Repeat bursts and look switches cost a fraction of a fresh build.
- **First builds are spread out.** In play, pickups appearing for the first time build at most `Pickups.BUILD_BUDGET_MS` (3 ms) of models a frame, and always at least one. A wave of spawns therefore takes a few frames instead of stalling one. A prefab or letter change never waits.
- **Labels: show and hide, don't rewrite.** Changing a `Text3D` label's text redraws it, about 5 ms each time. For text that cycles through known values, make one label per value and show the one you need. Showing or hiding a label costs about 0.01 ms. The gallery's look-switch label works this way.
## Known limits
Engine problems that still affect the kit, each with its GitHub issue:
- **#19339: the editor's checker flags lookups inside the kits that come with pickupsKit.** In a fresh install, the bundled copies of Lifeline, juiceKit and SecondWind show warnings such as `asset reference "~.Health" could not be resolved`. They are warnings only: the lookups resolve when the game runs, and nothing blocks publishing. pickupsKit's own lookups (`SecondWind.Rules`, `Vitals`, `HUD`, `Trap`) are no longer flagged.
- **#19340: a setting with a fixed list of choices can't take old names.** The `prefab` list holds only the new names, so writing an old id such as `cartoon_coin` straight into `prefab` is refused. Old ids go through `look`, `spawn`, `setPrefab`, `setLook` and `burst`. The editor's list for `look` shows the old ids after the new names.
- **#18688, #19114, #14448 and #20946: one engine can't be two players.** The loopback test mode doesn't echo messages (#18688), an agent working inside the engine has no way to bring in a second player (#19114) or start a web engine (#20946), and two engines signed in to the same account collide as one player (#14448). The kit's own tests therefore drive both ends of the network through `_deliver`, and a real two-player check needs a second engine or browser tab on a second account, as in "Seen with two players" above.
- **#22451: installing scoreKit after pickupsKit leaves extra copies, and the MatchFlow one logs errors.** scoreKit uses the pickupsKit already in your world, as the example guide does, but the install also writes copies under `/source/deps/.../versions/`: a second MatchFlow package under `deps/40bc9b7f-d32c-427f-b0ac-22d25071e2fa/versions/`, and two lone Lifeline files, `Lifeline.package/api.module` and `Lifeline.package/Health.component`, under `deps/45f92606-2e79-4b2b-8e03-b1fa2649e5c2/versions/`. In a fresh world set up exactly that way, only the MatchFlow copy logged errors: none while editing, four the first time Play was pressed after the world was reopened, none on the second Play, and two more the first time the kit looked up a player's health. The two Lifeline files logged nothing. Lifeline kept using its own complete Health, SpawnPoint and Projectile parts, so pickupsKit had nothing to redirect, and hearts healed as usual: damage took the player to 80 and a heart brought them back to 100.
- **#20750: frame rate of the showcase gallery in a web browser.** The gallery holds every look at once, with labels and lights, and its frame rate in a browser is an open engine issue. "Performance in the browser" below has what the kit itself does to keep pickups cheap.
- **#19258: the ZeroMind description can lag a release.** For a while after a new version is published, its ZeroMind page can still show the previous description. The README and guides in your world after an install are the current ones.
- **#19347: nobody is host once the player who started play leaves.** The host role stays with whoever started the play session, even after they leave, so code waiting for the host never runs. The kit works around it for its counts: when nobody is host, the lowest-numbered player in the play room makes the ledger. Your own host-only code (spawning enemies, starting a round) needs the same care.
- **#19348: a message handler can't be removed, and old ones keep running after a live edit.** Each time the kit's code is edited while the game runs, the previous copy's handlers stay registered. The kit's old handlers check that they are still current and do nothing otherwise, so live edits are safe. A full reload of play clears them.
## Showcase and tests
The world this package lives in, "Treasure Trove", opens on a gallery. It is set up exactly as a one-install world: pickupsKit in `/source`, and the kits it builds on only as its dependencies, at the versions a fresh install brings (SecondWind 1.3.1, juiceKit 1.2.8, Lifeline 1.0.1, MatchFlow 1.3.1; a fresh install can bring MatchFlow 1.0.0 instead). It has every look, labelled and grouped by style, and a station for each behaviour:
- a respawning coin;
- blink and vanish;
- a coin burst from a chest;
- a magnet line;
- a shared pickup and a per-player one side by side;
- hearts and shields beside a lava trap;
- power-ups;
- spelling a word;
- a coin that cycles through prefabs, the pixel gem among them, by setting its `prefab` exactly as "Switching a look" above describes.
Every look's label shows its main `prefab` name, the one you type to use it.
`pickupsKit.pickupskit` is the test suite. It covers every public call of the api, logic, catalog, sounds, meshes, visual and fonts, the new names and every old id, `prefab` and `look`, the player who isn't hosting, and checks this README against the code: the version heading, the kit versions above, a row with style, kind, effect and size for every look, the quick start (short, compiles, real names) and this Known limits list. Run it with `tools.use("tests", "run", { suite = "pickupskit" })`.
## Version
2.3.14, which matches `package.yaml` (`pickupsKit.catalog.VERSION`, checked by the tests).
- 2.3.14: `restore(target?)` makes taken pickups available again for a new round: a one-time pickup someone took comes back at once for everyone, put back by the machine that owns it (other machines ask it over the network). A test covers it.
- 2.3.13: the juiceKit line names the version an install brings (1.2.10; it said 1.2.8). Behaviour is unchanged.
- 2.3.12: Every file that names SecondWind, juiceKit or Lifeline (the api, catalog and test modules) is recorded again against SecondWind 1.4.7, juiceKit 1.2.10, MatchFlow 1.4.0 and Lifeline 1.0.4, so an install no longer brings older single-file copies of SecondWind, MatchFlow or Lifeline beside the current ones; current engine library. No pickup behaviour changed.
- 2.3.11: Dependencies brought current: SecondWind 1.4.7, juiceKit 1.2.10, MatchFlow 1.4.0 and Lifeline 1.0.4, the releases the other kits around pickupsKit use, so an install that brings pickupsKit beside them lands one release of each instead of two. The world also moved to the current engine library. No pickupsKit code changed; its suite runs 86 of 86.
- 2.3.10: A pickup more than 60 m from every collector this machine moves updates one frame in ten (carrying the elapsed time along), so a long course full of coins costs little while you are far from them. Nothing changes within 60 m.
- 2.3.9: Its tests find the package's own files wherever it is installed (at /source, or under /source/deps when another package installs it). In a world where platformer3dKit installed it, 6 of its tests failed because they read README.md, package.yaml and source files from a fixed /source/pickupsKit.package path.
- 2.3.8: the kit requires its own modules relative to its package (`~.api`, `~.catalog`, `~.meshes`) instead of `@root::pickupsKit.*`, which only names a pickupsKit installed at a world's source root. A world that got pickupsKit as a dependency (under `deps/`, e.g. through inventoryKit or economyKit) failed with "module '@root::pickupsKit.meshes' not found".
- 2.3.7: on today's engine `entity.exists` logs an error for a name passed to it, even inside `pcall`, and the kit asked it about player keys such as `p10`: in a race with item boxes that was hundreds of errors a second. The kit now asks it only about entity ids.
- 2.3.6:
- **Package description rewritten:** it now says plainly what pickupsKit gives a creator and how to install it (search ZeroMind for "pickupsKit", or install asset `0d70dd00-9297-45d5-a290-5a51b9f9e262`; one install brings everything it builds on). No kit code, guide or other README text changed.
- 2.3.5:
- **juiceKit's example guide is linked:** both guides and this README now link "Make your game feel juicy step by step with hit feedback, explosions and damage numbers" beside juiceKit's how-to guide. It comes into your world with pickupsKit.
- **The scoreKit leftovers, as they behave** (#22451): 2.3.4 said every leftover copy loads and fails, that this happens when the world opens, and that pickupsKit points Lifeline at its complete copy. A fresh-world test showed otherwise: only the MatchFlow copy logs errors (none while editing, four on the first Play after reopening the world, none on the second, two more the first time the kit looks up a player's health); the two lone Lifeline files log nothing; Lifeline keeps using its own complete parts by itself, and hearts heal as usual. The README and both guides now say exactly that. No kit code changed.
- 2.3.4:
- **Easier to find:** both guides now open by saying they cover collectible pickups that respawn, the way people search for them, and their search descriptions and tags say it too.
- **What installing scoreKit leaves behind, told as it is** (#22451): the guides and Known limits named only an older MatchFlow copy and called it unused. The install also leaves two lone Lifeline files (`api.module`, `Health.component`), and the engine does load these copies and logs errors from them, at world open and during play. Pickups, scoring and health keep working.
- **Example guide:** the coin ring is 12 m across (each coin 6 m out from the middle), as the code places it.
- **Builds on:** a fresh install can bring MatchFlow 1.0.0 or 1.3.1; the release an install picks has varied. No kit code changed.
- 2.3.3:
- **The showcase world runs the same dependencies a fresh install brings:** SecondWind 1.3.1, juiceKit 1.2.8, Lifeline 1.0.1 and MatchFlow 1.3.1. So SecondWind's and juiceKit's guides, which the two pickupsKit guides link, open in Treasure Trove too. Played after a clean reload: 120 damage then a heart (30 → 55 through SecondWind 1.3.1), a coin, a jump orb, and juiceKit's pop on each grab. 86 of 86 tests, twice. No kit code changed.
- 2.3.2:
- **README:** the #19339 entry now says where the checker's false warnings still show (inside the kits that come with pickupsKit; pickupsKit's own SecondWind lookups are no longer flagged). Played the example guide word for word in a second brand-new world after 2.3.1 was published: same results, and every guide link opened. No kit code changed.
- 2.3.1:
- **Two guides ship in the package:** "How to add coins, gems and power-ups to my game" and "Make a coin and gem collecting game with power-ups and respawning pickups". See "Guides" above.
- **Checked on today's engine** in a brand-new world that installed only pickupsKit: the quick start as written, hearts healing through SecondWind 1.3.1, power-ups, juiceKit 1.2.8, and 86 of 86 tests. No kit code changed.
- **README:** your own scripts can now require SecondWind and juiceKit directly (#19199 is fixed), and Lifeline's lone old copies (#19260) no longer land in a fresh install, so both left Known limits. A brand-new world already has a `build.luau` for the quick start. Known limits add #14448, #20946, #22451, #20750 and #19258, and #19339 now names where the checker's false warnings still show (the bundled kits' own files, no longer pickupsKit's).
- 2.3.0:
- **`heart`, `speedOrb`, `damageOrb`, `jumpOrb`, `xpOrb` and `ammoCrate` are main names** (they were `redHeart`, `speedCore`, `damageCore`, `jumpCore`, `xpShard` and `ammoBox`, which still work, as do the pre-2.2 ids). `looks()` and `look()` list every other name a look answers to as `otherNames`; `catalog.OTHER_NAMES` holds them.
- **Gallery:** each label shows the look's main name; the look switcher sets the coin's `prefab`, as the README says to; the gallery scene saves with nothing pending, so clearing and reloading it gives every pickup back.
- 2.2.1:
- **Played with two players, start to finish.** Every behaviour in "Seen with two players" was watched across two engines, with each engine taking a turn as host. That covers every pickup kind for the player who isn't hosting, per-player copies, late joiners, respawns, expiries, bursts and chests, the pop and sound, the counter, and `prefab` switches.
- **`collect` events carry `prefab`** as well as `look` (the README's own example read `ev.prefab`, which was missing).
- **Who can write `prefab`:** the README says it plainly. The pickup's owner writes the setting, and `setPrefab` works from any engine.
- **Known limits** now name only problems that still exist, each with its GitHub issue.
- **Heals and shields reach a player in a web browser** (played 12 of 12, see "Seen with two players"). Messages also carry each entity's sync id as a safeguard.
- **Hearts heal in a fresh install.** Lifeline's own health part resolved to a lone old-version copy that doesn't compile (#19260), so `HK.attach` gave no health. pickupsKit now points Lifeline at the complete copy when it loads SecondWind. Lifeline is now a direct dependency of pickupsKit, at the same 1.0.1.
- **Every message counts once.** A live edit of the kit left the old copy's handlers answering too (#19348). Messages now carry ids, repeats are dropped, old handlers stand down, and a heal or shield is applied exactly once per event.
- **The counts ledger always exists, for everyone.** It was made only by the host, and nobody counts as host once the player who started play leaves (#19347), so a session could count nothing. The lowest-numbered player in the play room now makes it when nobody is host, its owner makes it again when a new player joins, and two ledgers fold into one.
- **`peerReport()` and `selfReport()`** read every engine's view of the kit from yours.
- **Tests:** 85, including entities that arrive as raw data, a heal heard twice, repeated messages, the ledger election, folding two ledgers and making the ledger again for a joining player.
- **Played in a web browser:** every pickup kind, 12 of 12, for a browser player (see "Seen with two players").
- 2.2.0:
- **Pickups work for every player, not just the host.** The kit sent pickup and player ids as text, but every engine has its own ids for the same entity, so a claim from a player who wasn't hosting named nothing the host knew. Now pickups, chests and players cross the network as entity references. Coins, keys, letters, XP, hearts, shields and every power-up reach whoever touched them; a coin is still only ever taken once.
- **`prefab` is the setting**, with a short name for every look (`goldCoin`, `pixelGem`, `speedCore`, `healingPotion`, `brassKey`...). `look` and every old id (`cartoon_coin`, `real_gold_coin`...) keep working. Added `setPrefab`, `oldId` on `looks()`, `catalog.OLD_ID` and `catalog.PREFAB_IDS`; the chest takes `prefab` too.
- **One install.** Installing pickupsKit now brings SecondWind 1.2.0, juiceKit 1.2.2, Lifeline 1.0.1 and MatchFlow 1.0.0 with it, and the kit uses them. Added `healthParts()` for SecondWind's components; your own code reaches SecondWind through `Pickups.health()`.
- **Tests:** 77, including the new names, `prefab` and `look`, the player who isn't hosting, and walking up to a chest.
- **Chests open when you walk up to them anywhere.** Since 1.1.0 the walk-up check measured from the middle of the map, so a chest away from it only opened from code.
- **Showcase:** set up as a one-install world, every pickup by its new name.
- 2.1.0: pickups load without waiting for SecondWind or juiceKit; SecondWind 1.2.0; heals and shields heard in a message apply on the next frame.
- 2.0.0: renamed to pickupsKit (from pickupKit, same guid); `pixelGem`; five new looks; size tags; dependency versions; remote pops on the next frame.
- 1.1.1: works with SecondWind 1.1.1; passing a Pickup component no longer logs.
- 1.1.0: performance in the browser: pickup shadows off by default, pooled visuals, a per-frame build budget.
- 1.0.1: a two-player test of 20 coins and a heart.
- 1.0.0: first release, as pickupKit.
# saveKit
Every player gets their own saved profile (level, XP, unlocks and play stats) that is still there when they leave and come back, with four ways of saving, four levelling curves, versioned save layouts and themed progression screens.
Version **1.3.18**, built against the current controlsKit (1.3.2) and menusKit (1.3.19).
## Guides
Two guides come inside the package, so every world that installs saveKit has them:
- **How to save player progress with saveKit**: what the kit is and how its pieces fit, saving and loading, the four ways of saving and when to pick each, profiles, levels, XP and unlocks, upgrading old saves, the save slot and load screens, and what each player's machine can change in multiplayer.
- **Example: save slots, level unlocks and a Continue button**: from an empty world to a small level-based game with three save slots, levels that unlock one after another and a Continue button on the title screen, with saveKit and menusKit from ZeroMind.
Open them any of these ways:
| Where | How-to guide | Example guide |
|---|---|---|
| The editor's **Docs** panel: type in its search box, then pick the entry under SAVEKIT | `save-player` | `save-slots` |
| The shell | `zero guides read save-player-progress` | `zero guides read save-slots-level-unlocks-continue` |
| An agent's `guides` tool, `path` = | `save-player-progress` | `save-slots-level-unlocks-continue` |
| The files | [documentation/save-player-progress.guide/guide.md](documentation/save-player-progress.guide/guide.md) | [documentation/save-slots-level-unlocks-continue.guide/guide.md](documentation/save-slots-level-unlocks-continue.guide/guide.md) |
`man` does not open them yet, and ZeroMind search does not list them yet (see Known limits).
## First example
Install saveKit into a new world, then replace the contents of the main scene's entrypoint (`/source/scenes/main.scene/entrypoint.luau`) with this and press Play:
```lua
local Save = require("saveKit.save")
-- onLoad runs when the scene starts in play.
function onLoad()
Save.setup({ mode = "profile", curve = "steady" })
-- A button that gives 40 XP each time it is pressed.
ui.registerScreen("xpButton", {
type = "button",
props = { text = "+40 XP", onClick = "gainXP" },
style = { position = "absolute", left = 24, top = 24, width = 140, height = 48, fontSize = 20 },
}, 1000)
ui.showScreen("xpButton")
end
-- Every button press in this scene lands here.
function onCallback(id: string)
if id == "gainXP" then
Save.addXP(40)
end
end
```
Press **+40 XP**: the XP bar in the bottom-left corner fills, and on the third press you reach level 2. A ribbon says so, the save happens by itself and a small "Saved" badge appears. Stop and press Play again, or leave the world and come back: you are still level 2 with your XP. Nothing else is needed. saveKit starts its own host the first time it is used in play, and menusKit (which draws the looks) comes with it.
## Styles
Every style works through the same calls. A world switches between them by changing one setting, for example `Save.setup({ mode = "slots" })`, and nothing else in its code.
### Ways of saving (`mode`)
| `mode` | What it is | Saves | On death (`Save.died()`) | Suits |
|---|---|---|---|---|
| `profile` | One automatic profile per player. | By itself: a few seconds after any change, and at once on level up, unlock, checkpoint and finished level. A reload or a closed browser tab loses nothing. | Counts a death; nothing is lost. | platformer, party, shooter, open-world, sandbox, casual, social |
| `slots` | Three save slots the player picks from: new game, load, copy and delete. The picker opens by itself until a slot is chosen. | By itself, into the chosen slot (same triggers as `profile`). | Counts a death; nothing is lost. | rpg, adventure, story, metroidvania, puzzle; shared devices |
| `checkpoint` | Saves only when the player reaches a checkpoint (`Save.checkpoint`). | At checkpoints only (and `Save.save()` if the game calls it). | Puts the profile back to what the last checkpoint saved. Leaving without a checkpoint loses what happened since. | platformer, obstacle course, horror, survival, soulslike, action |
| `roguelite` | Runs. A run's level and XP are lost when the player dies or starts a new run; unlocks and meta currency stay forever. | By itself (same triggers as `profile`), and when a run ends. | The run ends: level and XP go back to the start, 10% of the run's XP is banked as meta currency, unlocks and currency are kept. | roguelite, roguelike, arena, wave survival, deckbuilder, dungeon |
Each style keeps its own save, so switching style never mixes one style's data into another's. Aliases: `auto`, `single`, `automatic` (profile); `slot`, `saveslots` (slots); `checkpoints` (checkpoint); `roguelike`, `runs`, `run` (roguelite).
### Levelling curves (`curve`)
A curve says how much XP each level costs. The level is always worked out from the player's total XP, so a world that changes curve re-reads everyone's level from their XP.
| `curve` | Rule | XP for level 1→2, 2→3, … 10→11 | Total XP to reach level 5 / level 10 | Top level |
|---|---|---|---|---|
| `steady` | 100 XP for every level. | 100, 100, 100, 100, 100, 100, 100, 100, 100, 100 | 400 / 900 | 50 (4,900 XP) |
| `steep` | The first level costs 100 XP; each level after costs 40% more, rounded to the nearest 10: `round(100 × 1.4^(n−1) / 10) × 10`. | 100, 140, 200, 270, 380, 540, 750, 1,050, 1,480, 2,070 (then 2,890, 4,050, …) | 710 / 4,910 | 50 |
| `quadratic` | The XP from level *n* to *n*+1 grows with the square of *n*: `25 × n² + 75`. | 100, 175, 300, 475, 700, 975, 1,300, 1,675, 2,100, 2,575 (then 3,100, 3,675, …) | 1,050 / 7,800 | 50 (1,014,300 XP) |
| `custom` | Your own table: entry *n* is the XP from level *n* to *n*+1. The table's length sets the top level (length + 1). | with the default table `{ 50, 120, 250, 400, 600, 850, 1200, 1600, 2100 }`: 50, 120, 250, 400, 600, 850, 1,200, 1,600, 2,100 | 820 / 7,170 | 10 with the default table |
```lua
Save.setup({ curve = "custom", curveTable = { 50, 120, 250, 400, 600 } }) -- 6 levels
Save.setup({ curve = { 80, 160, 320 } }) -- a table is a custom curve too
Save.setup({ curve = "steady", maxLevel = 20 }) -- any curve can be capped lower
```
`steep` is exponential: it grows by the same 40% every level, so it starts gentler than `quadratic` and ends much steeper (level 20→21 costs 59,760 XP on `steep` and 10,075 on `quadratic`).
Aliases: `flat`, `linear`, `even` (steady); `steeper`, `exponential` (steep); `square`, `squared`, `polynomial` (quadratic); `table`, `own` (custom).
### Progression screens (`screens`)
Every screen has several presentations. Pick them with `Save.setup({ screens = { bar = "ring", banner = "toast" } })` or `Save.setScreens{...}`. `false` turns a HUD screen off.
| Screen | Presentations (first is not always the default) | Default | Suits |
|---|---|---|---|
| Level-up banner (`banner`) | `celebration` big full-screen burst with the new level on the look's panel (2.6 s) · `ribbon` a ribbon across the upper third (2.2 s) · `toast` a small card at the top right (2 s) · `false` | `ribbon` | celebration: rpg, party, kids · ribbon: adventure, platformer · toast: shooter, racing, competitive |
| XP bar (`bar`) | `thin` slim full-width line along the bottom · `segmented` ten blocks with a level badge, bottom left · `ring` a ring around the level number, top left · `false` | `segmented` | thin: shooter, open-world · segmented: platformer, arcade, kids · ring: action, mobile, roguelite |
| Unlock grid (`unlocks`) | `grid` tiles with icons, locked ones show a lock and what earns them · `list` rows with requirement and progress bar | `grid` | grid: cosmetics, party · list: achievements, rpg |
| Profile card (`card`) | `full` name, title, level ring, XP, unlocks and play stats · `badge` a compact nameplate | `full` | full: rpg, lobby · badge: shooter, scoreboard |
| Save slot picker (`slots`) | `cards` three cards side by side · `list` three rows (always used on narrow screens) | `cards` | cards: rpg, story · list: mobile, puzzle |
| Saved indicator (`saved`) | `badge` disk icon and "Saved" bottom right · `text` "Progress saved" and the reason at the top · `false` | `badge` | any |
The unlock grid, profile card and slot picker open as panels: `Save.showUnlocks()`, `Save.showProfile(player?)`, `Save.showSlots()`, `Save.hidePanel()`.
The XP bar stays on screen the whole game, so saveKit states where it is: its measured rect is listed in `ui.safeArea().controls` under the owner `saveKit_hud` (stated with `ui.setControlRegions`, restated whenever the bar moves, resizes or turns off). A game's own HUD reads it there to keep clear of the bar on any screen size, and other screens' anchors keep clear of it by themselves. The `segmented` bar also keeps clear of others: on a screen narrower than its 390 points (a phone held upright) its segments narrow so the whole bar fits on screen, and when its bottom-left corner lands on a rect another screen states (the engine's touch buttons, a kit's button column, a level's panel) it steps up above it. Where nothing is in the way it stands exactly where it always has. The HUD draws on UI layer 900 (`Screens.HUD_LAYER`) and panels on 940 (`Screens.PANEL_LAYER`): put something that has to show over the bar and the level-up banner, such as notice signs over people's heads, between the two.
### Looks
saveKit draws every screen in menusKit's look, so a game that uses menusKit looks the same everywhere: `scifi`, `fantasy` (parchment), `cartoon`, `pixel` (retro), `minimal`, `military`, `horror`, `cozy` (menusKit's aliases work too). Each screen takes the look's colours, fonts and panel frame. `Save.setTheme("pixel")` restyles every saveKit screen **and** every menusKit menu at once, and a game calling `Menus.setTheme` restyles saveKit's screens too.
### The list, for a world or another agent
```lua
local all = Save.catalogue() -- { version, modes, curves, screens, themes, events }, each entry with tags
local best = Save.match({ genre = "roguelike" }) -- ranked: { kind, name, label, score }, best first
local screens = Save.match({ kind = "screen", size = "small" })
```
Each mode carries `tags.genres`, `tags.session`, `tags.players`, `saves` and `death`; each curve `rule`, `firstCosts` and `tags.pace`/`tags.genres`; each screen presentation `tags.size`, `tags.mood`, `tags.fits`; each look menusKit's own mood/genre/input tags.
## Install
Install **saveKit** from ZeroMind (search "saveKit", home world *Save Point: Profiles, Levels and Unlocks Kit*), or in one call:
```lua
tools.use("zeromind", "installAsset", "6a0ed0da-0111-457f-b61e-d4040eaee34a") -- saveKit
```
It brings **menusKit** (and menusKit's controlsKit) along as dependencies, and nothing else. Any folder works: the kits find each other by name (`saveKit.save`, `menusKit.themes`).
Without code, add the **`saveKit.SaveSetup`** component to any entity: its inspector picks `mode`, `curve`, each screen's presentation and the look, and changing a field while playing switches at once.
## What a game calls
```lua
local Save = require("saveKit.save")
Save.addXP(25, "quest") -- any reason word; returns levels gained
Save.kill() -- kills +1 and 25 XP (setup xp.kill)
Save.coin(5) -- coins +5 and 5 XP each (xp.coin)
Save.finishLevel("level_2") -- levels +1, 100 XP (xp.level) and a save
Save.checkpoint("cp_3", "Bridge") -- remembered, 10 XP the first time, and a save in every style
Save.died() -- what dying means in the current style (see Styles)
Save.newRun() -- roguelite: give up the run
Save.unlock("red_hat") -- unlock anything by id (saves)
Save.event("boss") -- grants unlocks that have event = "boss"
Save.addCurrency(10); Save.buy("lucky_charm") -- meta currency, kept through roguelite deaths
Save.set("loadout", { "sword" }); Save.get("loadout") -- the game's own saved fields
Save.save() -- save now, whatever the style
```
Reading: `level()`, `xp()` (into the level), `xpToNext()`, `progress()` (0..1), `totalXP()`, `view()`, `currency()`, `stat(name)`, `stats()`, `isUnlocked(id)`, `unlocks()`, `lastCheckpoint()`, `data()`, `profile()`, `status()`, `lastSaved()`.
## What is saved
One record per save, in the player's own data (`runtime_data.player(id)`), under `saveKit/<namespace>/<style>` (`saveKit/main/profile`, `…/checkpoint`, `…/roguelite`, `…/slot1` to `slot3`, plus `…/activeSlot`):
| Field | What |
|---|---|
| `version` | the game's save layout version (see below); `kit` is saveKit's own layout number |
| `totalXp`, `level`, `best` | XP and level (this run, in roguelite), best level and XP ever |
| `unlocks` | `{ [id] = os.time() when unlocked }` |
| `stats` | `playTime` (s), `sessions`, `deaths`, `kills`, `coins`, `levels`, `checkpoints`, `runs`, `xpEarned`, and any the game adds |
| `currency` | meta currency |
| `checkpoint` | `{ id, label, at }` |
| `game` | the game's own fields (`defaults`, `Save.set`) |
| `created`, `saved`, `saves` | timestamps and save count |
A public **card** (`saveKit/card`: name, level, XP, title, unlock count, a few stats) is written beside it for other players to read.
### Unlocks
Without an `unlocks` list a world gets nine to earn at once: Bronze Frame (level 2), Spark Trail (3), Silver Frame (5), Title: Veteran (8), Gold Frame (10), First Blood (1 kill), Collector (50 coins), Pathfinder (3 checkpoints), Finisher (1 finished level). A game passes its own:
```lua
Save.setup({ unlocks = {
{ id = "red_hat", name = "Red Hat", icon = "star", level = 3 }, -- by level
{ id = "sharpshooter", name = "Sharpshooter", stat = "kills", atLeast = 50 }, -- by stat
{ id = "boss_slayer", name = "Boss Slayer", event = "boss" }, -- by Save.event("boss")
{ id = "lucky_charm", name = "Lucky Charm", cost = 25 }, -- bought with Save.buy
} })
```
Icons are menusKit's icon names (`star`, `starFill`, `trophy`, `heart`, `flag`, `lock`, `profile`, …). An id starting `title_` becomes the player's title on their card.
## Versions and upgrading old saves
Games change. Give your save layout a version and, when you change it, add a function that upgrades a save from the version before. A returning player's old save is upgraded step by step when it loads, never lost or broken:
```lua
Save.setup({
version = 2,
defaults = { coins = 0, cosmetics = { hat = "none", trail = "none" }, records = { bestTime = 0, bestScore = 0 } },
migrations = {
[1] = function(save) -- version 1 -> 2
local g = save.game
g.coins = g.gold or 0 -- "gold" was renamed "coins"
g.cosmetics = { hat = g.hat or "none", trail = "none" }
g.records = { bestTime = g.bestTime or 0, bestScore = 0 }
g.gold, g.hat, g.bestTime = nil, nil, nil
return save
end,
},
})
```
- `setup` refuses a `version` without a migration from every older number.
- The upgraded save is written straight away, and the save as it was is kept beside it at `<key>.v<old>` (`saveKit/main/profile.v1`). `Save.on("migrated", fn)` hears it; `Save.migration()` returns `{ from, to, steps }`.
- Fields added to `defaults` reach old saves without a migration.
- A migration that errors or returns nothing leaves the stored save untouched and the profile read-only for that session (`status() == "failed"`), so a bug in an update never destroys anyone's progress.
- A save from a **newer** build than the one running is read but never overwritten (`status() == "newer"`, event `newerSave`).
- A stored value that isn't a save at all is set aside at `<key>.broken` and a new profile starts (`recovered`).
The showcase does this for real: step on **Write a v1 save** (saveKit running the version 1 layout writes a save into your own data) and **Read it with v2**; the board shows the stored version 1 record and the upgraded version 2 record side by side.
## Multiplayer
- **Each profile is its player's own.** Every machine loads, changes and saves only its own player's profile, in that player's own `runtime_data` store. The engine refuses a write to another player's store ("runtime_data: you can only write your own player's data"), so no machine, modified or not, can change someone else's profile. The showcase's **Tamper test** pad tries it and shows the refusal.
- **Everyone can read everyone's card.** `Save.players()` lists every connected player with their card; `Save.cardOf(player)` takes a user id, peer id or avatar entity; `Save.showProfile(player)` opens it read-only. Cards from other players are checked before use (types, lengths), so a malformed card can't break your screen.
- **Code that runs on every machine** uses `Save.grant(player, xp, reason)`: it takes effect only on that player's own machine and returns `false, "not yours…"` everywhere else, so a kill seen by all machines gives XP exactly once. `Save.isMine(player)` answers the same question.
- `Save.addXP`, `kill`, `coin`, and the rest always act on the local player.
- Pads (`saveKit.SavePad`) test only the local player against themselves, so stepping on one changes your profile and nobody else's.
- A player's saved data can reach their machine a moment after they join. saveKit waits up to 2.5 s (`loadWait`) for it before starting a new profile, keeps whatever the player earned meanwhile and adds it, exactly once, to the save when it arrives, or to the new profile when none arrives. The same holds right after switching to another `namespace` or `mode`. A guest with no identity plays on in memory; saves then fail with a reason and the indicator says "Not saved".
### Profiles and accounts
A profile belongs to an **account**, not to a machine or a session. saveKit stores it in that account's own player data for this world (`runtime_data.player(<account id>)`), so the same person gets the same profile on the desktop app, in a web browser and on any other machine they sign in on. Two different accounts always have two separate profiles, even on the same computer.
Two sessions signed in to **the same account** at the same time (two browser tabs, the desktop app and a browser, two engines) are one player to the platform. They share one identity and one store, so they share **one** profile:
- both load the same saved profile when they start;
- when one session saves, the other takes that newer copy as long as it has no unsaved changes of its own;
- if both change the profile before either save reaches the other, the save written last wins, and the other session's changes since its own last save are lost;
- each session draws its own HUD, but other players see one card for that account, the one saved last.
saveKit can't tell two sessions of one account apart (open engine issue #14448, see Known limits). To test two players, sign in with two different accounts.
## Events
`Save.on(event, fn)` returns a handle for `Save.off(handle)`; an unknown name raises. A handler added during play ends when play stops.
| Event | `info` |
|---|---|
| `xp` | `amount, reason, level, xp, need, totalXp` |
| `levelUp` | `level, from, unlocked` (names) |
| `unlock` | `id, name, rule, why` (`level`, `stat`, `event`, `manual`, `bought`) or `atLoad` |
| `stat`, `currency` | `name, value, amount` / `value, amount` |
| `checkpoint`, `levelComplete` | `id, label, new` / `id` |
| `died`, `runEnded` | `mode, reverted, checkpoint, banked` / `banked, runXp, runLevel, died` |
| `saved`, `saveFailed`, `saveRefused` | `reason, key, slot, mode, saves` / `reason, error` / `reason, why` |
| `loaded`, `ready`, `migrated`, `newerSave`, `recovered` | `key, mode, slot, status, migratedFrom, fresh` / `status` / `from, to, steps, backup` / `version, reads` / `error` |
| `slot`, `mode`, `theme`, `screens`, `panel` | `action, slot, from` / `mode, from` / `name` / `screens` / `name, open` |
## Other kits
saveKit can link to these kits and needs none of them. Installing saveKit brings none of them along, and a link switches on only when your game hands saveKit the kit in its setup, which it can do only if the kit is installed in your world:
```lua
Save.setup({
mode = "checkpoint",
kits = {
trapline = require("Trapline.api"), -- only the kits your world has
scoreKit = require("scoreKit.core"),
pickups = require("pickupsKit.api"),
},
})
```
| Kit (`kits` key) | Pass | What happens |
|---|---|---|
| **Trapline** (`trapline`) | `require("Trapline.api")` | Reaching a Trapline checkpoint calls `Save.checkpoint` (a checkpoint save); losing a life calls `Save.died`. |
| **scoreKit** (`scoreKit`) | `require("scoreKit.core")` | Points the local player scores become XP: 10% by default (`bridges = { scoreToXp = 0.1 }`), fractions carried over. |
| **pickupsKit** (`pickups`) | `require("pickupsKit.api")` | Taking an XP orb gives its XP; coins count as `Save.coin`. |
- **Leave out a kit your world does not have.** Nothing else changes: saveKit never looks a kit up on its own, so a world without them logs nothing about them.
- **Why the game passes the kit in.** A kit saveKit loaded by name would be recorded as one of saveKit's dependencies and installed with it everywhere; a name worked out while the game runs would stop a world that uses saveKit from publishing. Passing the kit in keeps saveKit's install to menusKit and controlsKit.
- **Each link acts only for the local player's own events.** scoreKit is listened to in `scoreKit.core`, which carries both the award event and the local player's key.
- **Turning one off:** `Save.setup({ kits = { scoreKit = false } })`, or `bridges = { scoreKit = false }`. A module that is not the kit it is passed as is refused once, with one warning (`require("saveKit.bridges").failures()` says why).
- **What is linked:** `Save.kits()` answers `{ trapline, scoreKit, pickups }`, true for each kit linked. `require("saveKit.bridges").available()` says which of the three are installed in the world (it checks without loading them).
## Setup options
`Save.setup(opts)` can be called any time; only the options given change.
| Option | Default | |
|---|---|---|
| `mode` | `"profile"` | saving style |
| `curve`, `curveTable`, `maxLevel` | `"steady"`, default table, curve's own | levelling |
| `version`, `migrations`, `defaults` | `1`, none, `{}` | the game's save layout |
| `unlocks` | the nine defaults | unlock rules |
| `xp` | `{ kill = 25, coin = 5, level = 100, checkpoint = 10 }` | XP per event |
| `autosave` | `{ interval = 60, afterChange = 3, levelUp = true, unlock = true, checkpoint = true, levelComplete = true }` | autosave triggers: `afterChange` saves that many seconds after the last change (`0` turns it off), `interval` every that many seconds (`0` turns it off); the checkpoint style ignores both |
| `bankRate` | `0.1` | share of a roguelite run's XP banked as currency |
| `namespace` | `"main"` | a separate set of saves (for example per game mode) |
| `screens` | see Progression screens | presentations |
| `hud` | `true` | `false` hides the HUD screens (panels still open) |
| `kits` | none | the other kits to link: `{ trapline = require("Trapline.api"), scoreKit = require("scoreKit.core"), pickups = require("pickupsKit.api") }`; `false` unlinks one (see Other kits) |
| `bridges` | all on, `scoreToXp = 0.1` | turn a linked kit off, and the share of scoreKit points that becomes XP |
| `theme` | menusKit's | the look |
| `loadWait`, `minSaveGap` | `2.5`, `0.5` | seconds to wait for a late save; least time between autosaves |
## Components
- **`saveKit.SaveSetup`**: the whole setup from the inspector (see Install).
- **`saveKit.SavePad`**: a glowing floor pad that does one thing to your own save when you step on it: `xp`, `kill`, `coin`, `currency`, `finishLevel`, `checkpoint`, `died`, `newRun`, `save`, `reset`, `unlock`, `buy`, `event`, `unlocks`, `profile`, `playerCard`, `slots`, `mode`, `curve`, `theme`, `screen`. Fields: `action`, `amount`, `id`, `label`, `radius`, `cooldown`, `color`, `showLabel`, `labelHeight` (stagger neighbouring pads so their labels never overlap).
- **`saveKit.SaveHost`**: spawned by the kit in play; ticks autosaves, draws the HUD and panels, routes their clicks and connects the other kits.
## API
`saveKit.save` (what games use):
- **Setup:** `setup(opts)` (alias `configure`), `config()`, `kits()`, `VERSION`, `MODES`, `CURVES`, `SCREENS`, `EVENTS`, `SLOT_COUNT`.
- **Progress:** `addXP`, `kill`, `coin`, `finishLevel`, `checkpoint`, `died`, `newRun`, `addStat`, `unlock`, `event`, `buy`, `addCurrency`, `set`, `get`, `data`, `reset`.
- **Reading:** `level`, `xp`, `xpToNext`, `totalXP`, `progress`, `view`, `currency`, `stat`, `stats`, `isUnlocked`, `unlocks`, `rules`, `lastCheckpoint`, `profile`, `status`, `isReady`, `mode`, `curve`, `curveName`, `curveTable`, `isDirty`, `lastSaved`, `migration`, `saveKey`.
- **Saving:** `save(reason?)`, `flush()`.
- **Slots:** `slots`, `activeSlot`, `newGame`, `load`, `copy`, `delete`.
- **Other players:** `isMine`, `grant`, `players`, `cardOf`.
- **Screens:** `setScreens`, `screens`, `setTheme`, `theme`, `showPanel`, `showUnlocks`, `showProfile`, `showSlots`, `hidePanel`, `panel`, `toast`.
- **Events:** `on`, `off`.
- **Catalogue:** `catalogue`, `match`.
Functions starting with `_` are for the host and tests.
Supporting modules: `saveKit.curves` (the curves as pure functions), `saveKit.schema` (layouts, `upgrade`, `sanitize`), `saveKit.profile` (rules on one record), `saveKit.catalog` (the tagged list), `saveKit.store` (where saves live; `use` swaps in a stand-in store for tests), `saveKit.screens` (every presentation as a widget tree, for your own UI), `saveKit.bridges` (the links to other kits: `start`, `stop`, `reset`, `active`, `available`, `failures`, `canonical`, `KITS`).
## Tests
`saveKitTests` covers every public call: the curves' exact numbers, layouts and upgrades (missing, failing and newer migrations), each saving style, slots, unlock rules, the public card, refused writes to another player's data, the bridges, the catalogue, every screen in every presentation and look, that the first example in this README runs as written (its button pressed three times reaches level 2, saves, and is still level 2 after a rejoin), and that the version matches in `package.yaml`, this README and the code (88 tests). XP, coins and currency earned while a save is still loading are checked to count exactly once: when no save arrives, when it arrives late, and right after switching save name or style. The bridges are tested with stand-in kits, and one test reads every saveKit source file to check that none names Trapline, scoreKit or pickupsKit, so saveKit works and installs on its own. It saves through a stand-in store, so running it never touches a real player's progress. Run it in edit mode:
```lua
tools.use("tests", "run", { suite = "saveKitTests", onWorker = true })
```
## Showcase
The *Save Point* world opens on a square plaza with every saving style, levelling curve and progression screen on labelled boards facing the spawn, with glowing pads to use each one (move the mouse to look around: saving styles ahead, curves and the pink look pads on the left, the save upgrade, profiles and Trapline on the right, screens, scoreKit and pickupsKit behind): pink pads switch the look, green ones switch style or curve, blue ones give XP, kills and coins, and others reach checkpoints, die, start new runs, open panels and slots. A **Screen gallery** pad shows every presentation of every screen side by side, the **save upgrade** board shows a real version 1 save read by the version 2 layout, **Everyone's profile** lists every player's card with the tamper test, and the **kit stations** run the real Trapline, scoreKit and pickupsKit: touch a Trapline flag or campfire and saveKit saves at that checkpoint, step on a points pad and scoreKit's points turn into XP, walk through pickupsKit's XP orbs and coins and they give XP and coins. Those three kits are installed in the Save Point world for the showcase only; saveKit itself needs none of them.
## Changelog
- **1.3.18**: the `Saved` flash is stated to other screens while it shows, the way the XP bar and the level-up banner are: its rect is in `ui.safeArea().controls` under `saveKit_hud` (widget id `sk:saved`), so another kit's notice signs or prompts keep off it instead of drawing over it. Nothing else changes.
- **1.3.17**: the `Saved` badge stands in the bottom-right corner when that spot is free, as before; otherwise it takes the nearest free spot above it on the right edge, then on the left edge, clear of every rect another screen states with `ui.setControlRegions` and of this HUD's own XP bar (on a touch tablet it sat on the engine's Jump button, and on a phone held upright on the XP bar). With no free spot anywhere the badge is not drawn: a short `Saved` is not worth covering a button or a panel. Found in Dockhands.
- **1.3.16**: the `segmented` XP bar fits on a phone held upright and never covers a button: it narrows its segments to the screen's width (it ran 18 points off the right edge of a 390-point screen) and steps up above any rect another screen states with `ui.setControlRegions` that its corner would land on (on a portrait phone it covered the engine's Jump button and a kit's Act button). Landscape phones, tablets and desktops are unchanged. Found in Dockhands.
- **1.3.15**: the level-up ribbon keeps clear of what other screens state with `ui.setControlRegions` (a level's objectives panel, a kit's touch buttons): it narrows to the widest free stretch of its band, or moves down below what is in the way when that stretch is too narrow to read. While it shows, its rect is stated in `ui.safeArea().controls` beside the XP bar's (owner `saveKit_hud`), so things drawn over the picture, such as notice signs over people's heads, can step clear of it. New `Screens.BANNER_ID`. Found in Dockhands, where the ribbon covered the objectives and the guards' notice signs sat on it.
- **1.3.14**: the XP bar states its rect in `ui.safeArea().controls` (owner `saveKit_hud`, via `ui.setControlRegions`), so other screens and a game's own HUD can keep clear of it on phones and desktops. Before, the bar told nobody what part of the screen it covered, and things drawn on a lower layer ended up underneath it. New `Screens.BAR_ID`.
- **1.3.13**: built against menusKit 1.3.19, the first menusKit whose files all name one controlsKit release (1.3.17 and 1.3.18 still named older controlsKit releases in MenusHost and themes, so an install landed three controlsKit copies). No saveKit behaviour changed.
- **1.3.12**: built against controlsKit 1.3.2 and menusKit 1.3.17, the first releases of those two that install as a single copy each (controlsKit 1.3.1 still pointed some of its own files at 1.3.0, so every kit on it landed two controlsKit releases). The test suite names saveKit modules relatively. No saveKit behaviour changed.
- **1.3.11**: built against menusKit 1.3.16 (was 1.3.13), the release inventoryKit, questKit, dialogueKit, economyKit and arpgKit move to, so one world can install all of them with one menusKit and one saveKit. The world also moved to the current engine library. No saveKit code changed.
- **1.3.10**: built against the current controlsKit (1.3.1) and menusKit (1.3.13), the releases economyKit, inventoryKit and navUiKit use, so a world that installs saveKit beside them holds one controlsKit and one menusKit instead of older copies beside the current ones. The world also moved to the current engine library. No saveKit code changed; the suite runs 88 of 88.
- **1.3.9**: built against controlsKit 1.2.8 and menusKit 1.3.11. 1.3.8 installed, but a fresh world still held three controlsKit releases: a dependency on controlsKit resolves to the release controlsKit's world ships, so only the newest one can be shared. Every package that ships with sideScrollerKit now moves to 1.2.8 together. Code unchanged.
- **1.3.8**: installs again, on one controlsKit release. This world held its own copy of controlsKit (old 1.0.1 files over the release menusKit brings), and every install of saveKit failed reading a controls module ZeroMind never received. The copy is gone (controlsKit needed none of it), and saveKit is built against menusKit 1.3.10 and the published controlsKit 1.2.4, the release the kits it ships beside (twoDKit, sideScrollerKit) are built against. Code unchanged.
- **1.3.7**: states menusKit at exactly 1.3.6, so an install no longer takes menusKit 1.3.7 to 1.3.9, whose controlsKit copy ZeroMind cannot serve. Code unchanged.
- **1.3.6**: installs again. menusKit's newest commit in its world (a merged pull request) references a controlsKit build ZeroMind never received, so an install of saveKit 1.3.4 or 1.3.5 failed reading it. saveKit now holds menusKit at the published 1.3.6 release. Code unchanged.
- **1.3.5**: installs again. 1.3.4 was published with a locally changed copy of controlsKit in its world, so an install asked ZeroMind for a controlsKit build it never received and failed. 1.3.5 holds controlsKit exactly as published. Code unchanged.
- **1.3.4**: built against controlsKit 1.2.4 like the kits it ships with, so a world on 1.2.4 can take the update. menusKit stays at 1.3.6. Code unchanged.
- **1.3.3**: built against menusKit 1.3.6, so an install no longer carries older copies of two menusKit modules. Code unchanged.
- **1.3.2**: the README names the current version and carries the 1.3.1 entry (1.3.1 shipped without them). Code unchanged.
- **1.3.1**: with the HUD off (`hud = false`) saveKit draws no screen at all. It used to register an empty full-screen root on its HUD layer, which took every click and drag meant for the game's own UI beneath it.
- **1.3.0**: two guides inside the package, and a check on today's engine. saveKit's own code is unchanged from 1.2.1 (only its version number moved).
- **Two guides ship with the kit** in `documentation/`: *How to save player progress with saveKit* (the ideas: saving and loading, the four ways of saving and when to pick each, profiles, levels, XP and unlocks, upgrading old saves, the save slot and load screens, and what each player's machine can change in multiplayer) and *Example: save slots, level unlocks and a Continue button* (an empty world to a four-level game with three save slots, levels unlocking in order and a Continue button, using saveKit and menusKit from ZeroMind). Every step of the example was done and seen working in a fresh world. The guides link to each other and the README's new Guides section says how to open them.
- **Checked on today's engine.** saveKit installed on its own into a fresh world (it brought menusKit and controlsKit and nothing else), the first example above ran as written (three presses of +40 XP reached level 2 with 20 XP and saved by itself), and the level was still there after the world was closed and opened again. The tests passed twice in the Save Point world and once in the fresh world (88 of 88 each time). Nothing needed fixing.
- **Known limits** name the open issues that apply today.
- **The store listing and the world description** say 1.3.0 and mention the guides.
- **1.2.1**: a tidy showcase, and a store listing and world description that match the kit. saveKit's own code is unchanged from 1.2.0 (only its version number moved).
- **The store listing and the world description are corrected.** The world's description still began "saveKit 1.1.0" and its store page described the kit links as working just by having the kits installed. Both now say 1.2.1 and describe what the kit does today: autosave also a few seconds after any change, the steep curve growing 40% a level, the Trapline, scoreKit and pickupsKit links switching on only when a game passes those kits to `Save.setup({ kits = ... })`, and installing saveKit bringing menusKit and none of the other kits. The store page also says where each station stands in the showcase.
- **The Save Point showcase is laid out on a grid you can read from the spawn.** Every station faces the spawn from one of four sides of a square plaza (ahead: saving styles; left: curves and looks; right: save upgrade, everyone's profile and Trapline; behind: screens, scoreKit and pickupsKit). Each row of pads has its labels on its own line, so no label, board or pickup covers another from the spawn, whichever way the camera turns. scoreKit's counter moved to the bottom-right corner, over open floor. The section headings (saving styles, curves, screens) lie flat on the wall with clear space above and below, and every board has a single title. The curve, saving style and profile boards break their text into short lines so it is large enough to read from the spawn, and the tamper test reports its result in one plain sentence ("changing another player's profile was refused: only a player's own machine can change their profile") instead of the engine's error text.
- **1.2.0**: installs on its own, XP counted once, readable showcase.
- **Installing saveKit brings only menusKit and controlsKit again.** 1.1.0 looked the other kits up by name, and because they were installed in the world saveKit is published from, the install recorded them, and their own dependencies, as saveKit's: eleven extra packages. saveKit now names no other kit. A game links one by passing it in `setup({ kits = ... })`, and only then does that link switch on (see Other kits). New: `Save.kits()`.
- **XP earned while a save is loading counts once.** When no save arrived in time (a new player, or right after switching save name or style), what was earned while waiting was added twice: 70 XP became 140. Fixed, with tests for each case.
- **The card and the unlock grid count the same unlocks**: every unlock rule, plus anything unlocked that no rule names.
- **`SavePad.labelHeight`**: how high a pad's label floats, so neighbouring pads can stagger theirs.
- **Tests.** 88 tests (5 new: XP earned while loading with no save, with a late save and after a switch; saveKit on its own; kits linked only when passed in).
- **1.1.0**: a quadratic curve, kit links that work and stay quiet.
- **New curve `quadratic`**: `25 × n² + 75` XP from level *n* to *n*+1 (100, 175, 300, 475, 700, …). `SaveSetup` offers it too.
- **scoreKit points give XP again.** saveKit listened on `scoreKit.score`, which has no `localKey`, so it could not tell which awards were yours and gave XP for none of them. It now listens on `scoreKit.core`, which has both.
- **No log spam without a kit.** The links find each kit by package name (`~pickupsKit.api`), which also reaches a kit installed as another kit's dependency. A kit that is installed but fails to load is warned about once and not retried every few seconds. New: `bridges.failures()` and `bridges.reset()`.
- **README:** how profiles belong to accounts and what happens when two sessions share one account; known limits name the open engine issues.
- **Tests.** 83 tests (4 new: the quadratic curve, a broken or missing kit tried once, scoreKit wired through its core, Trapline and pickupsKit wired to their events).
- **1.0.2**: `Save.theme()` checks quietly that menusKit is there before loading it, so a world unloading menusKit logs no error. Install checked in a clean private world: the first example ran as written and the level came back in a fresh session.
- **1.0.1**: nothing is lost on a reload, and setup keeps unsaved progress.
- **Saves a few seconds after any change** (`autosave.afterChange`, 3 s). Before, XP gained without a level-up waited for the 60-second timer or a clean exit, so a browser reload or a closed tab could lose up to a minute of it.
- **`setup` keeps unsaved progress.** Calling `setup` again with the same `version` and `migrations` used to reload the save from the store and drop anything not yet saved. It now reloads only when the layout really changes (saving first), or when the loaded save had been refused as newer or not upgradable.
- **Every play session loads fresh.** The host now loads the player's save in its `start()` (play only), so a profile read in edit mode, for example by an editor board before the game's `setup` ran, is never carried into play. Each session is counted once and the count is saved.
- **Late fonts on the web player.** The host re-registers the look's fonts while they are missing and redraws when they arrive, so the HUD uses the look's fonts in a game that never opens a menusKit menu.
- **Tests.** 79 tests (5 new: save after a change, setup keeping progress, one count per session, the first README example run as written with only saveKit, and one version in package, README and code).
- **1.0.0**: first release.
## Known limits
Each of these is an open issue in the engine or in ZeroMind, not in saveKit, and each says where it applies.
- **#14448: two sessions on one account are one player.** Sessions signed in to the same account (two browser tabs, the desktop app and a browser) are one player identity with one player data store, so they collide as one player and share one profile: both load the same saves, and when both change it before either save reaches the other, the save written last wins (see Profiles and accounts). Two-player saves need two accounts.
- **#20750: frame time spent on multiplayer sync.** The engine spends part of every frame keeping multiplayer state in step. saveKit adds little to it (it writes only the local player's own data and reads other players' cards), but in a busy world that sync is part of the frame budget your game shares.
- **#19849: long waits.** Some engine calls take a long time to come back: running the kit's tests, installing, and switching worlds can run on in the background for several seconds or more. Wait for them to finish before judging the result.
- **#20946: checking the world on the web build happens outside your session.** The browser build can't be started from an editor session, so a check that saving works in a web browser has to be done by opening the world in a browser tab yourself.
- **#21420: installs with several dependencies are slow.** Installing saveKit brings menusKit and controlsKit; linking Trapline, scoreKit or pickupsKit means installing those too, and each brings its own dependencies. Install one kit per call and let each finish.
- **#19258: the ZeroMind description can lag one version behind after a release.** Right after a new version is published, the kit's description on ZeroMind may still describe the version before. The README in the installed package is always current.
- **ZeroMind#3099: guides inside a package don't show up in ZeroMind search yet.** The two guides install with saveKit and open inside the engine (see Guides), but searching ZeroMind doesn't find them yet.
- **#22286, #22291 and #22315: opening and searching a package's guides only works in some forms.** In this release, the Docs panel's search box, `zero guides read <name>` and the `guides` tool with the guide's short name open them; `man <name>` does not, and neither does the guide's dotted identity in the `guides` tool. The Guides section lists the forms that work.
# scoreKit 1.4.10
Scores, combos, multipliers, star ratings, grade letters and leaderboards for any Zero game, in one package. A game writes one line, `Score.add(player, 10)`, and the player sees it straight away: the number rolls up, a "+10" pops where it was scored, quick points build a combo, the multiplier climbs to x5, and the end of the round brings a rating card and a place on a leaderboard that is still there tomorrow.
- **13 score displays, 5 popup styles, 6 leaderboard views, 4 end-of-round screens, 5 looks.** Every style works off the same data. Changing one setting swaps one for another, and nothing else in your code changes.
- **Multiplayer by design.** One machine (the *keeper*) runs the rules and writes the board. Every player sees the same scores and the same board, and each player gets their own display, popups and results.
- **Builds on MatchFlow, navUiKit and pickupsKit.** Rounds are MatchFlow matches: scores count in them and players are ranked when a round ends. Notifications ("x4 COMBO", "New personal best!") are navUiKit toasts. pickupsKit's coins, gems and hazards score through `ScorePickups`, once per grab.
## Guides
Two guides ship inside this package, in `scoreKit.package/guides/`, and install with it:
- **[How to add a score and combo system to my game](scoreKit.package/guides/how-to-add-a-score-and-combo-system-to-my-game)**: the how-to. What the kit is and what to do first, adding points and "+N" popups, how combos and multipliers build and break, penalties and bonuses, star ratings and grades, leaderboards that survive a restart (top scores, best times, personal bests, seasons), swapping every style with one setting, and how scores work per player in multiplayer.
- **[Make an arcade game with a score, combos and a leaderboard](scoreKit.package/guides/make-an-arcade-game-with-a-score-combos-and-a-leaderboard)**: the example. A brand-new world becomes a two-player coin round with scoreKit, MatchFlow and menusKit: quick pickups build a combo, the round ends with stars and a grade, the result goes onto a top-10 leaderboard that is still there after a restart, and there is a title screen and a pause menu.
Open one with the `guides` tool by the path in its link (`scoreKit.package/guides/<name>`), or in the editor's Docs panel under scoreKit.
## Install
One install: search ZeroMind for "scoreKit" and install it from the ZeroMind panel, or ask your agent to run `zeromind_install` with `guid = a1e6c665-2332-4886-954e-06c028e86b19`. Your world gets `/source/scoreKit.package`, and the kits it builds on come with it under `/source/deps/`: MatchFlow (rounds), navUiKit (toasts) and pickupsKit (pickups that score, with the SecondWind, Lifeline, juiceKit and controlsKit it uses). There is nothing else to set up. While the files land, the log can show passing "waiting for content it requires" lines.
## First example
Your world needs a scene with a player. A brand-new world already has one: `scenes/main.scene`, with a ground, lights and the default player, and an `entrypoint.luau` that holds only comments. (A world that has no scene yet gets the same one from `tools.use("scene", "create", "main", "player", { startup = true })`.) Replace everything in `scenes/main.scene/entrypoint.luau` with this:
```lua
local Score = require("scoreKit.score")
local jump -- the jump handler, kept so it can be removed when play stops
function onLoad()
local controls = asset.resolve("@builtin::inputMaps.default", "inputMap"):activate()
jump = controls.jump:onPressed(function()
Score.add(nil, 10) -- nil = the player on this machine
end)
end
function onUnload()
-- remove the handler when play stops: the engine keeps it otherwise (#22432)
if jump then jump:Disconnect() end
jump = nil
end
```
Press **Play** and jump (Space, or the jump button on a phone or a gamepad). The arcade counter appears top-left and rolls up by 10, and a "+10" pops under it. Jump three times quickly and the third jump is worth 20 (x2). Keep it going and you reach x3 at 6 jumps, x4 at 10 and x5 at 15, with an "x3 COMBO" toast along the way. Wait more than 2.5 s and the combo breaks.
Stop and press Play again and the score starts from 0: every play session starts a fresh score, combo and round, and only the boards keep scores between sessions. Each jump still counts once, because `onUnload` removes the jump handler when play stops. Leave `onUnload` out and the engine keeps the old handler attached (#22432, see Known limits): from the second Play on, each jump counts twice, then three times in the third Play, and so on.
That's everything you need on one machine. With two or more players, scoring is keeper-only by default, so a jump on another player's machine is not counted. Score from code on the keeper (a coin it sees taken), or set `acceptRemote = true` to let each machine report its own player's points (see "Who can write the board"). The first `Score.add` creates the synced `ScoreKit` entity that keeps the score. You can also place it yourself to set its options:
```lua
-- in a scene's build.luau, inside content()
local kit = entity.spawnSynced("ScoreKit")
kit.component.add(asset.resolve("scoreKit.ScoreKit", "component"), { display = "comboMeter", look = "fantasy", board = "level1" })
```
From a coin, a kill or a checkpoint, pass whatever touched it. scoreKit walks up from the touching entity to the player's body:
```lua
Score.add(touchingEntity, 10, { at = coin, reason = "coins" }) -- "+10" pops at the coin; "coins" is a results line
Score.add(attackerBody, 100, { reason = "kills" })
Score.penalty(playerBody, 25) -- a hit taken: -25, and the combo breaks
Score.bonus(playerBody, "No damage", 500) -- a named bonus line, never multiplied
Score.breakCombo(playerBody, "fell")
```
## Combo rules
These are the exact rules, with the defaults. They are written so that you can balance a game around them.
1. **A hit is any `Score.add` with a positive amount**, unless it is passed `combo = false`.
2. **The combo** counts hits in a row. A hit that comes at most **2.5 s** (`window`) after the previous hit adds 1 to the combo. A hit that comes later, or after the combo broke, starts it again at 1. A gap of exactly `window` still counts.
3. **The multiplier** is 1 plus the number of `steps` the combo has reached, and never above `maxMultiplier`. With the default `steps = { 3, 6, 10, 15 }` and `maxMultiplier = 5`:
| combo | 1 to 2 | 3 to 5 | 6 to 9 | 10 to 14 | 15 and up |
|---|---|---|---|---|---|
| multiplier | x1 | x2 | x3 | x4 | x5 |
`every = n` replaces the steps with a uniform step: x2 at n hits, x3 at 2n, and so on up to `maxMultiplier`.
4. **The hit that reaches a step is already multiplied.** The 3rd hit is the first worth double. Points awarded = amount × multiplier, rounded to the nearest whole number with halves rounding up (`round = false` keeps fractions).
5. **The combo breaks** when:
- **time runs out**: more than `window` seconds pass with no hit. The keeper checks this every frame, so a combo breaks on time even if no more points come.
- **the game says so**: `Score.breakCombo(player)`.
- **a penalty**: a negative amount always breaks the combo, unless `breakOnPenalty = false`.
With `decay = "reset"` (the default) a break sets the combo to 0 and the multiplier to x1. With `decay = "step"` a timeout drops one multiplier step instead: the combo goes to that step's start (x4 → combo 6, x3) and gets a fresh window. If no hit comes, it keeps stepping down. `breakCombo` and penalties always reset.
6. **Penalties** (negative amounts) are never multiplied.
7. **`combo = false`** points are not a hit: they don't grow the combo or refresh its window, and they are not multiplied (pass `multiply = true` as well to multiply them by the current multiplier). **`multiply = false`** keeps a hit's points at face value while it still counts toward the combo.
8. **Bonuses** (`Score.bonus`) are never multiplied, never touch the combo, and get their own line in the results breakdown. The same label adds up.
9. **Score = points before multipliers + multiplier extra + bonuses − penalties.** The results breakdown lists exactly these, so its lines always add up to the total.
Set the rules on the `ScoreKit` component's fields, or call this on every machine with the same values:
```lua
Score.configure({ window = 1.8, steps = { 5, 10, 20, 40 }, maxMultiplier = 8, decay = "step", breakOnPenalty = false })
```
## Ratings: stars and grades
A level sets targets. `Score.rate` (and the `stars`, `grade` displays and every results screen) turn a score or a time into 0 to 3 stars and a grade letter:
```lua
Score.setTargets({ score = { 1000, 2500, 5000 } }) -- points for 1, 2, 3 stars
Score.setTargets({ time = { 90, 60, 45 } }) -- seconds for 1, 2, 3 stars (lower is better)
Score.setTargets({ score = { 1000, 2500, 5000 }, grades = { S = 7000, A = 5000, B = 3000, C = 1500 } })
local r = Score.rate(3100) -- { stars = 2, grade = "B", frac = 0.24, next = 5000, kind = "score" }
```
- **Stars** = how many targets the value meets (score: at least the target; time: at most the target).
- **Grades** without explicit lines: **S** = 20% past the three-star target (score ≥ 1.2 × three, time ≤ three ÷ 1.2), **A** = three stars, **B** = two, **C** = one, **D** = below one. Explicit `grades` lines replace these.
- `frac` is the progress from the last star target to the next one. `next` is the next target (nil at three stars).
- With no targets set, the defaults are `{ score = { 1000, 2500, 5000 } }`, so the rating displays work out of the box.
## Rounds with MatchFlow
When the scene has a **MatchFlow** match (the Match Flow Kit), scoreKit binds to it on its own (`match = "auto"`):
- **Scores count in its matches.** The keeper reports every award, already multiplied, with `m:addScore(peer, points)`, so MatchFlow's HUD, standings and podium show the same numbers as scoreKit.
- **Points only count while the round is playing** (`matchOnly = true`). An add during the lobby, countdown or results is refused, and a predicted "+10" is taken back.
- **Every score goes back to 0** when a round's countdown starts.
- **When a round ends, players are ranked.** MatchFlow's places are used, so every format ranks the way MatchFlow does. Each player's score is posted to the board, and every player gets their own results: the `roundEnded` event (on every machine) carries `{ n, ranking = { { key, name, score, place, stars, grade } }, results = { [key] = ResultsData } }`. Each player sees their results screen after MatchFlow's podium, during the break, never on top of it: the card waits until MatchFlow has finished showing its own results on that player's machine. It then stands in for MatchFlow's "next round" panel and shows "Next round in N" itself. If the break is over before the card could show, it is skipped, and a card still up when the next round counts down closes, so there is only ever one end-of-round screen. The break is how long the card can stay up, so give MatchFlow a `breakSeconds` at least as long as `resultsSeconds`. A new personal best or record is shown on the rating card itself ("New personal best" beside the place): in a MatchFlow break there is time for one card, not a celebration first.
Without MatchFlow, call `Score.endRound()` yourself to rank, post and show results, and `Score.resetRound()` to start over. `Score.submit(player)` posts a score to the board at any moment, for example at the end of a level.
```lua
-- a whole match in two components on synced entities
local match = entity.spawnSynced("Match")
match.component.add(asset.resolve("~MatchFlow.MatchFlow", "component"), { format = "timed", roundSeconds = 30 })
local kit = entity.spawnSynced("ScoreKit")
kit.component.add(asset.resolve("scoreKit.ScoreKit", "component"), { results = "tally" })
```
MatchFlow comes with scoreKit as one of its dependencies. Your own scripts find it by name, `MatchFlow.MatchFlow` or `~MatchFlow.MatchFlow` (the form to use from inside another package), wherever the install put it.
## Pickups that score (pickupsKit)
scoreKit comes with **pickupsKit**: coins, gems, hearts, keys and power-ups in 47 looks, where pickupsKit decides who took each one, even when two players grab at once. The `ScorePickups` component turns every grab into points for the player who took it:
```lua
-- in a scene's build.luau, inside content()
local Pickups = require("scoreKit.pickups").kit() -- pickupsKit's API, as scoreKit installed it
for i = 1, 5 do
Pickups.spawn({ (i - 3) * 1.5, 0, 4 }, { prefab = "goldCoin" })
end
Pickups.spawn({ 0, 0, 7 }, { prefab = "ruby" })
Pickups.spawn({ 3, 0, 6 }, { prefab = "damageOrb", effect = "none" }) -- a hazard: no power-up, just a penalty
entity.spawn("PickupScores").component.add(asset.resolve("scoreKit.ScorePickups", "component"),
{ points = "goldCoin=10, ruby=50, damageOrb=-25" })
```
- **`points`** gives each pickupsKit prefab (`goldCoin`, `ruby` …) or kind (`coin`, `gem` …) its points. A prefab's entry beats its kind's. A negative value is a penalty: never multiplied, and it breaks the combo. A pickup with no entry scores nothing (pickupsKit still counts it).
- **Each grab scores once.** pickupsKit tells every machine about a grab once. Only the machine keeping the score turns it into a `Score.add` for the player who took it, with the "+N" at the pickup and `coins`, `gems` … (or `hazards`) as the results line. Before the first point there is no `ScoreKit` yet: then the senior machine scores the grab, and its `Score.add` creates the kit, as the first example's jump does. So a coin is worth the same whichever player grabs it, on whichever machine.
- Grabs build the combo like any other hit, and count only while a MatchFlow round is playing.
- From code: `require("scoreKit.pickups").listen("goldCoin=10")` does the same and returns a stop function. `score(ev, points)` scores one pickupsKit `collect` event.
- **Where pickupsKit's counter goes.** pickupsKit's `PickupHUD` sits in a top corner, and MatchFlow's standings take the top right, so put the counter top-left: `entity.spawn("PickupCounter").component.add(Pickups.HUD, { corner = "topLeft" })`. With `corner = "auto"`, scoreKit's score display sees it there and moves to the bottom-left, so the three never cover each other.
- `require("scoreKit.pickups").kit()` is pickupsKit's own API (`spawn`, `burst`, `on`, `get` …), so a game that got pickupsKit with scoreKit reaches it through scoreKit. pickupsKit's README has every look and setting.
## Time trials
```lua
Score.startRun(player) -- start the clock
Score.split(player, "Bridge") -- a checkpoint (labels default to CP1, CP2 ...)
Score.finishRun(player) -- the time goes to the time board, fastest first, with its splits
```
The `splits` display shows each split against the player's own best: green when ahead, red when behind. The `timeTrial` results screen shows the finished run against the best. The keeper times every run on its own clock. It uses the runner's own reading (which has no network delay) only when that reading is within 0.75 s of the keeper's. A runner can't claim a time their run didn't take.
## Leaderboards
Each world has its own boards, kept in the world's `runtime_data`, so they survive the world being closed and opened again. A board keeps **one row per player: their best of the season** (highest score, or fastest time on a time board), and counts their plays.
```lua
local board = Score.board() -- the kit's board (field `board`, default "main")
local times = Score.timeBoard() -- "<board>_times": fastest first
board:top(10) -- { { k, n, v, rank, st, g, at, c } }
board:around(player, 5) -- you and the players just above and below
board:entry(player), board:rankOf(player)
board:season(), board:seasons() -- the current season, and past ones with their top 10
board:newSeason("Summer") -- archive this season's top 10 and start an empty one
board:remove(player) -- take a stale or test row off this season (the writer in charge only)
board:status() -- is it saved? (below)
board:data(player) -- exactly what the board views draw
board:onChange(fn)
Score.board("level2") -- any number of boards, by id
```
**Seasons.** `newSeason` archives the current season's top 10 (names, values, stars, grades), records how many players it had, and opens season N+1 empty. Old rows stay in storage under their season. `board:seasons()` and the `seasons` view show the champions of every past season. Only the board's writer can start a season, and only while it is the keeper.
## Who can write the board
**Only the keeper changes scores, and only the keeper writes the board.** The keeper is the machine that owns the synced `ScoreKit` entity: whoever loaded the scene first, or, after that machine leaves, the remaining player with the lowest peer id. Every other machine only *asks* it, and by default its asks are refused:
- **Scoring is keeper-only by default** (`acceptRemote = false`). Only code running on the keeper changes a score. The keeper sees every player's body, so a coin, a kill or a checkpoint is judged there, as the gallery's coins are. You can run the same code on every machine: the keeper's call counts, and on the other machines `Score.add` sends nothing, predicts nothing and fires `refused` locally. So each pickup counts once. `Score.isKeeper()` says where you are.
- **No machine can post its own value to the board.** A post asked for from another machine carries no number. The keeper posts the score it counted, and only to the kit's score board. Times reach the time board only from runs the keeper timed itself.
- **Only the keeper's messages are believed.** Other machines take standings, awards and round results only from the keeper's peer. A player who sends their own "snapshot" or "award" is ignored, and the ignore is logged.
- **Points formats are ranked on the keeper's counted scores**, not on MatchFlow's standings: MatchFlow takes reports from any machine. MatchFlow's places count only for `race`, `lastStanding` and `kingOfTheHill`, where order is not decided by points.
- **Only while playing**, when bound to a MatchFlow match.
**`acceptRemote = true`** lets each machine report points for its own player, for events only that machine can see, such as a button press. Its "+N" then shows instantly. That is a trust decision, because a modified client can then claim points for itself within these caps:
- **Only its own player** (`remoteFor = "self"`): a request to score for anyone else is refused and logged.
- **No absurd amounts**: a single remote add above `maxPerAdd` (1000) is refused.
- **No floods**: more than `maxPerSecond` (20) remote adds per player per second are refused (short bursts of up to twice that are allowed).
A refused request is answered with the reason: the sender's "+N" is taken back, a `refused` event fires there, and a warning is logged on both machines.
**Two modes, set by the `writers` field:**
| `writers` | Where the board lives | Who can write it |
|---|---|---|
| empty (default) | the world store (`runtime_data.world`) | the keeper, whoever it is |
| `"<userId>, <userId>"` | those accounts' **own** player stores (`runtime_data.player(id)`) | only those accounts, and only while one of them is the keeper. The Zero server enforces it: no other account can write a player store. |
The default mode protects the board from the kit's own network path. Nothing another player's game sends can change it. But `runtime_data.world` itself accepts writes from any client, so a player who runs modified engine code could still write it directly. If your board must hold against that too, set `writers` to your own account id(s) (`runtime_data.localId()` prints yours).
**What happens when a write can't be made.** Scores are never lost silently:
| The board's status | When | What happens |
|---|---|---|
| `saved` | every write landed | nothing to do |
| `saving` | writes in flight | they land within a moment |
| `retrying` | a write failed (network, store unavailable) | it stays queued and is retried with back-off (0.5 s, 1 s, 2 s … up to 30 s) until it lands. The queue is also kept in the keeper's own player store, so it is replayed if the keeper's tab closes first. |
| `held` | locked mode and the keeper is not a writer | the result is **held**: queued in the world store as a pending result, not put on the board. The player gets a toast saying so, and the results screen says "Held for the board's keeper". A writer later calls `board:held()`, `board:approveHeld("all")` or `board:rejectHeld(ids)`. |
| `offline` | `runtime_data` is not available | nothing is written; the status says so |
| `readOnly` | on a machine that is not the keeper | `board:status()` there reports the keeper's status from its snapshot |
Every board view shows this status as a chip, so players can see whether their score is saved.
## Multiplayer
- **The keeper** runs the rules (combos time out on its clock), applies every add, writes the board and publishes every player's score, combo, multiplier and combo timer in a synced snapshot on the `ScoreKit` entity, up to 12 times a second (and at least twice a second). **Every player sees the same scores and the same board.**
- **Each player's display and popups are their own.** Each machine draws its own player's corner display, "+N" popups, toasts and results screen. Nobody sees another player's popups.
- **Seen quickly.** A player sees their own points as soon as the keeper's next snapshot reaches them (it publishes up to 12 times a second). With `acceptRemote = true`, `Score.add` on the player's own machine is also *predicted*: the points, the combo and the "+N" show the moment it is called. The prediction is let go once the keeper's snapshot confirms it, and taken back if it is refused. One that is never confirmed is dropped after 3 s with a warning.
- **Players come from the scene's player setup** (`layers.active.players`). Every player in the match has their own score, results and board row:
- A signed-in player's key is `u:<userId>`, so a returning player keeps their personal bests.
- **The same account signed in on two machines is two players.** The session on the lowest peer keeps `u:<userId>`; the next is `u:<userId>#2` and shows as "Name (2)", and so on. Each has its own score, its own place in the round and its own board row.
- `p:<peer>` is used for an anonymous session, and `b:<name>` for bots (`Score.add("Robo", 10)`, `Score.setName`).
- **Only players who are here are ranked.** A round's ranking, its places ("1st of 2") and the board posts cover the players in the scene's player setup when the round ends, plus any bots the game scored by name. A player who left before the end is not ranked or posted, and a key nobody plays under can never take a place.
- **Each event counts once.** With the default keeper-only scoring, only the keeper's `Score.add` counts, so the same pickup code can run on every machine. With `acceptRemote = true`, report an event either from the keeper or from the player's own machine, not both.
- **If the keeper leaves**, the entity passes to another machine, which carries on from the last snapshot. Writes still queued on the leaver are replayed the next time that account keeps. Points scored in the instant of the handover can be lost.
- **Events** fire on every machine: `award`, `comboUp`, `comboBreak`, `record`, `held`, `submitted`, `run`, `roundStarted`, `roundEnded`, `refused`, `snapshot`. Use `Score.on(name, fn)`, which returns an unsubscribe function.
## Styles
Every style is listed by `Score.catalog()` as `{ id, family, name, description, natural = { w, h }, themed, tags = { look, looks, size, genres, shows } }`. Filter it with `Score.catalog("display")` or `Score.catalog({ family = "board", genre = "racing" })`. Themed styles draw in any of the five looks.
```lua
Score.setDisplay("multiplierRing") -- this machine's corner display
Score.setLook("fantasy") -- themed displays, boards, results
Score.setPopups("cartoon") -- "+N" popups ("off" to hide)
Score.setResults("tally") -- the end-of-round screen
Score.setHud({ corner = "topRight", scale = 0.8 }) -- corner: auto, topLeft, topRight, bottomLeft, bottomRight, top, bottom
```
Or set the world's defaults with the `ScoreKit` fields `display`, `look`, `popups`, `results` and `corner`.
### Score displays (`display`)
| id | name | look | size | suits | what it is |
|---|---|---|---|---|---|
| `arcade` | Arcade Odometer | arcade | medium | arcade, shmup, pinball, platformer | Zero-padded rolling digits in a black glass bezel. Every digit column rolls like an odometer, with a 1UP label and a multiplier chip. |
| `pixel` | Pixel Counter | arcade | medium | retro, arcade, platformer | Chunky 8-bit pixel digits with a hard shadow, a stepped pixel combo bar and a pixel x3. |
| `comboMeter` | Combo Meter | any (themed) | medium | action, rhythm, brawler, arcade | Score plus a wide meter that fills toward the next multiplier step, and a strip that drains with the combo window. |
| `multiplierRing` | Multiplier Ring | any (themed) | medium | action, shooter, rhythm | A circular ring that drains with the combo window, one segment per multiplier step, and a big xN in the centre. |
| `stars` | Star Rating | any (themed) | medium | puzzle, casual, mobile, platformer | Score with three stars that fill as the score passes its targets. The next star fills partially. |
| `grade` | Grade | any (themed) | medium | action, rhythm, racing, stylish | A big grade letter (S A B C D, each its own colour, S shines) with progress toward the next grade. |
| `splits` | Time Trial Splits | any (themed) | large | racing, speedrun, time trial, parkour | Running timer, finished splits with green/red deltas, the current split highlighted, an ahead/behind banner and the time to beat. |
| `minimal` | Minimal | minimal | small | any, casual, exploration | Quiet thin type straight over the game with a soft shadow, a small label and a subtle xN. |
| `scifi` | Holo Readout | scifi | medium | shooter, space, cyberpunk | Clipped-corner holographic frame with scanlines, glowing mono digits and the combo as tick segments. |
| `fantasy` | Gilded Plaque | fantasy | large | rpg, adventure, medieval | A walnut plaque on a parchment ribbon with gold serif numerals, a wax-seal multiplier and rune gems lighting up. |
| `cartoon` | Bouncy Cartoon | cartoon | medium | casual, kids, party, platformer | A chunky inked number on a yellow starburst that squashes and stretches on every award, with a combo starburst badge. |
| `neon` | Neon Sign | arcade | medium | arcade, synthwave, rhythm | A glowing neon-tube number with a subtle flicker, and the multiplier in a second tube colour. |
| `broadcast` | TV Score Bug | any | small | sports, racing, party, multiplayer | A sports-broadcast lower third: LIVE dot, place, player name, score and a multiplier tag. |
### Popups (`popups`)
"+N" where the points were scored: projected from the `at` position you pass, or under the display when there is none. Kinds: normal, combo (with its xN), big (at least `bigAt` = 100), bonus (with its label) and penalty (red, falling).
| id | name | look | size | suits | what it is |
|---|---|---|---|---|---|
| `pop` | Clean Pop | any (themed) | small | any | Bold outlined number that pops in, rises and fades. Draws in the current look. |
| `arcade` | Arcade Pixel | arcade | small | retro, arcade, platformer | Pixel-font number that hops up in hard steps and blinks out. Big throws pixel sparks. |
| `scifi` | Holo Bracket | scifi | small | shooter, space, cyberpunk | Glowing mono number between brackets that spread open. Big draws an expanding hex, penalty glitches. |
| `fantasy` | Gold Embers | fantasy | small | rpg, adventure, medieval | Gold serif numerals that drift up like embers with sparks. Big radiates rays. |
| `cartoon` | Inked Bounce | cartoon | small | casual, kids, party | Chunky inked number with an elastic bounce and a tilt. Big lands on a starburst, bonus on a ribbon. |
`popups = "auto"` (the `ScoreKit` default) picks the popup that matches the look.
### Leaderboards (board views)
| id | name | look | size | suits | what it is |
|---|---|---|---|---|---|
| `top10` | Top 10 | any (themed) | medium | arcade, platformer, puzzle, racing, party | The classic high-score table: rank with medals, avatar, name, stars and grade, value. Your row is highlighted, and pinned under a divider when you are outside the top 10. |
| `podium` | Podium | any (themed) | large | party, arcade, sports, racing | The top three on stepped podium blocks (1st centre, crowned), with 4th to 8th as a compact list. |
| `aroundMe` | Around Me | any (themed) | medium | arcade, platformer, puzzle, racing, endless | Your rank as a hero (#17 of 214, top 8%), the rows just above and below you, and how far it is to pass the next player. |
| `bestTimes` | Best Times | any (themed) | medium | racing, platformer, speedrun, time-trial | Fastest first, with a stopwatch: the track record on top, every other time with its gap to first and a gap bar. |
| `seasons` | Seasons | any (themed) | large | competitive, arcade, sports, racing | This season's standings under a season badge, beside a hall of champions: each past season with its top three. |
| `sign` | Scoreboard Sign | any (themed) | large | arcade, platformer, party, racing, hub | A sign that stands in the level (the `ScoreSign` component), framed per look: arcade marquee with bulbs, LED panel, holo-board, wooden notice board, chalkboard. Top 5 in big type. |
Draw any view anywhere with `require("scoreKit.boards").render(id, look, Score.board():data(), { w, h, t })`.
**A board in the level:** the `ScoreSign` component builds a sign (two posts and a backboard) and draws a board view on its face, live:
```lua
local sign = entity.spawn("HallOfFame", { position = { 0, 0, -10 } })
sign.component.add(asset.resolve("scoreKit.ScoreSign", "component"), { view = "sign", look = "fantasy", width = 5, height = 3 })
```
Fields: `board` (empty = the kit's), `view` (any board view), `look`, `title`, `width`, `height` (metres), `lift` (height above the ground), `frame` (false: no posts or backboard, for your own wall), `maxDistance`.
### End-of-round screens (`results`)
| id | name | look | size | suits | what it is |
|---|---|---|---|---|---|
| `ratingCard` | Rating Card | any (themed) | medium | arcade, platformer, puzzle, rhythm, party | Stars that pop in one by one, a big grade letter, the score and this round's place, a breakdown table that adds up to the total, and best-combo / max-multiplier chips. |
| `celebration` | Celebration | any (themed) | large | arcade, platformer, racing, endless, party | NEW PERSONAL BEST or NEW WORLD RECORD with rays and confetti, the new score, the previous best, the improvement and the board rank. A calm "Good run" when neither. |
| `tally` | Tally | any (themed) | medium | arcade, platformer, action, rhythm | A combo and bonus tally that counts up: each breakdown line appears and counts from 0, a running total climbs, then the final total punches in with the rating. |
| `timeTrial` | Time Trial | any (themed) | medium | racing, platformer, speedrun, time-trial | The final time big, every split against its best with green (ahead) / red (behind) deltas and a gap bar, a PB / record badge and the time to beat. Handles a first run with no best. |
A finished time run always shows `timeTrial`. Without MatchFlow, a round that brings a personal best or record shows `celebration` before a `ratingCard`; in a MatchFlow round the `ratingCard` shows alone and says "New personal best" or "New world record" beside the place. The screen closes on its own after `resultsSeconds`, or on a click or tap.
### Looks
| id | name | what it is |
|---|---|---|
| `arcade` | Arcade | Black glass, neon yellow and magenta, chunky monospace digits. |
| `minimal` | Minimal | White cards, quiet blue accent, clean sans type (MatchFlow's minimal). |
| `scifi` | Sci-Fi | Dark navy glass, cyan and pink glow, clipped corners (MatchFlow's sci-fi). |
| `fantasy` | Fantasy | Parchment and walnut, gilded gold, serif type. |
| `cartoon` | Cartoon | Cream panels, thick ink outlines, hard drop shadows (MatchFlow's cartoon). |
`minimal`, `scifi` and `cartoon` use MatchFlow's own design tokens, so a world running both kits looks like one game.
## The ScoreKit component
| Field | Default | What it does |
|---|---|---|
| `display` | `arcade` | the corner score display |
| `look` | `arcade` | the look for themed displays, boards and results |
| `popups` | `auto` | "+N" popup style (`auto` follows the look, `off` hides them) |
| `corner` | `auto` | `auto` (top-left; bottom-left when pickupsKit's counter is in the top-left or a MatchFlow timer would overlap; the bottom on a phone), `topLeft`, `topRight`, `bottomLeft`, `bottomRight`, `top`, `bottom` |
| `showHud` | `true` | off: draw nothing, and build your own HUD from `Score.state()` |
| `results` / `resultsSeconds` | `ratingCard` / `7` | the end-of-round screen (`none` for none) and how long it stays |
| `toasts` / `toastComboFrom` | `true` / `3` | navUiKit toasts; a combo toast when the multiplier reaches this (0 = never) |
| `window`, `steps`, `maxMultiplier`, `decay`, `breakOnPenalty` | `2.5`, `"3,6,10,15"`, `5`, `reset`, `true` | the combo rules |
| `board` / `boardTitle` | `main` / "" | the board's id and title (time board: `<board>_times`) |
| `writers` | "" | user ids that may write the board (empty: the keeper) |
| `match` | `auto` | bind to the scene's MatchFlow (`off`, or the Match entity's name) |
| `acceptRemote`, `maxPerAdd`, `maxPerSecond` | `false`, `1000`, `20` | off: only the keeper scores. On: other machines may report their own player's points, capped by the other two |
`Score.configure` also takes `matchOnly`, `remoteFor`, `round`, `bigAt`, `every`, `targets`, `comboToast` and `recordToast` (navUiKit toast variants, default `minimal` and `achievement`), and `resultsAt` (`auto` waits for MatchFlow's results to finish).
## API
`local Score = require("scoreKit.score")`. From inside another package, use `require("~scoreKit.score")`.
| Call | Does |
|---|---|
| `Score.add(player, amount, { at, reason, combo, multiply })` | add points; returns the points awarded, as a number (see below) |
| `Score.penalty(player, amount, opts)` / `Score.bonus(player, label, amount)` / `Score.breakCombo(player, reason)` | take points away / a named bonus / break the combo. `penalty` and `bonus` return the points awarded too. |
| `Score.get(player)` / `Score.state(player)` / `Score.players()` | a score / everything live about a player / everyone this round, ranked |
| `Score.configure(opts)` / `Score.rules()` / `Score.setTargets(t)` / `Score.rate(v, t)` | rules and settings / the rules in force / a level's targets / a rating |
| `Score.setDisplay`, `setLook`, `setPopups`, `setResults`, `setHud`, `start`, `stop` | this machine's HUD |
| `Score.catalog(filter)` | every style with its tags |
| `Score.endRound(opts)`, `Score.resetRound()`, `Score.submit(player, value, { board })`, `Score.lastRound()`, `Score.match()` | rounds and posting |
| `Score.startRun`, `split`, `finishRun`, `cancelRun` | time trials |
| `Score.board(id)`, `Score.timeBoard()` | board handles (see Leaderboards) |
| `Score.on(event, fn)`, `Score.isKeeper()`, `Score.keyOf(player)`, `Score.setName(player, name)` | events and identity |
| `require("scoreKit.pickups")`: `listen(points, { reason }?)`, `score(ev, points, { reason }?)`, `scoresHere()`, `parse`, `pointsFor`, `reasonFor`, `kit()` | pickupsKit grabs as points (see Pickups that score) |
**What `Score.add` returns.** Always a number: the points that call put on the score.
- **On the keeper** (a solo game, or the host): the points awarded after the combo multiplier, at once. Three quick `Score.add(player, 10)` calls return 10, 10, then 20 (x2). `Score.penalty(player, 25)` returns -25, and `Score.bonus(player, "No damage", 500)` returns 500.
- **0 when nothing was awarded:** outside a playing MatchFlow round, or when the call was refused.
- **On another machine with keeper-only scoring** (`acceptRemote = false`, the default): 0. That machine's call awards nothing; the keeper's own call for the same event is the one that counts.
- **On another machine with `acceptRemote = true`:** the points it predicts, shown at once. The keeper confirms them within a round trip, or takes them back if it refuses.
The renderers are plain functions over data, for drawing a style inside your own UI. Each data shape is written down, with a moving sample generator, in `scoreKit.demo`:
- `scoreKit.displays.render(id, data, { w, h, look, t })`
- `scoreKit.popups.render(id, popup, { k, look })`
- `scoreKit.boards.render(id, look, data, { w, h, t, narrow })`
- `scoreKit.results.render(id, look, data, { w, h, t, narrow })`
## The gallery
`ScoreGallery` is the style browser the Hall of Fame world opens with. Its **Everything** tab puts every score display, every leaderboard and every end-of-round screen on one page, side by side and labelled with their tags. Further tabs show each family larger, plus the popups. Every card draws from **one feed** at the same moment: in a round it is your own live score, combo and multiplier, the world's real boards and your last round's results (the card is marked LIVE). Before there is anything live, all cards play the same demo run in lockstep (marked DEMO). A look switcher redraws every themed card, and a "Use" button on a card puts that style on your own HUD. The **Live round** tab shows the world's real round and board. Add it to any scene: `entity.spawn("Gallery").component.add(asset.resolve("scoreKit.ScoreGallery", "component"), {})`.
**The coin round is scoreKit with pickupsKit.** The arena's seven gold coins, the ruby and the damage orb are real pickupsKit pickups, placed in the scene's `build.luau` exactly as in "Pickups that score". pickupsKit decides who took each one, pops it, counts it on its own counter (top left, so MatchFlow's standings keep the top right) and brings it back. The score display then sits bottom-left on its own (`corner = "auto"`). A `ScorePickups` with `points = "goldCoin=10, ruby=50, damageOrb=-25"` scores each grab. The world has no coin code of its own.
## Phones and the browser
- Every screen is sized from the safe area (`ui.safeArea()`, through MatchFlow's `theme.viewport()`). On a phone held upright (under 640 points wide), the corner display takes at most 62% of the width. Results screens and the gallery switch to single-column layouts (boards and results take `narrow`) instead of shrinking their text.
- Everything is UI-tree drawing (boxes, SVG, engine-bundled fonts: Anton, Archivo Black, Arimo, Comic Neue, EB Garamond, PT Serif, JetBrains Mono), with no textures or shaders to load. Each release is checked in the desktop editor: an agent working inside the engine cannot open the web build to check it there (#20946).
- Results screens close on a tap. The gallery's buttons are full-size touch targets.
## What it builds on
| Package | World | Used for |
|---|---|---|
| **MatchFlow** 1.3.1 | Match Flow Kit | rounds: `addScore`, `getPhase`, `getStandings`, `onStateChanged`, `onRoundEnded`. Its theme tokens are the base of three looks. |
| **navUiKit** 1.2.1 | Wayfinder Studio | toasts (`Nav.toast`, achievement / minimal / banner variants), and its camera projection (`navUiKit.geom`) for popups and signs |
| **pickupsKit** 2.3.14 | Treasure Trove | pickups that score: `ScorePickups` and `scoreKit.pickups` listen to its `collect` event (see Pickups that score). It brings SecondWind, Lifeline and juiceKit with it, and the same MatchFlow. |
They come with scoreKit: its code names them (`~MatchFlow.theme`, `~navUiKit.nav`, `~navUiKit.hud`, `~navUiKit.geom`, `~pickupsKit.api`), and an install brings what the published package references. scoreKit finds them by package name, so they work wherever the install puts them (`/source` or `/source/deps/<guid>/`). Keep one copy of each: a second MatchFlow, navUiKit or pickupsKit makes its name ambiguous. If the log shows `module '~navUiKit.nav' not found`, `'~MatchFlow.theme' not found` or `'~pickupsKit.api' not found`, install the missing kit from ZeroMind ("navUiKit", "MatchFlow", "pickupsKit"). Only the part that uses it stops working: without navUiKit scoreKit draws its own toasts, without MatchFlow it uses its embedded looks, and without pickupsKit only `ScorePickups` fails to load.
scoreKit carries its toasts on a navUiKit HUD it makes itself through navUiKit's `hud` module. It shows only the toasts (no minimap, compass or objectives, and the map key is unbound), and needs no navUiKit component in your scene. If your world runs navUiKit's own HUD (`Nav.start()` or a NavHud), scoreKit's toasts appear on that one instead.
## Tests
The `scoreKit` test suite runs in edit mode with `tools.use("tests", "run", { suite = "scoreKit" })`. It covers:
- **Rules:** the combo rules against the numbers in this README, ratings and ranking.
- **Board:** bests, records, time boards, corrupt rows, merging, around-me, seasons.
- **Persistence through `runtime_data`:** write and read back, a new session seeing it, a non-keeper refusing, held results in locked mode with their approval and rejection, retrying and the outbox replay.
- **Keeper:** its checks on remote scores, prediction and refusal, adopting the keeper's rules on another machine, MatchFlow binding with a stand-in match, round ends whose breakdown adds up, time runs and their validation.
- **API:** every public call (HUD settings, reading, configuring, scoring, rounds, runs, every board-handle method), the events they fire, and the `ScoreKit` and `ScoreGallery` components.
- **Pickups:** the points table, the keeper scoring each pickupsKit grab once (combo, penalty, unlisted pickups), a machine that is not the keeper scoring nothing, only the senior machine scoring before any ScoreKit exists, grabs announced through pickupsKit's own network handler, and the `ScorePickups` component.
- **Styles:** the catalog, and every renderer in every look at desktop and phone sizes. Also the HUD, every gallery tab (and that all its cards are handed the same data in the same frame) and the sign.
- **Install layout:**
- every require and asset name in the package resolves wherever an install puts scoreKit and its dependencies (package-relative `~.x`, packages by name `~Name.x`, or `@builtin::`)
- a package named `~Name` is found under `/source/deps/`
- toasts run on the HUD scoreKit makes itself
- **This README:** its version against `package.yaml`, `Score.version` and the changelog, its rules and style tables, and its first example run against a stand-in jump button (three quick jumps make 40).
- **Coverage:** a check that every public function of every module is called by the suite.
The suite removes everything it writes to the world's store. It passes in a world just loaded, right after a play session, and with other engines in the room.
## Known limits
Engine issues that still affect scoreKit, each with the GitHub issue that tracks it:
- **An install also writes a partial second copy of some of scoreKit's modules (#10762).** A fresh install puts scoreKit in `/source/scoreKit.package`, and can put copies of a few of its modules (`theme`, `basetheme`, `displays`, `popups`, `boards`, `results`) beside it under `/source/deps/877b8381-7a16-4946-9242-f1140f46092a/scoreKit.package/`. The engine records which version of each module a file requires against that file's bytes, and an install fetches every recorded version the package does not ship as a lone copy. The copy has no `package.yaml`, so it is not a second scoreKit: `scoreKit.*` and `~scoreKit.*` still name the real one. Up to 1.3.1 the copies held older code, and the shipped modules loaded it (the 1.3.1 pixel-font fix did not reach installs). 1.4.0 gives every file new bytes, so each one records the versions it ships with, and a fresh install loads the code it ships. Fresh installs of 1.4.0, 1.4.1 and 1.4.2 wrote no copy at all.
- **The world store is open to modified clients** in the default mode (see Who can write the board). The engine has no store that only the world's authority can write (#19283), so the kit's own network path cannot change the board, but a player running modified engine code can still write `runtime_data.world` directly and forge rows. Use `writers` for a board that must hold against that too.
- **One account on two machines presents one player in the engine (#14448).** scoreKit works around it by giving each session its own key (`u:<id>`, `u:<id>#2` …). "Nova (2)" is whichever of that account's machines joined the room second, so that board row belongs to the account's second seat rather than to one particular computer.
- **The test suite can't be two players in one engine (#18688, #19114).** The loopback test mode doesn't echo messages, and an agent in the engine can't bring in a second player. So the suite delivers the other machine's messages through the real network handlers: scoreKit's own (refusals, rate limits, predictions, forged snapshots) and pickupsKit's (`pk:got` grab announcements). So two real machines are played by hand for each release instead. For 1.4.2, two editors on the relay, signed in to one account, played the gallery's coin round together, one of them hosting. The other machine's player took the seven coins and the ruby: that machine showed its own score as 290 and the host's live count for that player was 290, both showed the same standings, and both showed the same Hall of Fame board (1060 and 150, Saved) before, during and after the round. MatchFlow ended the round on both together, with the player 1st at 290, 1 star, C. The board kept that player's season best of 1060 and counted the play. The machine with the lower peer id kept the account's own key and the host showed as "(2)".
- **The sign's face is UI drawn where the sign is on screen (#19284).** Zero's 3D `UiPanel` turns widget trees into plain rich text, so the styled board is drawn as UI fitted to the backboard's projected size, squashed to the viewing angle. It is hidden when its back faces you or beyond `maxDistance`, but a wall between you and the sign does not hide it.
- **An input handler from an earlier Play stays attached (#22432).** A handler your scene adds in `onLoad` (for example `controls.jump:onPressed(...)`) is not removed when play stops. So if you press Play, stop and press Play again, every jump calls `Score.add` once for each Play so far: twice in the second Play, three times in the third, four times in the fourth. The score really does start from 0 each time, it just climbs two, three or four times too fast. To avoid it, keep the handle `onPressed` returns and call its `:Disconnect()` in `onUnload`, as the first example does. Closing and reopening the world also clears the old handlers.
- **ZeroMind's description can lag a release (#19258).** For a while after a release, scoreKit's description on ZeroMind can still show the previous README. The README inside an install is always the one for the version installed.
By design:
- **`acceptRemote = true` trusts each machine with its own player's points**, within `maxPerAdd` and `maxPerSecond`. A modified client can then award itself points up to those caps. Keep the default for anything competitive.
- **MatchFlow takes reports from any machine.** scoreKit ranks points rounds on its own counted scores. But in `race`, `lastStanding` and `kingOfTheHill` it uses MatchFlow's places, and those trust MatchFlow's own reports (`finish`, `knockOut`, `setOnHill`).
- **Points scored in the instant the keeper leaves can be lost.** The next keeper carries on from the last published snapshot.
- **A player who leaves before the round ends is not ranked or posted.** Their points that round don't reach the board.
## Changelog
### 1.4.10
- **Every player's pickups score, whoever's machine they were grabbed on.** The keeper found the player behind a grab by the collector entity pickupsKit named, an entity id another machine's player body may not have on the keeper, so grabs made on other machines could score nothing. It now falls back to the player pickupsKit names by key (`p<peer>`). `listen(points, { reason })` and `score(ev, points, { reason })` name the results line the points go to (Skyhook's starfruit read "starfruit", not "stars"). Built and tested on pickupsKit 2.3.14.
### 1.4.8
- **Built and tested on pickupsKit 2.3.8,** the version a new install of scoreKit brings. Earlier releases named 2.3.0, so a fresh install ran against a newer pickupsKit than the README said, and the dependency test failed there. Nothing in scoreKit's code changed: pickupsKit 2.3.1 to 2.3.8 added guides and fixed how it loads when installed under `deps/`, with the same `collect` event.
### 1.4.7
- **The test suite passes with the gallery open.** Two pickups tests grab a gold coin and a ruby through pickupsKit, which every listener hears, and the gallery's own `ScorePickups` (listening in edit mode too) scored those same grabs, so the tests read 20 for 10 and 100 for 50. They now use pickup names no scene scores.
- **The test file is back to the kit's own references.** 1.4.6 came from a contribution whose test file named the kit the way its own install did (`~scoreKit.ScoreKit` and `~.score`), and one of those, a file read by asset name, broke the catalog test. They read as before 1.4.6 again. The 1.4.6 fix itself is unchanged.
### 1.4.6
- **Fixed: the run clock shows from the start of a run.** A run started before the player had scored (`Score.startRun` on a fresh player) had no timer on the `splits` display, which read "SCORE 0" until the first point: the view packs the run from the keeper's player record, and starting a run did not make one. Starting a run now makes the record. Found while following Trapline's Trap Run example, which starts the clock on Play. A test in `api` covers it.
### 1.4.5
- **Fixed: from the third Play on, sometimes nothing scored or showed.** A flag that stops two kits being made at once was cleared by a task one second later. When play stopped within that second, the task was dropped with the session and the flag stayed set, so no later session ever made a `ScoreKit`: scores waited for a keeper that never came and the score display stayed off. The hold is now a time that runs out by itself, and every new session clears it.
- **The first example removes its jump handler in `onUnload`.** The engine keeps an input handler from an earlier Play attached (#22432), so the old example counted each jump twice in the second Play, three times in the third, and so on. With `onUnload` each jump counts once in every Play. Known limits describes the engine issue in plain words, and the how-to guide's copy of the example does the same.
### 1.4.4
- **Every play session starts from zero.** The score, combos, runs and rounds lived on in the kit's module between play sessions, so pressing Play again went on from the last session's score (40, then 150 …), and that score stayed on screen in edit mode. Now each switch between edit and play starts a fresh session (`C.newSession`) and takes the HUD down until the next session draws it. Boards and settings are untouched. Found in a fresh world running the first example.
- **A readable end-of-round card in MatchFlow rounds.** The card shows in MatchFlow's break and closes at the next countdown. On a first score or a new best, the `celebration` screen used to take the first 4 seconds of that break, leaving the rating card a second or so. In a MatchFlow round the rating card now shows alone for the whole break and says "New personal best" or "New world record" beside the place. Without MatchFlow the celebration still comes first. The README and the how-to guide say to give MatchFlow a break at least as long as `resultsSeconds`.
- **The example guide** builds a 60 second round with a 4 second podium and a 10 second break, keeps its rubies away from the spawn point (one sat right where players arrive), and installs scoreKit first so a world gets one MatchFlow package (see the guide for what installing MatchFlow first does).
- **Changelog:** older entries say what the engine changed instead of citing issues that are now closed.
### 1.4.3
- **Played on two real machines again.** Two editors on one account played the Hall of Fame world's coin round together, and both showed the same scores, standings and board before, during and after the round. Known limits describes it in place of the 1.3.0 test.
- The Hall of Fame world's opening scene has a proper description, and a leftover scene from an earlier install check is gone. No code change.
### 1.4.2
- **A steadier test.** The test that checks scoreKit sees pickupsKit's counter took one look 1.1 s after adding a stand-in counter. On a slow editor (frames of 250 ms and more) the counter's component sometimes attached too late for that look, and the test failed in about 2 runs of 7 in a freshly installed world. It now waits up to 3 s for the answer. scoreKit's own check (once a second) is unchanged.
### 1.4.1
- **The test suite passes right after a play session.** Two tests read what a play session (or a second engine in the room) leaves on a machine. The refused-prediction test sent its refusal from a made-up machine, which a kit that has a keeper rightly ignores; it now comes from the keeper. The toast test found the toast HUD scoreKit had made before a local player existed.
- **Fixed: toasts follow this machine's player.** scoreKit's navUiKit toast HUD kept the player key it was made with. When the local player arrived later (the HUD was made before the player spawned, or in edit mode before Play), it stayed keyed to no one. It is now made again for the player who is here.
- **Fixed: MatchFlow in the Hall of Fame world, and in what 1.4.0 installed.** Eight MatchFlow files in this world had been brought to MatchFlow's current release by hand after an update left them behind. Their recorded references still named older MatchFlow modules, so MatchFlow stopped every frame with "attempt to call a nil value" (`MatchFlow.component:255`), and 1.4.0 carried those eight files to the worlds that installed it. MatchFlow is now a clean install of its release (2bd2d5f), and every scoreKit file records it.
### 1.4.0
- **Two guides ship in the package** (see Guides): *How to add a score and combo system to my game*, the how-to, and *Make an arcade game with a score, combos and a leaderboard*, an example that builds a two-player coin round with scoreKit, MatchFlow and menusKit from a brand-new world. The example was followed step by step in a throwaway world before release.
- **Installs now run the code they install.** A file's record of which version of each module it requires is kept against that file's bytes. Files whose bytes had not changed since 1.3.0 kept pointing at older versions of `theme`, `displays`, `boards`, `popups` and `results`, so an install fetched those older copies into `deps/` and loaded them: the 1.3.1 pixel-font fix never reached an installed kit. Every file in 1.4.0 has new bytes, so each one records the versions it ships with. The test suite failed 2 of 113 in a fresh 1.3.1 install and catches this.
- **README checked on today's engine, in a brand-new world with only scoreKit installed.** A new world now comes with `scenes/main.scene`, so the first example no longer asks you to create it (that step failed with "'main' already exists"). The engine now finds a kit that came as a dependency by its bare name (`MatchFlow.MatchFlow`), and finds a moved kit at its new place without an editor restart, so the two Known limits about those are gone. Installing scoreKit no longer leaves `versions/` folders (other kits can still leave their own).
- **Built and tested against MatchFlow 1.3.1 and navUiKit 1.2.1**, the versions a scoreKit install brings, in the Hall of Fame world too.
- On-screen text drops its dashes: "Held, will retry", "No scores yet. Be the first!", "You're on top. Hold the line!", "First run: this is the time to beat".
### 1.3.1
- **One end-of-round screen at a time.** With MatchFlow, the results card waits until MatchFlow has finished its own results on that machine and moved on to the break. Before, it only waited while that machine already read "results": on a machine that wasn't hosting, the round's results arrive a moment before its MatchFlow switches over, so the card and MatchFlow's podium were drawn on top of each other. A card the break has passed by is skipped, and one still up when the next round counts down closes.
- **pickupsKit's counter and MatchFlow's standings no longer overlap.** With `corner = "auto"`, the score display moves to the bottom-left when pickupsKit's counter is in the top-left (`H.pickupHudCorners()`). The gallery puts the counter top-left, so MatchFlow's standings keep the top right.
- **Clean text in the pixel font.** The arcade look's pixel text read text byte by byte, so "·" and "…" (and any accented letter) drew as one "?" per byte, and "@" had no glyph. It now reads characters, draws "·", "…", "@", brackets, quotes and other punctuation, and draws accented letters as their plain letter (`T.pixelGlyphs`). A test renders every display, board and results screen in every look with awkward names and fails on any "?".
- **Gallery:** its board is now "Hall of Fame" (id `hallOfFame`), with both players' rows carried over, and the demo boards are titled "Gem Dash". A stray empty entity left in the gallery scene is gone.
### 1.3.0
- **`Score.add`, `Score.penalty` and `Score.bonus` return the points awarded.** On the keeper they returned nothing; they now return the amount after the combo multiplier (10, 10, 20 for three quick 10s), negative for a penalty, 0 when nothing was awarded. Off the keeper they return 0 with keeper-only scoring, or the predicted amount with `acceptRemote = true`. See "What `Score.add` returns".
- **The gallery's coin round is built on pickupsKit 2.3.8**, installed in the Hall of Fame world under `/source/deps/` like MatchFlow and navUiKit. Its coins, ruby and damage orb are pickupsKit pickups placed in the scene, scored by `ScorePickups`. The world's own one-off coin script is gone.
- **`ScorePickups` and `scoreKit.pickups`: pickups that score.** Every pickupsKit grab becomes one `Score.add` on the machine keeping the score, for the player who took it, from a points table such as `"goldCoin=10, ruby=50, damageOrb=-25"`. Before any `ScoreKit` exists, the senior machine scores the grab and its `Score.add` creates the kit. pickupsKit is now a dependency of scoreKit, next to MatchFlow and navUiKit.
- **README checked in a brand-new world with nothing but scoreKit installed.** The first example now says how to make the scene it goes in (a new world has none), and the MatchFlow example names MatchFlow as `~MatchFlow.MatchFlow`, the form that resolves when MatchFlow came with scoreKit.
- **Known limits name only open issues.** The engine now sends a table with an `x` field, and an entity inside a table, between machines intact, so the notes about working around them are gone. Added #10762 (the partial copy an install writes), #19284 (the sign's face) and #18688 / #19114 (two players in one engine), plus two limits the engine has fixed since (a kit that came as a dependency was not found by its bare name, and a moved kit needed an editor restart).
- **Played on two real machines.** The coin round with two editors on the relay: every grab on the machine that wasn't hosting scored exactly once, for its own player.
- **Fixed:** navUiKit's HUD modules pin different copies of navUiKit's core, so toasts sent through `Nav.toast` reached a core the HUD never read. scoreKit hands toasts straight to its HUD (or to the world's own navUiKit HUD), and its HUD shows only the toast band.
### 1.2.1
- MatchFlow and navUiKit are installed as dependencies under `/source/deps/<origin world>/` in the Hall of Fame world, next to controlsKit, the layout an install of scoreKit gives you. No code change: scoreKit already reaches them by package name.
- Known limits now cite the engine issues behind them (#19283, #14448), and say what the engine changed for the ones it has fixed since: positions sent between machines now arrive as tables, an entity inside a sent table now arrives on the other machine, and keys with prefixes are carried intact.
- **Fixed:** two writes to the same board row are sent in order. A `board:remove` made while that row's save was still on its way used to be folded into the save already sent and lost, so the row came back.
- **Fixed:** navUiKit is looked up when toasts first need it, and again (at most once a second) until it is found. Right after an install or an editor start the first lookup can fail, and that used to leave toasts off for the whole session. `H.navModules()` returns the navUiKit modules in use.
### 1.2.0
- **One account signed in on two machines is two players.** Each session gets its own key (`u:<id>`, `u:<id>#2` …) and name ("Nova", "Nova (2)"), so the round ranking, the results and the board show both with their own points. Before, both sessions shared one key: one machine's points were credited to the other, and the board listed one row.
- **Only players who are here are ranked, placed and posted.** Absent player keys are dropped at the next round's start and never count toward "1st of N".
- **`board:remove(player)`**: the writer in charge can take a stale or test row off the current season. A queued delete hides the row at once.
- Removed a leftover test player ("Player Two") from the gallery's board.
### 1.1.0
- **Keeper-only scoring by default** (`acceptRemote` now defaults to `false`). Another machine's `Score.add`, `bonus`, runs and board posts are refused at the keeper, and not sent or predicted at all once a keeper is known. The same code can run on every machine and count once. `acceptRemote = true` restores self-reported points within the caps.
- **A board post from another machine never carries its own value.** The keeper posts the score it counted, to the kit's board only. Time boards take only runs the keeper timed.
- **Only the keeper's standings, awards and round results are believed**: forged `snap`/`ev`/`nak` messages from other peers are ignored.
- **Points rounds are ranked on scoreKit's counted scores**, not on MatchFlow's standings. MatchFlow's places are used for `race`, `lastStanding` and `kingOfTheHill` only.
- **Fixed:** after leaving play and pressing Play again (or any rebuild that replaces the MatchFlow component on the same entity), scoreKit kept the old, frozen match. It refused every point as "not playing" and never saw the round end. It now follows the live component.
- Gallery: an **Everything** tab with every display, leaderboard and results screen on one page, all drawn from one shared feed (live scores when there are any).
### 1.0.0
- First release: `Score.add` with combos and multipliers, ratings (stars and S to D grades), rounds through MatchFlow, toasts through navUiKit, persistent boards (top scores, best times, personal bests, seasons, locked writers, held results), 13 displays, 5 popup styles, 6 board views with the `ScoreSign`, 4 results screens, 5 looks, the `ScoreGallery`, and the `scoreKit` test suite.
# Trapline 1.5.8
Checkpoints, traps and lives for platformers, obstacle courses and runners, in any Zero world, multiplayer-safe.
- **Touch a checkpoint** and it becomes where *you* come back.
- **Fall off the map or get caught by a trap** and you lose a life and reappear at your last checkpoint.
- **Run out of lives** and it's game over for you, with a Try Again button.
Every player's progress is their own: when you die you go back to *your* checkpoint and lose *your* life, and nobody else's lives or checkpoint change. Every player sees the traps move in step.
It is built on the kits it needs, not beside them. **SecondWind** does all damage, death and respawn and writes the kill feed ("Kai was killed by Spinning saw"), **Lifeline** places respawns, **juiceKit** plays checkpoint, death and respawn effects, and **barsKit** draws the heart and pip displays. A cartoon, fantasy, sci-fi or pixel game each has at least two kill zones and two lives displays of its own style to pick from.
Every part has **one setting, `look`**, that picks what it is. Change it, in the editor or with `TL.setLook`, and the part turns into another one. A world-wide `theme` switches every checkpoint and lives display left on `auto`.
| part | looks |
|---|---|
| `Trapline.Checkpoint` (6) | `flag` cartoon, `campfire` fantasy, `beacon` sci-fi, `crystal` fantasy, `bell` pixel, `teleporter` sci-fi |
| `Trapline.Hazard` (12) | `spikes` cartoon, `lava` fantasy, `saw` cartoon, `axe` fantasy, `crusher` sci-fi, `laser` sci-fi, `electric` sci-fi, `poison` fantasy, `rocks` cartoon, `flame` pixel, `pit` pixel, `water` cartoon |
| `Trapline.KillZone` (9) | `invisible` minimal (a boundary you can't see), `abyss` fantasy (a visible void you'd fall into), `grid` sci-fi (a glowing out-of-bounds wall), `sea` cartoon (cartoon water with a shark fin), `clouds` cartoon (a drop to the clouds far below), `thorns` fantasy (a bramble wall), `plasma` sci-fi (a crackling plasma pool), `pixelvoid` pixel (a black pit with a blocky rim), `pixelfence` pixel (a red and white warning fence) |
| `Trapline.LivesDisplay` (12) | `hearts` cartoon, `counter` cartoon, `balloons` cartoon, `potions` fantasy, `shields` fantasy, `candles` fantasy, `pips` sci-fi, `battery` sci-fi, `holo` sci-fi, `tokens` pixel, `pixelhearts` pixel, `arcade` pixel |
The world this kit comes from opens on a showcase walk with every checkpoint, hazard, kill zone and lives display labelled, which you can play with friends.
## Guides
Two guides ship inside this package, in `Trapline.package/guides/`, and install with it. Open them in the editor's Docs panel (search "Trapline"), with the `guides` tool by the path in the link, or ask your agent for them by name:
- **[How to add checkpoints, traps and lives to my game](Trapline.package/guides/how-to-add-checkpoints-traps-and-lives-to-my-game)**: the how-to, for someone who just found the kit. What it is and what to do first, checkpoints and coming back at your last one, traps and falling off the map, lives and the game over screen with Try Again, restarting a run, how it behaves with several players, and switching any part to another look with its one setting.
- **[Make an obstacle course game with checkpoints, traps, lives and a game over screen](Trapline.package/guides/make-an-obstacle-course-game-with-checkpoints-traps-lives-and-game-over)**: the example. An empty world becomes a short obstacle run with three checkpoints, spikes and other traps, a fall-off edge, a lives counter and game over, plus coins from pickupsKit, a finish time from scoreKit, a title, pause and game over flow from menusKit, and the reached checkpoint and best time saved with saveKit, so Continue on the title screen takes you back to your last checkpoint. Every step of it was followed in a new world before release.
## What's new in 1.5.8
- **One health stack.** Trapline reaches Lifeline (spawn points, the respawn picker) through SecondWind's new `HK.base()` instead of requiring it beside SecondWind, so health has one line of ownership: Trapline, then SecondWind, then Lifeline (which comes with SecondWind). Needs SecondWind 1.4.8.
- **barsKit loads only when it draws.** The `hearts` and `pips` lives displays load barsKit the first time one is drawn; a course with another display (or none) never loads it. `displays.hasBarsKit()` is now a call.
## What's new in 1.5.7
- A Course with `lives = 0` gives unlimited lives: a death sends you back to your checkpoint and never ends in game over (the lives display stays at 0 lives left).
## What's new in 1.5.6
- **On the current kits.** Trapline is now built and tested on SecondWind 1.4.5, Lifeline 1.0.4, MatchFlow 1.3.2, juiceKit 1.2.10 and barsKit 1.4.5, so installing it no longer brings the older releases of those kits alongside the current ones. Nothing else changed.
## What was new in 1.5.5
- **Tests run wherever Trapline is installed.** Its tests find the package's own files wherever it is installed (at /source, or under /source/deps when another package installs it). In a world where platformer3dKit installed it, 10 of its tests failed because they read README.md, package.yaml and source files from a fixed /source/Trapline.package path. The check that this world runs exactly the dependency builds named below now asks for that exact build only in Trapline's own world; elsewhere the world decides the build (an @builtin upgrade repins it, another package pins its own), so it asks for the same version.
## What's new in 1.5.4
- **A checkpoint that draws nothing:** `look = "none"` builds no checkpoint model and animates nothing per frame, while touching it, its order, coming back at it and its events work as with any other look. For games that draw their own checkpoint (a 2D sprite, say); it costs next to nothing. It is not one of the catalogue looks, so counts and look cycling are unchanged.
- **`Trapline.deps` reports the copies Trapline runs.** `D.check()` reads each kit through Trapline's own pinned reference instead of looking the kit up by name, so a world that also holds another copy of a kit (another install's, or an older one an earlier install left behind) no longer reads as running the wrong version.
- **One version everywhere:** package.yaml, `TL.VERSION`, the catalogue and this README all say 1.5.4.
## What was new in 1.5.2
- **A clearer description on ZeroMind:** what the kit gives you, its four styles, and that one install brings the kits it is built on. The kit itself is the same as 1.5.1.
## What was new in 1.5.1
1.5.0 was out for a few minutes with the example guide's course turned round the wrong way; 1.5.1 is the release, with the guide as it was played through in a new world.
- **Six more kill zones and eight more lives displays**, so every style has a few of its own. Kill zones: a cartoon `sea` with a circling shark fin, a cartoon `clouds` sky drop, a fantasy `thorns` bramble wall, a sci-fi `plasma` pool, a pixel `pixelvoid` pit and a pixel `pixelfence`. Lives displays: cartoon `balloons` that pop, fantasy `potions`, `shields` and `candles`, sci-fi `battery` and `holo`, and pixel `pixelhearts` and an `arcade` "1UP REST x 03" counter. Each is the same component with a different `look`, so a world swaps between them with that one setting.
- **On the current kits.** Trapline is now built and tested on SecondWind 1.4.4, MatchFlow 1.3.1, juiceKit 1.2.8 and barsKit 1.4.3 (Lifeline 1.0.1 as before), so the how-to now links those kits' own guides, SecondWind's arena example included, and they open in the Docs panel.
- **The first example starts in view.** In a scene made from the player template the camera looks down -Z when you press Play, so the first example now runs that way, with each checkpoint turned round so you come back facing the run. Before, it was built behind you. (A new world's own main scene faces +Z, which is where the example guide's course runs.)
- **Lighter to edit.** While you edit, the previews of checkpoints, hazards and kill zones move at 15 frames a second instead of every frame, spread over frames; a level full of Trapline parts no longer slows the editor down.
- **A kill zone over the spawn is named.** If a kill zone covers a player spawn (easy to do with the default 40 m box at the origin), Trapline warns once, by name, instead of players losing lives as they appear.
- **Clearer docs.** The README and the how-to say that R and Enter for Try Again only work once you have clicked into the game view, and the example guide says why it picks each setting and kit.
- **The showcase:** the four pads at the start are one per style (cartoon, fantasy, sci-fi, pixel); step on one for its look and again for the next. A new stretch of the walk crosses a bridge between the six new kill zones, and the finish gate now celebrates with confetti and a card with your time and lives.
## What was new in 1.4.2
- **Every link in the how-to guide opens.** Its links to SecondWind's, juiceKit's and barsKit's guides pointed at guides that only those kits' newer releases have, so with the versions Trapline comes with (SecondWind 1.2.0, juiceKit 1.2.1, barsKit 1.2.0) they opened nothing. They now open those kits' READMEs, for exactly the versions Trapline installs.
- **SecondWind's arena guide is pointed to.** *Build a small arena game with health bars, hit markers and respawn* ships with SecondWind 1.3.0 and later, not the 1.2.0 Trapline comes with, so the how-to links SecondWind's page on ZeroMind, where it can be read, and says which version it is written for.
- **The example guide links each kit's own example game:** pickupsKit's coin and gem collecting game, scoreKit's arcade game, menusKit's pause menu game and saveKit's save slots, level unlocks and Continue game, next to their how-to guides. They open once the example's Step 2 has installed those kits.
- **A test opens every link** in both guides: Trapline's own guides, the READMEs of the kits Trapline ships with, a web page, or (in the example only) a guide of one of the four kits the example installs.
## What was new in 1.4.1
1.4.0 was published for a short time during this release's checks, with an earlier draft of the example guide. 1.4.1 is the release: the same kit, with the example guide as it was played through in a new world.
- **Two guides** inside the package (see Guides above): a how-to and a step-by-step example game.
- **Checked again on the current engine.** The four bugs fixed in 1.2.0 and 1.3.0 were played again, twice each: the lives display pads read in full from the start, GAME OVER says "Lives lost: 3" after every Try Again, the player template is never in the runner list (with a second player's body present), and Try Again sends a living player back to the start.
- **Installing is quick and exact again.** Checked today, an install of 1.3.0 into a new world timed out on ZeroMind (it couldn't work out what to bring). This world now keeps each of the five kits as one install pinned to the commit its version came from, and an install of 1.4.0 into a new world took under 3 seconds and brought exactly the versions in Dependencies.
- **A test that no longer depends on child order.** One test compared a hazard's parts in the order the engine lists an entity's children, which the current engine does not keep the same between two identical builds. It now compares them sorted. The kit itself didn't change for it.
## What was new in 1.3.0
- **Try Again is a clean run.** The deaths count (`deaths` in `TL.state`, on the `Trapline.Runner` and on the body's health) goes back to 0 on every Try Again, together with lives going back to full. GAME OVER's "Lives lost" shows that count, so it reads 3 after every run with 3 lives, however many runs you play. The separate `lostThisRun` count 1.2.0 added next to it is gone: read `deaths`.
- **Every kit at its exact version.** Trapline now names the exact version of each of the five kits it is built on (see Dependencies), and installing Trapline brings those versions, the same ones this world runs. 1.2.0 could bring a newer juiceKit (1.2.2) than the 1.2.1 it was built and tested with. `require("Trapline.deps").check()` says what a world runs of each kit.
- **More tests**: 65 in the package, including deaths going back to 0 over three runs and every kit's version.
## What was new in 1.2.0
- Installing is one call, with no order to follow.
- Try Again sends you back to the start (or the checkpoint) with full lives and health whether or not you're dead.
- `TL.runners()` lists real players only, never the player template (`TL.isTemplate(body)`).
- `TL.view()` and `TL.views()` report who sees whom across machines.
- The showcase's lives display pads read in full from the start.
## What was new in 1.1.0
- The kill feed names the hazard ("Kai was killed by Spikes"), and the hazard's own effect still plays on every screen.
- Kill zones have looks (`invisible`, `abyss`, `grid`).
- The first example shows four hazards and two checkpoints.
- Each network event is heard once, and the host can check the trap clock with `TL.clockInfo().peers`.
- The showcase signs read from both sides, and no long dashes anywhere.
## Install
One call:
`zeromind_install guid=57c0995a-9ba8-4e5a-a7ca-341e8706c7c1` (Trapline)
That's all. Trapline brings the five kits it is built on with it, each at the exact version in Dependencies, under `/source/deps/`. Your scripts reach everything through `Trapline.api` and the `Trapline.*` components.
To also call a kit from your own scripts (`require("SecondWind.api")`), install it at the same version in a call of its own, before or after Trapline, with `ref` set to its build in the table below: for example `zeromind_install guid=5da0a53c-5953-4adc-80fb-f5afb02f6568 ref=0438275b43fd883e671f167f8b438f696e97c5be57badbda526881ed12a6d244` (SecondWind 1.2.0).
The copies under `/source/deps/` hold a few components Trapline doesn't use (Lifeline's projectile and HUD, the MatchFlow component, older copies of SecondWind's parts), which log `no root to resolve against` while the world loads. Trapline doesn't touch them, and play isn't affected.
## Dependencies
Trapline is built and tested on exactly these versions, and an install of Trapline brings exactly these:
| kit | ZeroMind id | version | build | what Trapline uses it for |
|---|---|---|---|---|
| SecondWind | `5da0a53c-5953-4adc-80fb-f5afb02f6568` | 1.4.8 | `caf5bbdf206dd5813040a7728f7a4bcd2afd76fbe2b352fecc810c2c6a45c868` | all damage, death and respawn, and the kill feed |
| Lifeline | `7b85ce05-3903-4374-b654-2d4ffea295a5` | 1.0.4 | `602a98c6e5202bd52ed60e275e11d06ca336dbdc9ce41507a4edc76c5acc8edf` | health under SecondWind, spawn points and the respawn picker; comes with SecondWind, and Trapline reaches it through SecondWind (`HK.base()`) |
| MatchFlow | `31cf13b4-df7d-4888-85e2-7947a7301614` | 1.3.2 | `d2122b6ce481e3f483d17139b400f01d8a5e48e382d4c740c63bfad8554dc352` | SecondWind's rounds and countdowns |
| juiceKit | `eed55f6d-afaf-4767-83c5-539ef91e0dc5` | 1.2.10 | `98b784aedeb338392db0d7112c2d2896d1b927737d8c461059f063bfd47d52bd` | checkpoint, death and respawn effects |
| barsKit | `c154eb07-ce7c-48ca-8232-4ce1a8754214` | 1.4.5 | `09133dec0da4eebdac79ebaa403a1dcff1cd84ae9df0dd5730b59a37708d50a2` | the hearts and pips lives displays |
SecondWind, Lifeline and MatchFlow are required. juiceKit and barsKit are optional: without juiceKit there are no effects, and without barsKit the `hearts` and `pips` displays draw Trapline's own hearts and pips. A newer version of a kit may work, but these are the versions Trapline is checked on.
`require("Trapline.deps")` holds this table (`D.kits`), and `D.check()` says what your world runs of each kit and whether it is this exact version (`matches`).
## First example
A scene made from the engine's `player` template (`scene.create("course", "player")`), like the one this example was checked in, builds its player in its `build.luau` with `local body = entity.spawn("body", { parent = prototype })`. Paste this at the end of `content()`, after the player setup:
```lua
local TL = require("Trapline.api")
local HAZARD = asset.resolve("Trapline.Hazard", "component")
local CHECKPOINT = asset.resolve("Trapline.Checkpoint", "component")
-- Lives and SecondWind health for every player who joins.
TL.attach(body)
-- Your lives in the top-left corner, and the game over screen.
entity.spawn("Lives").component.add(asset.resolve("Trapline.LivesDisplay", "component"), { look = "hearts" })
-- A short run straight ahead of the spawn: four hazards and two checkpoints.
-- Ahead is -Z, the way the player template's camera looks when you press Play,
-- and each checkpoint is turned round so you come back facing the run.
local TURN = { 0, 1, 0, 0 }
entity.spawn("Spikes", { position = { 0, 0, -5 } }).component.add(HAZARD, { look = "spikes" })
entity.spawn("Flag", { position = { 3, 0, -8 }, rotation = TURN }).component.add(CHECKPOINT, { look = "flag", order = 1 })
entity.spawn("Saw", { position = { 0, 0, -11 } }).component.add(HAZARD, { look = "saw" })
entity.spawn("Lava", { position = { 0, 0, -16 } }).component.add(HAZARD, { look = "lava" })
entity.spawn("Campfire", { position = { 3, 0, -19 }, rotation = TURN }).component.add(CHECKPOINT, { look = "campfire", order = 2 })
entity.spawn("Laser", { position = { 0, 0, -22 } }).component.add(HAZARD, { look = "laser" })
```
Pasting it into a new world's own `scenes/main.scene` instead? That scene's camera looks down +Z, so drop the minus signs from the `z` positions and leave out `rotation = TURN`.
Press Play. Three hearts sit in the top-left corner.
1. Walk forward onto the spikes: you lose a heart, the kill feed says you were "killed by Spikes", and you come back where you started.
2. Touch the flag: it runs up its pole, and "CHECKPOINT!" shows.
3. Get caught by the saw, which runs back and forth across the path: you come back at the flag, not at the start.
4. Cross the lava (go round it, or lose a heart and come back at the flag) and touch the campfire: it lights, and it is your checkpoint now.
5. Time the laser grid: walk through while its beams are off.
6. Lose your third heart: GAME OVER, "Lives lost: 3". Press Try Again (or R / Enter) and you start a clean run: three hearts, and the deaths count back to 0. R and Enter only work once you have clicked into the game view; right after Play the keyboard still belongs to the editor, so click the game once or use the button.
7. Walk off the edge of the ground: falling below `Course.fallLimitY` (-25 m) costs a life too.
To turn the spikes into an electric floor, change one word: `look = "electric"`.
With no further setup:
- 3 lives each;
- back 1.5 s after a death, with 1.5 s of spawn protection;
- checkpoints count forward only;
- Try Again starts a clean run from the start: full lives and health and a deaths count of 0, whether you are out of lives or not.
A `Trapline.Course` changes any of it (see Settings).
Without `TL.attach`, a player who touches a hazard or checkpoint is given Trapline at runtime (`Course.autoSetup`). `TL.attach` in the build is still the better way, because it puts health on the body before anyone joins.
## Switching looks
```lua
TL.setLook(spikes, "lava") -- any Hazard, Checkpoint or LivesDisplay; same as setting `look`
TL.setTheme("pixel") -- every part whose look is "auto": bells, 1-UP tokens
TL.find({ kind = "hazard", style = "scifi" }) -- crusher, laser, electric
TL.find({ kind = "hazard", family = { "moving", "timed" } })
TL.catalog() -- everything, labelled, with descriptions
```
Every catalog entry carries:
- `kind`: `checkpoint`, `hazard`, `killZone`, `livesDisplay`;
- `family`: checkpoints `marker`/`light`/`pad`; hazards `static`/`moving`/`timed`/`fall`; displays `icons`/`counter`/`bar`;
- `style`: `cartoon`, `fantasy`, `scifi`, `pixel` (the kill zone is `minimal`);
- a `description`, plus `before`/`after` for checkpoints, and `damageType`, `size` and `cycle` for hazards.
`TL.find` refuses an unknown key or kind by name, so a typo never just returns nothing.
## Settings
### `Trapline.Hazard`
| field | default | what it does |
|---|---|---|
| `look` | `spikes` | What the hazard is (the 12 above). |
| `sizeX/Y/Z` | 0 | Footprint in metres; 0 takes the look's own size. +Z is the front (the flamethrower blasts along +Z; the saw runs and the axe swings along X). |
| `cycle` | -1 | Seconds per loop for moving and timed looks; -1 is the look's own, 0 is always on. Spikes pop up and down when `cycle` is above 0. |
| `offset` | 0 | Seconds to shift it along its loop, to stagger a row of the same trap. |
| `damage` | 0 | 0: touching it costs a life. Above 0: this much SecondWind damage per hit instead. |
| `interval` | 1 | Seconds between hits when `damage` is above 0. |
| `grace` | -1 | Seconds you can stay in before it gets you; -1 is 3 s of breath for `water`, 0 for everything else. |
| `label` | none | Its name in the kill feed and the "-1 LIFE" message; empty uses the look's name. |
| `active`, `playersOnly` | true, true | Switch it off; let it catch non-players with SecondWind health too. |
Hits use the look's SecondWind damage type, so you see SecondWind's effects: fire from lava, sparks from saws, poison bubbles, electric arcs. Method: `hazard:isDeadly(body, t?)`.
### `Trapline.Checkpoint`
| field | default | what it does |
|---|---|---|
| `look` | `auto` | One of the 6 looks, or `auto` to follow the theme. |
| `order` | 0 | Its place along the course. With `forwardOnly`, touching one with a lower order than yours does nothing. Leave every order at 0 and the latest one touched counts. |
| `label` | none | Its name in "CHECKPOINT!" and "Back at … in 1.5". |
| `radius`, `height` | 1.5, 3 | How close counts as touching it. |
| `restoreLives` | false | Refill lives when reached. |
| `preview` | `before` | Which state to show while editing (`before` or `after`). |
You come back just in front of it (its +Z side, facing the way it faces), or on it for the teleport pad. Each machine draws checkpoints as *its own* player has reached them.
### `Trapline.LivesDisplay` (one per scene, plain entity)
`look` (`auto`, or any of the twelve: `hearts`, `counter`, `balloons`, `potions`, `shields`, `candles`, `pips`, `battery`, `holo`, `tokens`, `pixelhearts`, `arcade`), `anchor` (`topLeft`, `topCenter`, `topRight`, `bottomLeft`, `bottomRight`), `size`, `offsetY`, `showGameOver`, `showMessages` ("-1 LIFE", the respawn countdown, "CHECKPOINT!"), `showBreath` (bubbles under deep water), `visible`.
### `Trapline.KillZone`
A box of `sizeX × sizeY × sizeZ` (default 40 × 4 × 40) centred on its entity. Anyone who enters it loses a life, whatever it looks like. Pick the look with `look`:
| look | style | what you see |
|---|---|---|
| `invisible` (default) | minimal | Nothing in play; a see-through red box while editing (`showInEditor = false` hides that too). Put it under a level to catch falls. |
| `abyss` | fantasy | A black shaft at the top of the box with drifting violet mist, rising motes and a glowing brink. Put it in a gap in the floor, with its top just under floor level, so players see the drop. |
| `grid` | sci-fi | A glowing red holographic grid on every side, with a scan line sweeping up it: a visible out-of-bounds wall. |
`label` names it in the kill feed; empty uses the look's own (`a fall`, `the abyss`, `the out-of-bounds field`). Also `active` and `playersOnly`. Falling below `Course.fallLimitY` costs a life with no zone at all.
```lua
local gap = entity.spawn("Gap", { position = { 0, -2.3, 30 } })
gap.component.add(asset.resolve("Trapline.KillZone", "component"), { look = "abyss", sizeX = 8, sizeY = 4, sizeZ = 4 })
TL.setLook(gap, "grid") -- one setting turns it into a glowing wall
```
### `Trapline.Course` (optional, one per scene, on a synced entity)
| field | default | what it does |
|---|---|---|
| `lives` | 3 | Lives each player starts with and gets back after game over. |
| `respawnDelay` | 1.5 | Seconds between losing a life and coming back. |
| `fallLimitY` | -25 | Falling below this costs a life. |
| `theme` | `mixed` | `mixed`, `cartoon`, `fantasy`, `scifi`, `pixel`: the look of every `auto` part. |
| `forwardOnly` | true | Checkpoints only count going forward. |
| `restartFrom` | `start` | Where Try Again (and `TL.restart`) puts you, dead or alive: `start` or `checkpoint`. |
| `spawnProtection` | 1.5 | Seconds you can't be hurt after coming back. |
| `autoSetup` | true | Give players Trapline at runtime when the world didn't call `TL.attach`. |
| `feedback` | true | Play the juiceKit effects. |
```lua
local course = entity.spawnSynced("Course")
course.component.add(asset.resolve("Trapline.Course", "component"), { lives = 5, theme = "scifi" })
```
## `Trapline.api`
`local TL = require("Trapline.api")`. A player argument takes a body entity, a component or an entity id.
| call | what it does |
|---|---|
| `TL.attach(body, opts?)` | SecondWind health (if missing, set to come back only when Trapline says) and a `Trapline.Runner`. opts: `lives`, `health`, `team`, `displayName`. |
| `TL.state(player)` | `{ lives, maxLives, checkpoint, checkpointLabel, checkpointOrder, gameOver, deaths, respawnIn, breath, dead, alive, name }`. `deaths` is the lives lost in this run: 0 at the start and again after every Try Again, and what GAME OVER shows. |
| `TL.reach(player, checkpoint, opts?)` | Make it their checkpoint, as if touched. `opts.force` ignores forward-only. |
| `TL.clearCheckpoint(player)` | Back to the start. |
| `TL.hit(player, info?)` | A hazard hit: `{ label, type, damage, origin, knockback, by, force }`. No damage means it costs a life. |
| `TL.loseLife(player, cause?)` | Take a life now, even through spawn protection. |
| `TL.setLives(player, n, max?)`, `TL.addLife(player, n?)` | Change lives (an extra life, a 1-UP). |
| `TL.restart(player)` | Try Again, a clean run: full lives and health, `deaths` back to 0, and back to the start (or the checkpoint, with `restartFrom = "checkpoint"`), whether the player is dead or still alive. |
| `TL.returnToCheckpoint(player)` | Put a living player back at their checkpoint without costing a life. |
| `TL.respawnPoint(checkpoint)` | `{ position, rotation }` where players come back. |
| `TL.hasReached(player, checkpoint)` | On the player's own machine. |
| `TL.on(event, fn)` | `checkpoint`, `lifeLost`, `respawned`, `gameOver`, `restarted`, `livesChanged`, or `"*"`. They fire on every machine. Returns a connection with `:Disconnect()`. |
| `TL.setLook(part, look)`, `TL.setTheme(theme)`, `TL.resolveLook(kind, look)` | Switch looks. |
| `TL.catalog()`, `TL.find(query)`, `TL.looks(kind)` | Browse what the kit offers. |
| `TL.now()`, `TL.clockInfo()` | The shared clock traps run on, and how this machine is synced to it. |
| `TL.view()`, `TL.views()` | What this machine sees (every real player's body: owner, lives, checkpoint, whether it is drawn here), and what each other machine last said it sees, by peer id. |
| `TL.runner(player)`, `TL.runners()`, `TL.checkpoints()`, `TL.course()`, `TL.rules()`, `TL.localPlayer()` | Lookups. `TL.runners()` lists real players only, never the player template. |
| `TL.isTemplate(body)` | Is this the body inside a `PlayerPrototype` (the template each joining player is copied from), not a real player? |
| `TL.capsuleBox`, `TL.capsuleSphere`, `TL.capsuleDisc` | Shape tests, for your own hazard looks. |
Modules: `Trapline.catalog` (the data), `Trapline.hazards` with `hazardsGround` and `hazardsMotion` (each look's build, animate and danger), `Trapline.checkpoints`, `Trapline.killZones`, `Trapline.displays` (`D.render(look, info)` for your own UI), `Trapline.parts` (shape helpers).
### Your own hazard look
Add an entry to a hazards module: `{ build(root, cfg) -> h, animate(h, cfg, t, dt), danger(cfg, t, cap) -> boolean }`. `t` is the shared clock, so make `animate` and `danger` depend only on `t`. Then every player sees the same thing, and the danger matches what they see. The contract is written at the top of `Trapline.hazards`.
## Multiplayer
- **Progress is per player.** Lives and checkpoint live in a `Trapline.Runner` on each player's own body, which only that player's machine changes. The fields are synced, so everyone can read everyone's lives.
- **Each machine tests only its own player** against hazards, kill zones and checkpoints. A hit goes through SecondWind on that machine, so a death, its effects and the kill feed reach everyone through SecondWind. The hit that takes a life goes in as SecondWind's `environment` type with the hazard's name, because that is the type SecondWind's feed names a cause for ("Kai was killed by Lava"); every machine then draws the hazard's own effect (flames, sparks, bubbles) from the `lifeLost` event, whose `damageType` carries the hazard's real type.
- **One respawn per player.** Trapline gives Lifeline a respawn picker (`Lifeline.setSpawnPicker`). When SecondWind brings a body back, Lifeline asks Trapline where to put it, and the answer is that player's own checkpoint. If your world sets its own picker, set it after Trapline loads and fall back to `TL.respawnPoint`.
- **Traps move in step.** Moving and timed hazards run on `TL.now()`, the host's clock. Each machine asks the host for the time (`trapline:ping`/`trapline:pong`) and keeps the answer with the shortest round trip. A hazard's pose and its danger depend only on that time, so every machine shows the same blade in the same place, and the danger matches what each player sees.
- **Events** go to every machine on `trapline:evt`. Each carries an id, and a machine hands each id to its listeners once, so an event that arrives twice (a hot reload while playing leaves an extra network listener behind) is still heard once.
- **Clock check:** on the host, `TL.clockInfo().peers[peerId].error` says how far each other machine's trap clock is from the host's, in seconds.
- **Who sees whom:** every 3 s in play, each machine sends what it sees on `trapline:view`: every real player's body, its owner, its lives and checkpoint as that machine reads them, and whether it is drawn there. `TL.views()` on any machine lists the other machines' reports by peer id, and `TL.view()` is this machine's own, so one machine can check that everyone sees everyone and agrees on their progress.
- **Players' lives are their own business.** As with SecondWind, a modified client could lie about its own lives. Trapline doesn't try to stop that.
## Tests
`tools.use("tests", "run", { suite = "trapline" })` runs 69 tests. They cover:
- every catalog label and filter;
- that every hazard look builds, animates, is deadly where it looks deadly and safe elsewhere;
- that timed hazards switch on and off, and that a pose depends only on the shared time;
- that every checkpoint looks clearly different before and after;
- that every lives display draws at every count from full to none and right after a life is lost, and that each of the cartoon, fantasy, sci-fi and pixel styles has at least two kill zones and two lives displays;
- the shared clock's maths, and the host's per-machine clock report;
- that every event is delivered once however many times it arrives;
- checkpoints, forward-only and per-player checkpoints;
- life lost, respawn, game over and Try Again (dead or alive, from the start or the checkpoint, with full lives and health), the deaths count going back to 0 on every Try Again over three runs, and that one player's death leaves another's lives alone;
- switching looks and themes;
- the kill feed naming the hazard, and a hurting hazard keeping its own damage type until the hit that kills;
- `TL.returnToCheckpoint` (with and without a checkpoint), `TL.runners` (and that it leaves player templates out), `TL.view` and `TL.views` (what each machine sees, bad and stale reports dropped), `TL.checkpoints` (in course order) and `TL.localPlayer`;
- every kill zone look, and switching kill zones with one setting;
- the five kits: each named with its id, version and build here and in `Trapline.deps`, and this world running exactly those versions;
- this README's first example (at least three hazards, every name it uses), the version, an issue number on every platform limit, and no long dashes anywhere in the package;
- the two guides: each is there with a description, each links the other, this README links both, and every link in them opens something with the kits Trapline ships with (or, in the example, the kits it installs).
They drive temporary dummies by hand, far from the scene.
Two-player play was checked live for 1.2.0, with the world playing on two computers (another computer hosting, the native editor joining), using `TL.view()` and `TL.views()` to read what each machine saw:
- each machine drew both players' bodies, and both agreed on who owned which;
- the editor's player lost a life and touched the Flag: 2 lives, Flag, on both machines, while the other player stayed at 3 lives with no checkpoint on both;
- the other player was then hit from the editor through SecondWind: their own machine took the life (3 to 2, back at the start, "was killed by" in the kill feed), and the editor's player stayed at 2 lives and the Flag.
## Known limits
- **The pit doesn't cut a hole in your floor.** It draws a deep shaft and takes a life when you step into it. To make players really fall, leave a gap in the floor under it, or use a `KillZone`.
- **Deep water is wading, not swimming.** Trapline doesn't add swimming: under water you walk on the bottom while your breath runs out over `grace` seconds, with bubbles on screen.
- **Hazards don't block movement.** They have no colliders: a crusher won't stop you walking under it, it just takes a life if it lands on you.
- **Two engines signed in to one account are one player** (#14448). To try two players yourself, sign the second engine or browser tab in with another account; with the same account, both bodies count as the same player and share one set of lives.
- **The web build runs at a lower frame rate** (#20750). Moving traps animate every frame; Trapline skips animating any part more than 45 m from the camera, which keeps a long course cheap, but a scene with many traps close together costs more in a browser tab than in the editor.
- **The browser check is done by hand** (#20946). An agent can't start a browser engine itself, so the web build of this release is checked by a person opening the world in a browser tab; everything here was played in the native editor.
- **ZeroMind's search text lags a release** (#19258). For a while after a new version, the description ZeroMind shows in search results is the one from the previous README.
# api
The one interface to pickupsKit: `local Pickups = require("pickupsKit.api")`.
- **Pickups:** `spawn`, `burst`, `setLook`, `collect`, `available`, `all`, `openChest`.
- **Counters:** `get`, `counts`, `allCounts`, `add`, `set`, `spend`, `reset`, `ledger`.
- **Letters:** `letters`, `spelled`, `giveLetter`, `clearLetters`.
- **Power-ups:** `givePowerup`, `powerup`, `powerupLeft`, `activePowerups`, `damageMultiplier`.
- **Catalog:** `looks` (filter by style, kind, effect or size), `look`, `styles`, `kinds`, `effects`, `powerups`, `counters`, `sizes`, `dependencies`.
- **Identity and collectors:** `keyOf`, `nameOf`, `localKey`, `localAvatar`, `owns`, `addCollector`, `removeCollector`.
- **Setup and events:** `setup`, `installDamageFilter`, and `on` for collect, counter, letter, powerup, powerupEnd, respawn, expire, burst and chest.
It also runs the components. The owner of each pickup decides claims and announces them with event ids that every peer de-duplicates, and only the ledger's owner writes counts. Functions starting with `_` are the components' hooks. The package README lists every argument.
# save
The one interface game code uses. Every player gets their own profile (level, XP, unlocks, stats, meta currency and the game's own fields) that is still there when they leave and come back. Each machine works on its own player's profile only, in that player's own data store, and the game's calls are the same in every saving style.
- Setup: `setup(opts)` (alias `configure`; mode, curve, curveTable, maxLevel, version, migrations, defaults, unlocks, xp, autosave, bankRate, namespace, screens, hud, kits, bridges, theme), `config`, `on(event, fn)` / `off(handle)` (event names in `EVENTS`).
- Progress: `addXP`, `kill`, `coin`, `finishLevel`, `checkpoint`, `died`, `newRun`, `addStat`, `unlock`, `event`, `buy`, `addCurrency`, `get` / `set` / `data` for the game's own fields; read back with `level`, `xp`, `xpToNext`, `totalXP`, `progress`, `currency`, `stat`, `stats`, `isUnlocked`, `unlocks`, `lastCheckpoint`, `view`, `profile`.
- Saving: `save(reason)`, `flush`, `reset`, `status` / `isReady`, `lastSaved`, `isDirty`, `migration`, `saveKey`. Autosave runs on level up, unlock, checkpoint, finished level and on a timer, as `autosave` says.
- Slots (slots style): `slots`, `activeSlot`, `newGame(i)`, `load(i)`, `copy(from, to)`, `delete(i)`.
- Other players: `isMine(player)`, `grant(player, xp)` for code that runs on every machine (takes effect only on that player's machine), `players`, `cardOf(player)`.
- Screens: `setScreens`, `screens`, `setTheme`, `theme`, `showPanel` / `showUnlocks` / `showProfile` / `showSlots`, `hidePanel`, `panel`, `toast`.
- Catalogue: `catalogue()` and `match(want)` list and rank the styles, curves and screens.
Calls whose names start with `_` are for the `SaveHost` component and tests. The first call in play spawns the host by itself, so a game never places it.
# core
The runtime behind `scoreKit.score`: who the keeper is, player keys, the keeper's checks on requests from other machines, prediction on the other machines, the synced snapshot, events, rounds (with or without MatchFlow), time runs and posting to the board. Game code uses `scoreKit.score` instead.
# profile
The rules applied to one saved record, as pure functions with no engine calls.
- XP and levels: `view`, `addXP`, `relevel`.
- Stats and unlocks: `addStat`, `unlock`, `ruleMet`, `checkUnlocks` (rules by level, by stat, by event) and `buy` (rules with a `cost`, paid in meta currency).
- Roguelite: `endRun` resets the run's XP and level, keeps unlocks, currency and lifetime stats, and banks part of the run's XP as currency.
- Public card: `card` builds what other players see, `sanitizeCard` makes a card read from another player safe to draw, `title` picks the best `title_` unlock.
`DEFAULT_UNLOCKS` is the unlock list used when a game names none.
Internal: `saveKit.save` drives these for the local player. Tests and tools can call them on any record.
# store
Where saves live. Each player's saves sit in their own `runtime_data.player(id)` store under `saveKit/<namespace>/...`, which survives leaving and rejoining. Any machine can read any player's store; the engine refuses a write to a store that is not the writer's own, so one player cannot change another's profile.
- Local player: `localId`, `localName`, `mine`, `get`, `set`, `delete`, `onChange`.
- Other players: `of`, `read`, `onAnyChange`, `users` (everyone connected).
- `key(ns, name)` builds a save's path; `writeOther` attempts a write to another player's store and returns the engine's refusal (used by tests and the showcase's tamper check).
- `use(fn, others)` swaps the live store for a stand-in in tests; `use(nil)` restores it.
Internal: `saveKit.save` does all reading and writing through this module. Read and write calls never raise; they return nil or `ok, error`.
# score
The module a game talks to: `local Score = require("scoreKit.score")`. `Score.add(player, 10)` and friends, ratings, rounds, time runs, boards, styles and events. The package README is its full reference.
# Trapline.api
The kit's public interface: TL.attach for players, per-player state (lives, checkpoint, game over), checkpoints and respawn (through Lifeline's spawn picker and SecondWind's revive), hazard hits through SecondWind, events (TL.on), the shared clock hazards run on (TL.now), switching looks and themes, and the labelled catalog (TL.catalog, TL.find). Required by every Trapline component and by game code. Full reference in the package README.