# Recipes: complete working code
Cooldown, pressure plates, kill reward, countdown, shop menu with click dispatch, parkour with checkpoints, top-N, mini-game round, boss fight (docs/recipes*.jc compile as is). Open for a model to copy.

## Recipes (docs/recipes.jc, compiles as is)
Recipe files are still edition 1 (no `edition 2` line); in an edition 2 file they behave the same (tested).
Every location is tied to `FLOOR_Y` (the top floor block of the world you deploy to — measure it, never guess): check each
teleport / spawn point against the real floor before copying a recipe into a live world.
```js
// FLOOR_Y — the top floor block of YOUR world (measure it: F3 / jmvcc client export; never guess, never y=64).
// Players stand at FLOOR_Y + 1; every teleport / spawn below is on the floor. Author's test world (yours differs — `jmvcc client world-profile`): 32x32 floor, x,z -16..15, top y=3.
inline var FLOOR_Y = 3
save var %player%_coins
save var %player%_last_use
game var round_running = 0

// per-player saved counter with default
event<player_join> {
  %player%_coins ??= 0
  player::message("Coins: ${%player%_coins}")
}

// cooldown via timestamp (ms); return ends the event. player_right_click fires once per click
// (verified with an empty off-hand); the hand filter is a cheap safety net
event<player_right_click> {
  if (value::event_equipment_slot != "hand") { return }
  line var now = value::timestamp
  if (now < %player%_last_use + 3000) {
    player::action_bar("Cooldown!")
    return
  }
  %player%_last_use = now
  player::message("Used!")
}

// pressure plate. event_block_type is the full block state ("minecraft:light_weighted_pressure_plate[power=0]"),
// so == with an id is always false (verified): check the block type with event_block_equals
event<player_interact> {
  if (value::event_interaction == "physical" && world::event_block_equals([item("stone_pressure_plate")])) {
    player::teleport(location(0, FLOOR_Y + 1, 0, 0, 0))
  }
}

// kill reward. Who the default player is in player_kill_player is an OPEN question (#10), so name
// the killer explicitly: %killer%_coins is the same saved variable as that player's %player%_coins
event<player_kill_player> {
  save var %killer%_coins
  %killer%_coins += 10
  player::message<killer_player>("+10 coins, victim: %victim%")
}

// countdown broadcast to everyone (on_range includes the end: 0..4 is 5 steps)
function countdown() {
  repeat::on_range(0, 4) { i ->
    player::title<all_players>("${5 - i}", "", 0, 20, 0)
    code::wait(1, time_unit = "seconds")
  }
  round_running = 1
}

// function with a return value
function reward_for(streak) {
  if (streak >= 10) { return 50 }
  if (streak >= 3) { return 20 }
  return 5
}

// random chance 25%
event<player_break_block> {
  var roll = variable::random_in_range(1, 100)
  if (roll <= 25) {
    player::give_items(item("diamond"), 1)
    %player%_coins += reward_for(3)
  }
}
```
Interaction types in `value::event_interaction`: left_click_air left_click_block physical right_click_air right_click_block.

## More recipes (docs/recipes-extra.jc: menu item kept through death, shop menu with click dispatch, parkour start/checkpoint/finish plates and fall, top-N, mm:ss via std::mmss)
```js
inline var FLOOR_Y = 3   // top floor block of YOUR world (measured); players at FLOOR_Y + 1
save var %player%_coins
save var top_scores   // map: player name -> score
game var %player%_running    // parkour: 1 while the timer runs
game var %player%_start      // parkour: run start (ms)
game var %player%_cp         // parkour: where to put the player back after a fall
game var %player%_cp_block   // parkour: block location of the last plate (checkpoint de-dup)
game var %player%_cp_n       // parkour: new checkpoint plates since the start
inline var CHECKPOINTS = 3   // parkour: gold plates on your course
inline var SHOP = "shop"

// menu item: a compass in slot 8 (the last hotbar slot, slots start at 0, verified) opens the shop.
// Give it in player_join AND player_respawn: a death drops it with the rest of the inventory.
// set_slot_item OVERWRITES whatever is in slot 8 — keep that slot for the menu item in your game.
// has_item first, so a player who moved it to another slot does not get a second one.
function give_menu_item() {
  if (player::has_item(item("compass"), comparison_mode = "TYPE_ONLY")) { return }
  player::set_slot_item(item("compass", "&aShop &7(right-click)"), 8)
}

event<player_respawn> {
  code::wait(1)   // the event asks for a wait before other code
  give_menu_item()
}

// no throwing it away with Q. That cancel_event stops a drop is NOT verified on the server: check it once.
event<player_drop_item> {
  if (world::event_item_equals(item("compass"), comparison_mode = "TYPE_ONLY")) { world::cancel_event() }
}

// shop: right-click with the compass opens a menu; custom_id tells our menu apart from others.
// player_right_click fires once per click (verified with an empty off-hand); the hand filter is a cheap safety net.
// show_menu fills slots 0, 1, 2... in list order (1st item = slot 0, verified). & codes in item() name/lore
// are compiled into colored item text.
event<player_right_click> {
  if (value::event_equipment_slot != "hand") { return }
  if (player::is_holding(item("compass"), comparison_mode = "TYPE_ONLY")) {
    player::show_menu([item("bread", "&aBread &7- 5 coins"), item("iron_sword", "&bSword &7- 50 coins")], "Shop", inventory_type = "CHEST", custom_id = SHOP)
  }
}

// shop click: cancel so nothing can be taken out, then ONE line per button: slot -> one call, return.
// Keep button code OUT of this event (a long else-if chain with inline code is hard to read and to
// fix). Here a button costs 6 blocks (2 of them pass the arguments); for a big menu give each button
// its own function without parameters: if (slot == 2) { buy_axe(); return }.
// Verified: event_slot starts at 0 = the 1st item of the show_menu list
// (event_item is the clicked item, if you prefer world::event_item_equals). Only the menu half reaches
// player_click_inventory: clicks in the player's own inventory go to player_click_own_inventory (verified).
event<player_click_inventory> {
  if (value::open_inventory_custom_id != SHOP) { return }
  world::cancel_event()
  line var slot = value::event_slot
  if (slot == 0) { buy(item("bread"), 5); return }
  if (slot == 1) { buy(item("iron_sword"), 50); return }
}

// give the item if the player can pay; params are shared locals, so callers must not reuse these names
function buy(goods, price) {
  if (%player%_coins < price) {
    player::message("Not enough coins: ${%player%_coins}/$price")
    player::play_sound(sound("entity.villager.no"))
    return
  }
  %player%_coins -= price
  player::give_items(goods, 1)
  player::play_sound(sound("entity.experience_orb.pickup"))
}

// parkour plates: stone plate = START (place exactly one), gold = checkpoint, iron = finish.
// Only the start plate starts the timer. If any checkpoint could, a player who just finished would step
// back on the last checkpoint and "finish" in 2 s: a fake best time. The finish also wants CHECKPOINTS new
// plates since the start, but bouncing between two checkpoints counts too: build the course so that the
// finish cannot be reached around it (that is the real protection).
// Physical interact fires about 2 times a second while standing (verified): a checkpoint counts only when it
// is a NEW plate: == of two value::event_block of the same plate is true (verified, bench/sneak/block-eq.jc).
// Block type via event_block_equals, not event_block_type == (always false). value::event_block is the plate's
// block location, value::location is where the player stands.
event<player_interact> {
  if (value::event_interaction != "physical") { return }
  if (world::event_block_equals([item("stone_pressure_plate")])) {
    run_start()
  } else if (world::event_block_equals([item("light_weighted_pressure_plate")])) {
    run_checkpoint()
  } else if (world::event_block_equals([item("heavy_weighted_pressure_plate")])) {
    run_finish()
  }
}

function run_start() {
  %player%_running = 1
  %player%_start = value::timestamp   // re-set while standing on it: the time counts from stepping off
  %player%_cp = value::location
  %player%_cp_block = value::event_block
  %player%_cp_n = 0
  player::action_bar("&aGo!")
}

function run_checkpoint() {
  if (%player%_running == 0) { return }
  if (value::event_block == %player%_cp_block) { return }
  %player%_cp = value::location
  %player%_cp_block = value::event_block
  %player%_cp_n++
  player::message("&aCheckpoint!")
}

function run_finish() {
  if (%player%_running == 0) { return }
  if (%player%_cp_n < CHECKPOINTS) {
    player::action_bar("&cMissed a checkpoint: ${%player%_cp_n}/$CHECKPOINTS")
    return
  }
  %player%_running = 0   // clear the run: the next one must begin on the start plate again
  player::message("&6Finish: ${std::mmss(value::timestamp - %player%_start)}")   // ms → "01:15", one action
}

// player_move fires many times a second: cheapest check (a number) first, block check second.
// For a full block underfoot use is_standing_on_block (a pressure plate is better caught by the event above).
event<player_move> {
  if (value::y_coord < FLOOR_Y - 3) {
    if (%player%_running == 1) {
      player::teleport(%player%_cp, keep_rotation = false)   // _cp is always set while a run is on
    } else {
      player::teleport(location(0, FLOOR_Y + 1, 0, 0, 0))
    }
    player::message("You fell!")
    return
  }
  if (player::is_standing_on_block(item("gold_block"))) {
    player::give_potion_effect(potion("speed", duration = 40))
  }
}

// record a score in the saved map. A never-set variable is the NUMBER 0, and set_map_value on it
// stops the code line with a server error — create the map first (verified on the server)
function save_score(score) {
  top_scores ??= variable::create_map_from_values([], [])
  top_scores["%player%"] = score              // put_map_value: a new key is added
}

// broadcast top-n "1. name - score". sort_any_map keeps the sorted order for get_map_key_by_index
// and for_each (verified on the server). on_range includes the end.
function broadcast_top(n) {
  line var sorted = variable::sort(map = top_scores, sort_order = "DESCENDING", sort_type = "VALUES")
  line var size = sorted.length()
  if (size > n) { size = n }
  if (size == 0) { return }
  repeat::on_range(0, size - 1) { i ->
    line var name = sorted.get_map_key_by_index(i)
    line var score = sorted[name]             // sorted is a map (sort_any_map above)
    player::message<all_players>("${i + 1}. $name - $score")
  }
}

event<player_join> {
  %player%_coins ??= 100
  save_score(%player%_coins)
  broadcast_top(5)
  player::message("Time: ${std::mmss(75000)}")   // "01:15"
  give_menu_item()                    // last: an error in it must not skip the coin setup ("Error isolation")
}
```

## Mini-game round (docs/recipes-round.jc, compiles as is)
Last player alive wins; copy the file and change spawns/kit. The shape that survives players leaving:
- ONE world loop in top-level code (world_start, no target) owns the flow,
  `enum State { WAITING, COUNTDOWN, RUNNING, OVER }` + `game var state: State`: WAITING → (enough players)
  COUNTDOWN with `player::title<all_players>` → RUNNING → OVER (results + break) → WAITING. Events only change shared state; a player-bound thread dies when its player quits.
  `value::players` / `value::all_players_names` work in world code with no target (verified).
  Top-level code is one code line and the loop is its last statement: only plain variable setup goes before it
  (a server error there would mean no loop at all — topic async «Error isolation»).
- `game var alive` = list of fighter names (`value::all_players_names` at start; re-check `value::players` there,
  someone may leave in the last countdown second). Every tick the loop keeps only names still in
  `value::all_players_names` — a `player_quit` handler may be cut off, do not rely on it.
- Each fighter gets its OWN spawn on the ground: `select::player_by_name(name)` then actions without
  `<selector>` (one spawn per index; no high drop — fall damage kills everyone at once), `select::reset()`.
  Actions without `<selector>` going to the selection in a no-target thread is verified (with one player);
  `value::x` there still does NOT read the selected player. The spectator spot is elsewhere.
- `player_death`: `line var who = "%player%"`, remove `who` from `alive`, announce `"$who is out"`.
- `player_respawn` while the round runs: not in `alive` (died in the round) → spectator. Still in `alive` → died
  BEFORE the round (lobby PvP, AFK on the death screen when `alive` was copied): put them INTO the fight (own
  spawn, gamemode, kit). Removing them would give a free win to whoever killed them in the lobby. Read `state`
  into a `line var` BEFORE `code::wait(1)`: if the round started during that tick, start_round already placed them.
- Wins: `struct Stats { wins = 0 }` + `save var %player%: Stats` + `%player% ??= Stats()` in player_join.
  When ≤ 1 left: `state = State.OVER`, winner `line var w = alive[0]`, `` save var `${w}`: Stats ``, `` `${w}`.wins += 1 ``
  (same storage as `%player%.wins`), titles, wait, everyone back to the lobby, break, `state = State.WAITING`.

## Boss fight (docs/recipes-boss.jc, compiles as is)
A summoned boss with a boss bar, capped minions, a damage table and a finale. Copy it for any "one special mob"
mechanic. Mostly verified facts; the inferred, NOT checked spots (all listed in the file's header, each behind a
uuid guard that just skips code if the guess is wrong):
`value::uuid<victim_entity>` (not used); `has_entity` for a mob in an unloaded chunk. The shape:
- Summon from a player event: `world::spawn_entity(item("vindicator_spawn_egg"), loc, 200, "&4&lThe King")` (health
  200 works without set_max_health), then `boss = value::uuid<last_entity>`. Summon only
  `if (!world::has_entity([boss]))`, with `game var boss = ""` in top-level code (`has_entity([""])` is false),
  plus a summon cooldown (`value::timestamp` vs `game var last_summon`): the star is not used up and every kill
  pays out. has_entity notices a boss killed or removed outside your events, but NOT one left from before `/play`
  (`boss` resets to `""`) — that one is removed by the world-start cleanup.
- Mobs SURVIVE `/play`, game vars do not. The recipe keeps the boss/minion uuids in a `save var` list (dead ones
  pruned with has_entity) and removes them on world start and when a fight ends (`select::entity_by_name([u])` +
  `entity::remove()` in a NO_TARGET process). The cleanup copies and clears the list first and puts back the live
  boss and its minions, so it is safe to start at any time. `select::all_mobs()` + `entity::remove()` also works
  but removes EVERY mob in the world; selecting by custom name or tag is not verified.
- ONE NO_TARGET loop per fight with a generation token: summon does `boss_gen += 1`, the loop starts with
  `line var my = boss_gen` and breaks when `boss_gen != my` or `!world::has_entity([boss])` — a quick re-summon
  cannot leave two loops running. Cleanup is started from the loop, never after a `code::wait` in `entity_death`.
- Read the boss's values in a NO_TARGET process `boss_tick` (own line, started every 5 s by the loop):
  `select::entity_by_name([boss])` → `value::health<current>` (verified: <current> reads the selection). Abilities and
  a leash (`variable::distance(value::location<current>, arena) > N` → `entity::teleport(arena)`) go there too.
- Bar: in `entity_take_damage` with `value::uuid == boss`: `boss_hp = max(0, value::health - value::event_final_damage)`
  (health is BEFORE the hit), then `player::set_boss_bar<all_players>(id, "&4&lThe King ...", boss_hp / MAX * 100)`.
- Damage table: `player_damage_entity` (`%player%` = attacker, `value::event_final_damage`) into a name → damage map.
  Which entity was hit (`value::uuid<victim_entity>`) is not verified, so during a fight a hit on ANY mob counts
  and can call a minion.
- Minions: uuid list pruned with `has_entity`, capped, spawned from a player event (where last_entity is verified).
- Finale in `entity_death` (`value::uuid == boss`): this thread survives `code::wait`; top damage via `sort_any_map`.
