# Earth Games API reference (version 1)

Generated from the platform's API table. A rules script calls these as `eg.<namespace>.<name>(…)`.

- A `player` argument takes a player object or its id. A `point` is `{ lat, lon }`.
- Calls marked *private games* work in private instances only.
- Calls that return a Promise answer a few milliseconds later; `await` them.

## Events

Export the ones you need: `export default { onStart() { … } }`.

### `onLoad(saved: { [key: string]: any }, info: { version: string | null, savedAt: number | null, fresh: boolean })`

Persistent games only, before onStart: everything this world saved with saves.set. "fresh" is true for a brand-new world. "version" is the version of your game that last saved it, so an update can convert old saves here.

**In game:** Runs before `onStart` in persistent worlds, restoring saved state across server restarts or new sessions.

```js
if (saved && saved.day) eg.state.day = saved.day;
if (info.fresh) eg.state.day = 1;
```

### `onStart()`

The game started (or restarted after the server did). Set things up here.

**In game:** Initializes teams, spawners, combat rules, and lobby phase once as soon as the instance boots.

```js
eg.teams.define([{ id: 'red', color: 'red' }, { id: 'blue', color: 'blue' }]);
eg.instance.setPhase('lobby');
```

### `onPlayerJoin(player, info: { rejoined: boolean })`

A player entered the game. `rejoined` is true when they came back after a dropped connection in time to keep their place.

**In game:** Fires each time a player enters (or reconnects inside the rejoin window) so you can orient them and send their initial HUD.

```js
eg.ui.toast(player, info.rejoined ? 'Welcome back!' : 'Welcome!', 'good');
eg.ui.hud(player, [{ type: 'title', text: 'Ready' }]);
```

### `onPlayerAway(player)`

A player's connection dropped and their place is being held for a while (manifest player.rejoinS). Pause what they were doing.

**In game:** Alerts your script when a player drops connection during a `rejoinS` grace window so you can pause timers until they return.

```js
eg.players.setData(player, 'pausedAt', eg.world.now());
eg.ui.toast(null, eg.t('{name} disconnected (seat held).', { name: player }), 'warn');
```

### `onPlayerLeave(player, reason: 'left' | 'disconnected' | 'timeout' | 'closed')`

A player is gone from the game for good.

**In game:** Notifies your script when a player exits for good so you can reassign roles, rebalance teams, or clean up entities.

```js
eg.ui.toast(null, eg.t('{name} left ({reason}).', { name: player, reason: 'left' }));
```

### `onPlayerArea(player, area: { id: string, center: point })`

A player came into a new area (about 1.5 km squares), including the one they start in. Use it to put things where players actually are.

**In game:** Fires whenever a player steps or drives into a new ~1.5 km map square, letting games populate real places endlessly anywhere on Earth.

```js
const shops = await eg.world.placesNear(area.center, { kinds: ['shop'], max: 2, seed: area.id });
for (const s of shops) eg.entities.add({ id: 's-' + s.id, kind: 'zone', at: s, label: s.name, trigger: {} });
```

### `onPlayerMode(player, change: { from: string, to: string })`

A player switched how they are getting around (for instance walk to drive, or drive to walk).

**In game:** Triggers instantly when a player switches travel mode (`walk`, `drive`, `fly`, etc.) so scripts can swap HUDs or enforce rules.

```js
if (change.to === 'fly') {
  eg.ui.toast(player, 'No helicopters allowed in ground zones!', 'warn');
}
```

### `onZone(player, entityId: string, what: 'enter' | 'leave' | 'dwell')`

A player entered or left a zone with a trigger, or stayed in it slowly enough for long enough (dwell).

**In game:** Fires when a player walks or drives into (`enter`), exits (`leave`), or holds inside (`dwell`) a trigger zone.

```js
if (what === 'dwell' && entityId === 'capture') {
  eg.ui.toast(player, 'Zone captured!', 'good');
  eg.fx.confetti(player);
}
```

### `onInteract(player, entityId: string)`

A player pressed F at an entity with `interact`.

**In game:** Fires when a player walks up to an entity with `interact` and presses `F` (or taps the interact prompt on touch).

```js
if (entityId === 'terminal') {
  const ok = await eg.ui.confirm(player, { title: 'Hack Terminal?', body: 'Alerts nearby guards.' });
  if (ok) eg.ui.toast(player, 'Hacking...', 'warn');
}
```

### `onUi(player, what: { from: 'menu' | 'card' | 'hud' | 'action' | 'window', id: string, item?: string, tab?: string, button?: string, closed?: boolean })`

A player chose something: a menu item or tab, a button on a card, HUD or window, closing a window, or one of the game's own actions (manifest `actions`, such as a key).

**In game:** Handles button clicks, tab switches, menu item choices, window closes, and custom manifest hotkeys (`KeyH`, `J`).

```js
if (what.from === 'window' && what.id === 'shop' && what.button === 'heal') {
  eg.combat.heal(player, 50);
  eg.ui.toast(player, 'Healed +50 HP!', 'good');
}
```

### `onPlayerDamaged(player, hit: { amount: number, hp: number, why: 'npc' | 'player' | 'blast' | string, by?: string, npc?: number, kind?: string, weapon?: string })`

A player lost health. `by` is the id of the player responsible, `npc` the character.

**In game:** Reports every point of damage taken (from NPCs, rival players, blasts, or script damage) along with remaining HP.

```js
if (hit.why === 'npc') {
  eg.ui.toast(player, eg.t('Hit for {n}!', { n: hit.amount }), 'warn');
}
```

### `onPlayerDied(player, hit: { why: string, by?: string, npc?: number, kind?: string, weapon?: string })`

A player reached 0 health and is down.

**In game:** Fires at 0 HP so you can award elimination points, drop loot zones, or announce knockouts.

```js
eg.ui.toast(null, eg.t('{name} is down!', { name: player }), 'warn');
if (hit.by) eg.scores.add(hit.by, 25);
```

### `onPlayerRespawn(player)`

A downed player is back on their feet.

**In game:** Fires when the downed timer expires or `combat.respawn` runs, letting you re-equip weapons or warp them to base.

```js
eg.inventory.setLoadout(player, { pistol: 36, bat: 1 });
eg.ui.toast(player, 'Back in the fight!', 'good');
```

### `onRace(player, race: { ev: 'start' | 'gate' | 'finish' | 'void', track: string, name?: string, cls?: string, car?: string, racers?: number, n?: number, of?: number, ms?: number, splits?: number[], par?: number, lengthM?: number, mode?: string, place?: number, featured?: boolean, user?: boolean, course?: boolean, reason?: string })`

A race you offered moved on. "start": the lights began (racers: how many on them). "gate": gate n of "of" crossed at ms. "finish": every gate crossed in ms milliseconds, with the splits, the par for their car's class (cls), and their place among "of" racers when it was a heat. "void": it ended without a time; reason is teleport, correct, fly, onfoot, swap, fast, expired or cancelled.

**In game:** Streams race lifecycle events (`start`, `gate`, `finish`, `void`) with exact server split times, car class par, and heat placement.

```js
if (race.ev === 'finish') {
  eg.fx.confetti(player);
  eg.ui.toast(null, eg.t('{name} finished in {s} s', { name: player, s: (race.ms / 1000).toFixed(2) }), 'good');
}
```

### `onNpc(event: { ev: 'spawned' | 'died' | 'saw' | 'lost' | 'reached' | 'attack' | 'gone', id: number, player?: Player, kind?: string, damage?: number, spawner?: string, tag?: string, lat?: number, lon?: number, why?: string })`

Something happened to one of the game's characters. `player` is who it saw, attacked or was killed by; `died` says where (lat, lon); `gone` says why it was removed.

**In game:** Reports character sightings, attacks, arrivals (`reached`), deaths (with attacker & coordinates), and despawns.

```js
if (event.ev === 'died' && event.player) {
  eg.scores.add(event.player, 10);
  eg.ui.toast(event.player, '+10 pts', 'good');
}
```

## eg.world

Time, distance, bearings, real places, and instance weather/solar-hour atmosphere. Everything works wherever on Earth the game is played.

### `eg.world.now(): number`

The time now, in milliseconds since 1970 (the server clock). (answers at once)

**In game:** Uses the server clock (matching the client countdown) so every player's HUD clock counts down in sync.

```js
const endAt = eg.world.now() + 90_000;
eg.ui.hud(player, [{ type: 'timer', until: endAt, text: 'left' }]);
```

### `eg.world.distance(a: point, b: point): number`

Metres between two points. (answers at once)

**In game:** Computes the exact straight-line distance in metres across the 1:1 Earth sphere between two points or players.

```js
const goal = eg.world.offset(player, 150, 0);
const d = Math.round(eg.world.distance(player, goal));
eg.ui.toast(player, eg.t('{d} m away', { d }));
```

### `eg.world.offset(from: point, eastM: number, southM: number): point`

The point that many metres east and south of another: place things relative to wherever the game is being played. (answers at once)

**In game:** Spawns a glowing green safehouse ring 40 m east and 25 m north of the player without hardcoding coordinates.

```js
const camp = eg.world.offset(player, 40, -25); // 40 m east, 25 m north
eg.entities.add({ id: 'camp', kind: 'zone', at: camp, radius: 8, style: 'safehouse', label: 'Camp' });
```

### `eg.world.hour(at: point): number`

Local solar hour (0 to 24) at a point, for "only at night" rules anywhere on Earth. (answers at once)

**In game:** Reads the real local sun hour (0–24) at that spot on Earth so night rules trigger only after dusk in the player's town.

```js
const hr = eg.world.hour(player);
if (hr >= 20 || hr < 6) eg.ui.toast(player, 'Night bonus active!', 'good');
```

### `eg.world.placesNear(at: point, opts?: { minM?: number, maxM?: number, kinds?: string[], max?: number, seed?: string }): Promise<Place[]>`

Real named places from the built map between minM and maxM metres of a point: [{ id, name, kind (depot | fuel | shop | office), lat, lon }], each on the road in front of it. The same seed gives the same sample. Three more kinds come only when you ask for them in `kinds`: "hospital", "police" (a police station) and "street" (a point on a named street). (returns a Promise)

**In game:** Queries real built-map businesses and streets around the player and turns them into named interactive rings on the road.

```js
const stops = await eg.world.placesNear(player, { minM: 150, maxM: 1200, kinds: ['shop', 'fuel'], max: 4 });
for (const s of stops) eg.entities.add({ id: 'p-' + s.id, kind: 'zone', at: s, label: s.name, style: 'pickup', trigger: {} });
```

### `eg.world.onRoad(at: point): Promise<boolean | null>`

Is this point on a road? null where the map is not built. (returns a Promise)

**In game:** Verifies a candidate coordinate actually lands on paved road surface before spawning a roadblock, flare, or vehicle event.

```js
const spot = eg.world.randomPoint(player, { minM: 40, maxM: 120 });
if (await eg.world.onRoad(spot)) {
  eg.entities.add({ id: 'flare', kind: 'marker', at: spot, style: 'hot', label: 'Road Flare' });
}
```

### `eg.world.bearing(from: point, to: point): number`

Compass bearing in degrees from one point toward another (0 north, 90 east, 180 south, 270 west). (answers at once)

**In game:** Returns the compass heading (0 north, 90 east) so scripts can give directional callouts or place objects ahead.

```js
const target = eg.world.offset(player, 120, -120);
const deg = Math.round(eg.world.bearing(player, target));
eg.ui.toast(player, eg.t('Head {deg} deg', { deg }));
```

### `eg.world.pointAlong(from: point, bearingDeg: number, meters: number): point`

The point `meters` away from `from` along a compass bearing in degrees. (answers at once)

**In game:** Places a point 200 m along a compass angle and directs the player's GPS navigation line straight to it.

```js
const ahead = eg.world.pointAlong(player, 90, 200); // 200 m due east
eg.ui.waypoint(player, ahead, { hint: 'Check the alley.' });
```

### `eg.world.midpoint(a: point, b: point): point`

The point halfway between two points. (answers at once)

**In game:** Places a red capture ring directly halfway between two players so both have an equal sprint to reach it.

```js
const [a, b] = eg.players.all();
if (a && b) eg.entities.add({ id: 'arena', kind: 'zone', at: eg.world.midpoint(a, b), radius: 25, style: 'hot', label: 'Meet' });
```

### `eg.world.inRadius(at: point, center: point, radiusM: number): boolean`

True when `at` is within `radiusM` metres of `center`. (answers at once)

**In game:** Checks quickly in memory whether a player or NPC stands inside a circular area before rewarding points or healing.

```js
const base = eg.state.base;
if (base && eg.world.inRadius(player, base, 30)) {
  eg.ui.toast(player, 'Safe inside base.', 'good');
}
```

### `eg.world.randomPoint(center: point, opts?: { minM?: number, maxM?: number }): point`

A random point evenly distributed inside a circle or ring (`minM` to `maxM` metres, default 0 to 100) around `center`. (answers at once)

**In game:** Drops a glowing amber supply beacon somewhere inside an 80–220 m ring around the player and marks it on the minimap.

```js
const drop = eg.world.randomPoint(player, { minM: 80, maxM: 220 });
eg.entities.add({ id: 'crate', kind: 'marker', at: drop, style: 'pickup', label: 'Supply Drop', radar: true });
```

### `eg.world.setWeather(weather: WeatherPreset | null)`

Override the weather ("clear", "cloudy", "overcast", "rain", "storm", "snow", "fog") for everyone in the instance (null restores live local weather). *Private games.* (returns nothing)

**In game:** Transitions the 3D sky, clouds, rain/snow particles, wind sway on trees, and wet road grip across the whole instance.

```js
eg.world.setWeather('storm');
eg.ui.toast(null, 'A storm is rolling in!', 'warn');
```

### `eg.world.setTime(hour: number | null)`

Pin the local solar hour (0 to 24, for instance 22 for night or 6.5 for sunrise) for everyone in the instance (null restores real local time). *Private games.* (returns nothing)

**In game:** Pins the sun below the horizon for everyone in the match, illuminating stars, streetlights, headlights, and marker beams.

```js
eg.world.setTime(22.5); // 10:30 PM night sky
eg.ui.toast(null, 'Lights out. Survive until dawn.');
```

### `eg.world.lightning(at?: point | null)`

Flash the sky and play thunder for players near a point, or everyone in the instance when omitted. *Private games.* (returns nothing)

**In game:** Sends a bright sky lightning flash and rolling thunder boom to players near the bolt, heightening storm tension.

```js
eg.world.setWeather('storm');
eg.world.lightning(player);
```

## eg.players

Who is in the game: queries, teams, ephemeral match data, movement freezes, and teleports. Player objects are snapshots; call players.get for a fresh one.

### `eg.players.all(): Player[]`

Everyone in the game now. (answers at once)

**In game:** Iterates every player currently in the match so you can greet, teleport, equip, or score all participants.

```js
for (const p of eg.players.all()) {
  eg.ui.toast(p, eg.t('Match starts! {n} players ready.', { n: eg.players.count() }), 'good');
}
```

### `eg.players.get(player): Player | null`

The latest snapshot of one player, or null when they are not in the game. (answers at once)

**In game:** Fetches the player's up-to-date snapshot (position, speed, health, team, vehicle) instead of holding onto an older event copy.

```js
const fresh = eg.players.get(player);
if (fresh && fresh.speed > 20) eg.ui.toast(fresh, 'Top speed bonus!');
```

### `eg.players.near(at: point, radiusM: number): Player[]`

Players within a radius of a point, nearest first. (answers at once)

**In game:** Lists everyone standing or driving within 25 m sorted closest-first—ideal for aura heals, blast checks, or proximity tag.

```js
const nearby = eg.players.near(player, 25);
eg.ui.toast(player, eg.t('{n} players within 25 m', { n: nearby.length }));
```

### `eg.players.nearest(at: point, opts?: { exclude?: player | player[], team?: string, alive?: boolean, maxM?: number }): Player | null`

The closest player to a point matching optional filters (`exclude`, `team`, `alive`, `maxM`), or null when none match. (answers at once)

**In game:** Finds the single closest living opponent (excluding the hunter) and locks the player's GPS arrow onto them.

```js
const prey = eg.players.nearest(player, { exclude: player, alive: true, maxM: 150 });
if (prey) eg.ui.waypoint(player, prey, { hint: 'Target spotted!' });
```

### `eg.players.inTeam(team: string): Player[]`

Everyone currently assigned to a team. (answers at once)

**In game:** Filters directly to members of one team so you can reward, heal, or teleport only that squad.

```js
const blues = eg.players.inTeam('blue');
for (const p of blues) eg.combat.heal(p, 25);
```

### `eg.players.random(opts?: { team?: string, alive?: boolean, exclude?: player | player[] }): Player | null`

One randomly chosen player matching optional filters, or null when none match. (answers at once)

**In game:** Picks a fair random living player at round start to become the tagger, VIP, or driver.

```js
const seeker = eg.players.random({ alive: true });
if (seeker) {
  eg.players.setData(seeker, 'it', true);
  eg.ui.banner(seeker, { title: 'YOU ARE IT!', tone: 'warn', seconds: 4 });
}
```

### `eg.players.count(): number`

How many players are in the game. (answers at once)

**In game:** Checks live headcount to gate round starts, scale wave counts, or show a waiting hint when solo.

```js
if (eg.players.count() < 2) {
  eg.ui.hint(null, 'Waiting for at least 2 players...');
}
```

### `eg.players.isBusy(player): boolean`

True when the player is marked busy with `players.setBusy` or in a race. (answers at once)

**In game:** Checks whether a player is mid-race or marked busy so menus and world prompts don't overlap an active run.

```js
if (!eg.players.isBusy(player)) {
  eg.ui.toast(player, 'Visit any beacon to start a run!');
}
```

### `eg.players.setData(player, key: string, value: any)`

Keep an ephemeral value on a player for this run (up to 50 keys per player; cleared when they leave). (answers at once)

**In game:** Tracks per-player counters or flags (coins, streaks, role) for this match without manual Map boilerplate.

```js
const pts = (eg.players.getData(player, 'coins') || 0) + 1;
eg.players.setData(player, 'coins', pts);
eg.ui.hud(player, [{ type: 'counter', text: 'Coins', value: pts }]);
```

### `eg.players.getData(player, key?: string): any`

Read one ephemeral value set with `players.setData` (or all keys as an object when `key` is left out). (answers at once)

**In game:** Reads back ephemeral match data stored on that player (automatically cleaned up when they leave).

```js
const role = eg.players.getData(player, 'role') || 'runner';
eg.ui.toast(player, eg.t('Your role: {role}', { role }));
```

### `eg.players.skipped(player, sinceMs: number): 'teleport' | 'correct' | 'fly' | null`

Did this player skip the trip since a moment (teleported, was snapped back by the server, or flew)? null when the trip was honest. For games that reward getting somewhere. (answers at once)

**In game:** Catches teleports or flight shortcuts since a timestamp so delivery and courier games only score honest trips.

```js
const startAt = eg.world.now();
eg.players.setData(player, 'startAt', startAt);
// Later on arrival:
if (eg.players.skipped(player, eg.players.getData(player, 'startAt'))) {
  eg.ui.toast(player, 'Trip voided: fast travel detected.', 'warn');
}
```

### `eg.players.setBusy(player, busy: boolean)`

Mark a player as in the middle of a run (a job, a round). The platform will not move a busy player to another game without telling you first. (returns nothing)

**In game:** Tells Earth Games the player is in an active job or round so they aren't silently switched into another game.

```js
eg.players.setBusy(player, true);
eg.ui.toast(player, 'Heist active!');
```

### `eg.players.startRun(player): Promise<boolean>`

Ask the platform whether this player may start a scored run now. False when a free player has used up their runs for the day; the platform has already told them. Call it before starting anything that ends with finishRun. (returns a Promise)

**In game:** Checks daily free-play quota before starting a scored run; automatically prompts free players when daily runs are used.

```js
if (await eg.players.startRun(player)) {
  eg.players.setBusy(player, true);
  eg.ui.toast(player, 'Scored run started!', 'good');
}
```

### `eg.players.finishRun(player)`

A run that began with startRun was completed. Counts as having played the game. (returns nothing)

**In game:** Records a completed scored run on the player's account and unlocks game rating after completion.

```js
eg.players.setBusy(player, false);
eg.players.finishRun(player);
```

### `eg.players.award(player, badge: { id: string, label: string }): Promise<boolean>`

Give a signed-in player a profile badge. Resolves true when it is new to them. *Earth Games team only.* (returns a Promise)

**In game:** Awards a permanent profile badge (official Earth Games team games only) and notifies the player when newly earned.

```js
const won = await eg.players.award(player, { id: 'deliveries:first', label: 'First Delivery' });
if (won) eg.ui.toast(player, 'Badge unlocked: First Delivery!', 'good');
```

### `eg.players.teleport(player, to: point)`

Move a player to a point at once: the start of a round, a respawn point. *Private games.* (returns nothing)

**In game:** Instantly relocates the player to a starting line, lobby, or checkpoint and snaps their camera smoothly.

```js
const spawn = eg.world.offset(player, 0, -80);
eg.players.teleport(player, spawn);
eg.fx.ring(spawn, { color: '#38bdf8', radius: 5 });
```

### `eg.players.teleportAll(to: point, opts?: { spreadM?: number })`

Move everyone in the instance to a point, optionally spaced evenly around a ring of `spreadM` metres (0 to 100). *Private games.* (returns nothing)

**In game:** Warps every player in the match into a neat circle around a hub point so nobody spawns stacked inside each other.

```js
const hub = eg.state.hub || player;
eg.players.teleportAll(hub, { spreadM: 12 });
eg.ui.toast(null, 'Everyone gathered at the start line!', 'good');
```

### `eg.players.setFrozen(player | null, frozen: boolean)`

Freeze or unfreeze a player (null: everyone). Frozen players cannot walk or drive, while still able to look around and answer prompts or windows. *Private games.* (returns nothing)

**In game:** Holds players in place (and locks car brakes) during a 3-second countdown while still letting them look around or click UI.

```js
eg.players.setFrozen(null, true);
eg.ui.countdown(null, { seconds: 3, goText: 'GO!' });
eg.timers.after(3, () => eg.players.setFrozen(null, false));
```

### `eg.players.eject(player)`

Put a player out of the vehicle they are driving onto foot beside it. *Private games.* (returns nothing)

**In game:** Dismounts a driving player safely onto the pavement beside their car when entering a foot-only arena.

```js
if (player.mode === 'drive') {
  eg.players.eject(player);
  eg.ui.toast(player, 'Vehicles disabled in this zone!', 'warn');
}
```

### `eg.players.kick(player, reason?: string)`

Send a player out of this private instance back to the shared world with an optional message. *Private games.* (returns nothing)

**In game:** Sends a player out of the private instance back to the shared world and displays your optional reason toast.

```js
const ok = await eg.ui.confirm(player, { title: 'Leave match?', body: 'Return to Free Roam?' });
if (ok) eg.players.kick(player, 'Returned to Free Roam.');
```

### `eg.players.pay(player, cash: number): Promise<number>`

Add to a player's cash in this game (a negative number takes some, down to nothing). Resolves to what they have now. *Earth Games team only.* (returns a Promise)

**In game:** Adds or subtracts game cash (official Earth Games team games only) and resolves to their updated wallet balance.

```js
const bal = await eg.players.pay(player, 250);
eg.ui.toast(player, eg.t('Paid! Balance: {bal}', { bal }), 'good');
```

### `eg.players.wanted(at: point, radiusM: number): Promise<{ id: string, name: string, level: number, lat: number, lon: number }[]>`

Players within a radius who are wanted by the police in another Earth Games game right now, nearest first, with where they are. An id lasts while that player stays online. *Earth Games team only.* (returns a Promise)

**In game:** Lists nearby suspects wanted in Lawless (official team games only) with live coordinates and heat level.

```js
const suspects = await eg.players.wanted(player, 2000);
for (const s of suspects) eg.ui.toast(player, eg.t('{name} wanted level {lv}', { name: s.name, lv: s.level }));
```

### `eg.players.grantCar(player, car: string): Promise<boolean>`

Put a car from the roster in a signed-in player's garage for good (a prize). Resolves true when it is new to them. *Earth Games team only.* (returns a Promise)

**In game:** Permanently adds a roster vehicle into the player's garage (official Earth Games team games only).

```js
const fresh = await eg.players.grantCar(player, 'rally');
if (fresh) eg.ui.toast(player, 'Unlocked a new garage car!', 'good');
```

## eg.teams

Sides in a game, with scores, shuffling, leader lookups, and team broadcasts.

### `eg.teams.define(teams: { id: string, name?: string, color?: 'red' | 'blue' | 'green' | 'yellow' | 'purple' | 'orange' }[])`

Say which teams the game has (up to 8). Scores of teams that stay are kept; a player on a team that is gone has none. (returns nothing)

**In game:** Registers up to 8 colored squads for the game so team score pills and friendly-fire protection work automatically.

```js
eg.teams.define([
  { id: 'red', name: 'Crimson', color: 'red' },
  { id: 'blue', name: 'Cobalt', color: 'blue' },
]);
```

### `eg.teams.assign(player, team: string | null)`

Put a player on a team (null: on none). Their snapshot has `team` from the next event on. Teammates cannot hurt each other unless combat is enabled with friendlyFire. (returns nothing)

**In game:** Moves a player onto a specific team; from the next event onward `player.team` reflects it and teammates are protected.

```js
eg.teams.assign(player, 'red');
eg.ui.toast(player, 'Joined Crimson team.', 'info');
```

### `eg.teams.auto()`

Put every player who has no team on the team with the fewest players. (returns nothing)

**In game:** Automatically balances every unassigned player onto whichever team currently has the fewest players.

```js
eg.teams.auto();
eg.ui.hud(null, [{ type: 'teams' }]);
```

### `eg.teams.addScore(team: string, points: number)`

Add to a team's score (a negative number takes away). (returns nothing)

**In game:** Increments (or deducts) points on a team's scoreboard and updates everyone's HUD team strip when resent.

```js
if (player.team) {
  eg.teams.addScore(player.team, 10);
  eg.ui.hud(null, [{ type: 'teams' }]);
}
```

### `eg.teams.setScore(team: string, points: number)`

Set a team's score. (returns nothing)

**In game:** Directly overwrites a team's score, useful for setting starting lives or resetting points between stages.

```js
eg.teams.setScore('red', 0);
eg.teams.setScore('blue', 0);
```

### `eg.teams.all(): Promise<Team[]>`

The teams now, with their scores and the ids of the players on each. (returns a Promise)

**In game:** Reads all teams, their colors, live scores, and member lists to render end-of-round summaries or tiebreakers.

```js
const teams = await eg.teams.all();
const lines = teams.map(t => t.name + ': ' + t.score);
eg.ui.card(null, { title: 'Scoreboard', lines });
```

### `eg.teams.get(team: string): Promise<Team | null>`

One team by id, with its color, score and player ids, or null. (returns a Promise)

**In game:** Fetches one team's score and player list without needing to filter the full team list manually.

```js
const red = await eg.teams.get('red');
if (red) eg.ui.toast(player, eg.t('Red has {n} pts', { n: red.score }));
```

### `eg.teams.leader(): Promise<(Team & { tied: boolean }) | null>`

The highest-scoring team right now (`tied` is true when two or more teams share the lead), or null when no teams are defined. (returns a Promise)

**In game:** Identifies the leading team right now and flags `tied: true` when two squads share top score so you can trigger overtime.

```js
const top = await eg.teams.leader();
if (top && !top.tied) {
  eg.ui.banner(null, { title: eg.t('{name} wins!', { name: top.name }), tone: 'good' });
}
```

### `eg.teams.resetScores()`

Set every defined team's score back to 0. (returns nothing)

**In game:** Zeroes every team's score at once while preserving team rosters and colors for the next round.

```js
eg.teams.resetScores();
eg.ui.hud(null, [{ type: 'teams' }]);
```

### `eg.teams.shuffle()`

Randomly rebalance every player currently in the game evenly across the defined teams. (returns nothing)

**In game:** Randomly redistributes all players evenly across your defined teams between rounds so matches stay fair.

```js
eg.teams.shuffle();
eg.chat.announce('Teams have been shuffled for a fresh round!');
```

### `eg.teams.broadcast(team: string, text: string, tone?: 'info' | 'good' | 'warn')`

Show a toast message only to players on one team. (returns nothing)

**In game:** Sends a private toast banner exclusively to teammates on one squad without tipping off opposing teams.

```js
eg.teams.broadcast('red', 'Regroup at the northern bridge!', 'warn');
```

## eg.vehicles

What players drive: emergency sirens, handling profiles, tire compounds, speed caps, and nitro boosts.

### `eg.vehicles.siren(player, on: boolean)`

Switch the emergency siren of the vehicle a player is driving on or off: traffic makes way for them, and players near them hear it. (returns nothing)

**In game:** Flashes emergency lights and plays a two-tone yelp audible within 300 m while ambient traffic pulls aside.

```js
if (player.mode === 'drive') {
  eg.vehicles.siren(player, true);
}
```

### `eg.vehicles.setHandling(profile: HandlingProfile)`

Set ground-vehicle handling for everyone in the instance: "arcade" (forgiving grip), "sport" (eager and lively), or "real" (factory road specs). *Private games.* (returns nothing)

**In game:** Switches every ground vehicle in the instance between forgiving "arcade", lively "sport", or realistic factory physics.

```js
eg.vehicles.setHandling('sport');
eg.ui.toast(null, 'Sport handling enabled!', 'info');
```

### `eg.vehicles.setTire(player | null, tire: TireCompound | null)`

Fit a tire compound ("slick", "allweather", "gravel", or null for default) on a player's vehicle or everyone's. *Private games.* (returns nothing)

**In game:** Swaps tire grip profile ("slick", "allweather", "gravel") so cars bite harder on dirt, rain, or dry tarmac.

```js
eg.vehicles.setTire(player, 'gravel');
eg.ui.toast(player, 'Rally gravel tires fitted!', 'good');
```

### `eg.vehicles.setSpeedLimit(player | null, maxMps: number | null)`

Cap ground-vehicle speed in metres per second (for pit lanes or speed traps); null removes the cap. *Private games.* (returns nothing)

**In game:** Gently enforces a maximum ground speed for pit lanes, school zones, or handicap rules; pass null to uncap.

```js
eg.vehicles.setSpeedLimit(player, 15); // 15 m/s (~33 mph) pit lane cap
```

### `eg.vehicles.boost(player, opts?: { strength?: number, seconds?: number })`

Give a player's ground vehicle a temporary speed and acceleration surge (`strength` 0.2 to 2, `seconds` 0.3 to 8). *Private games.* (returns nothing)

**In game:** Surges the player's vehicle forward with extra acceleration and speed-widened FOV for a nitro pad or pickup effect.

```js
eg.vehicles.boost(player, { strength: 1.4, seconds: 2.5 });
eg.audio.cue(player, 'ui.race_go');
```

## eg.camera

What a player's camera and viewport do: shakes, field-of-view kicks, and smooth screen fades.

### `eg.camera.shake(player | null, opts?: { strength?: number, seconds?: number })`

Shake a player's camera for a moment (null: everyone): a blast, a landing, something heavy going past. Not shown to players who asked their device for less motion. (returns nothing)

**In game:** Rattles the player's camera for impacts or explosions (automatically skipped for reduced-motion preferences).

```js
eg.camera.shake(player, { strength: 1.8, seconds: 0.6 });
```

### `eg.camera.fov(player | null, opts: { kick?: number, seconds?: number } | null)`

Widen or narrow a player's field of view by `kick` degrees (-15 to 15) for `seconds` (0.1 to 30); null resets to normal. (returns nothing)

**In game:** Smoothly widens (positive kick) or narrows (negative zoom) the 3D camera field of view for adrenaline or focus.

```js
eg.camera.fov(player, { kick: 10, seconds: 3 });
```

### `eg.camera.fade(player | null, opts: { color?: "black" | "white", opacity?: number, seconds?: number } | null)`

Fade a player's screen smoothly toward black or white (`opacity` 0 to 1, `seconds` 0.1 to 5); pass opacity 0 or null to fade back in. (returns nothing)

**In game:** Fades the viewport smoothly to black or white and back for clean round transitions, round wins, or teleports.

```js
eg.camera.fade(player, { color: 'black', opacity: 1, seconds: 0.6 });
eg.timers.after(0.7, () => {
  eg.players.teleport(player, eg.world.offset(player, 200, 0));
  eg.camera.fade(player, null);
});
```

## eg.race

Timed races through gates, on the tracks the platform makes from real streets or on a course of your own. The platform draws the gates and lights and keeps the time.

### `eg.race.tracksNear(at: point, opts?: { maxM?: number, max?: number }): Promise<Track[]>`

Race tracks on real streets near a point, nearest first: [{ id, name, kind ("sprint" | "circuit"), laps, lengthM, start, par: { D, C, B, A, S, M } (a good time in ms for each class of car), featured?, user? }]. The platform makes them from the map, and players record their own. (returns a Promise)

**In game:** Finds real street circuits and point-to-point sprints near the player with par times tuned for each vehicle class.

```js
const tracks = await eg.race.tracksNear(player, { maxM: 2500, max: 3 });
if (tracks[0]) await eg.race.offer(player, tracks[0].id);
```

### `eg.race.course(points: point[], opts?: { name?: string, laps?: number }): Promise<Track | null>`

A course of your own through the points you give, in order (100 m to 20 km): the platform puts the gates on it. End within 30 m of the start for a circuit. It lasts as long as the game runs (up to 20 at a time). null when it cannot be made; your log says why. (returns a Promise)

**In game:** Generates timed holographic 3D gates and a glowing racing line along custom checkpoints you supply.

```js
const p1 = eg.world.offset(player, 150, 0);
const p2 = eg.world.offset(player, 250, -150);
const course = await eg.race.course([player, p1, p2], { name: 'Dock Sprint' });
```

### `eg.race.offer(player, track: string, opts?: { mode?: string }): Promise<{ ok: boolean, why?: 'racing' | 'unknown' | 'far' }>`

Put a player on a track (by its id): a ring appears on its start line. When they stop in it in a car or on a bike, the start lights count down and the platform times them through every gate; players of your game who line up together start together. You hear the rest in onRace. The player counts as busy until the race ends. (returns a Promise)

**In game:** Places a golden start-grid ring on the road; stopping inside triggers 5 red start lights, multiplayer heats, and split timing.

```js
const tracks = await eg.race.tracksNear(player);
if (tracks[0]) await eg.race.offer(player, tracks[0].id, { mode: 'heat' });
```

### `eg.race.cancel(player)`

Take a player out of the race they are lining up for or driving. You hear onRace with ev "void", reason "cancelled". (returns nothing)

**In game:** Removes a player from their active race or start grid, clears the gates, and fires `onRace` with reason "cancelled".

```js
eg.race.cancel(player);
eg.ui.toast(player, 'Left the race grid.', 'info');
```

### `eg.race.status(player): Promise<{ track: string, stage: 'grid' | 'count' | 'race', next: number, total: number } | null>`

The race a player is currently in (`stage`, `next` gate and `total` gates), or null when they are not racing. (returns a Promise)

**In game:** Checks what stage of a race a player is in ("grid", "count", or "race") and how many gates remain.

```js
const st = await eg.race.status(player);
if (st) eg.ui.toast(player, eg.t('Gate {n} of {of}', { n: st.next + 1, of: st.total }));
```

## eg.entities

Zones and markers on the map: places players go to, stand in, inspect, or press F at.

### `eg.entities.add(def: { id?: string, kind: 'zone' | 'marker', at: point, radius?: number, style?: string, label?: string, radar?: boolean, visibleTo?: player, trigger?: { dwellS?: number, maxSpeed?: number, modes?: string[] }, interact?: { verb: string, reach?: number, modes?: string[] } }): string`

Put a zone (a ring players enter) or a marker (a beacon) on the map and return its id. `visibleTo` makes it one player's own. A `trigger` makes it fire onZone; `interact` gives it an F prompt that fires onInteract. (answers at once)

**In game:** Renders a 3D glowing ring or beacon pillar in the world (plus optional minimap dot and "F: Open Vault" prompt).

```js
eg.entities.add({
  id: 'vault', kind: 'zone', at: eg.world.offset(player, 35, 0),
  radius: 6, style: 'pickup', label: 'Vault', radar: true,
  interact: { verb: 'Open Vault', reach: 6 }
});
```

### `eg.entities.update(id: string, patch: object)`

Change an entity (same fields as add). (returns nothing)

**In game:** Updates an entity's position, radius, label, color style, or minimap flag live without recreating it.

```js
eg.entities.update('vault', { style: 'dropoff', label: 'Vault Open!' });
```

### `eg.entities.remove(id: string)`

Take an entity off the map. (returns nothing)

**In game:** Immediately removes the ring or beacon from the 3D world, minimap, and player proximity triggers.

```js
eg.entities.remove('vault');
```

### `eg.entities.get(id: string): Promise<Entity | null>`

Read one entity your script placed by id, or null when it is not on the map. (returns a Promise)

**In game:** Reads back the live coordinates, radius, style, and label of any script entity so you can point GPS or distance HUDs at it.

```js
const flag = await eg.entities.get('flag-1');
if (flag) eg.ui.waypoint(player, flag.at, { hint: flag.label });
```

### `eg.entities.list(opts?: { kind?: 'zone' | 'marker', prefix?: string, visibleTo?: player }): Promise<Entity[]>`

List the entities your script currently has on the map, optionally filtered by `kind`, id `prefix` or `visibleTo`. (returns a Promise)

**In game:** Lists active entities filtered by kind, id prefix, or owner—handy for counting remaining collectibles or displaying a map directory.

```js
const drops = await eg.entities.list({ kind: 'zone', prefix: 'coin-' });
eg.ui.toast(player, eg.t('{n} coins left on map', { n: drops.length }));
```

### `eg.entities.near(at: point, radiusM: number, opts?: { kind?: 'zone' | 'marker', prefix?: string }): Promise<Entity[]>`

Your script's entities within `radiusM` metres of a point, nearest first. (returns a Promise)

**In game:** Finds your nearest placed zones or markers around a player sorted closest-first for radar sweeps or local alerts.

```js
const close = await eg.entities.near(player, 100, { prefix: 'loot-' });
eg.ui.toast(player, eg.t('{n} loot stashes within 100 m', { n: close.length }));
```

### `eg.entities.count(opts?: { kind?: 'zone' | 'marker', prefix?: string }): Promise<number>`

How many entities your script currently has on the map. (returns a Promise)

**In game:** Counts matching active entities quickly so you can detect when the final objective or collectible is cleared.

```js
if (await eg.entities.count({ prefix: 'gem-' }) === 0) {
  eg.ui.banner(null, { title: 'All gems found!', tone: 'good' });
}
```

### `eg.entities.clear(opts?: { prefix?: string, visibleTo?: player })`

Remove every entity your script placed, or only those matching an id `prefix` or `visibleTo`. (returns nothing)

**In game:** Wipes all entities (or a matching prefix/player's private markers) cleanly between rounds without touching active race start grids.

```js
eg.entities.clear({ prefix: 'temp-' });
```

## eg.npcs

Characters the game puts in the world. The platform moves them; you choose their kind, batch spawns, and what they are doing.

### `eg.npcs.kinds(kinds: Kind[])`

Define the kinds of characters this game uses: [{ id, name?, model?, scale?, speed?, runSpeed?, health?, sight?, leash?, brain?, aggro?, attack?: { range, damage, cooldownS, windupS, ranged? } }]. *Private games.* (returns nothing)

**In game:** Registers custom AI character archetypes (speed, model, health, vision radius, melee/ranged attack) used by spawn and spawners.

```js
eg.npcs.kinds([
  { id: 'guard', name: 'Guard', brain: 'guard', health: 120, sight: 35, attack: { range: 1.6, damage: 12 } }
]);
```

### `eg.npcs.spawn(kind: string, opts: SpawnOpts): Promise<number | null>`

Spawn one character. Resolves to its id, or null when the kind is unknown or the world is full. *Private games.* (returns a Promise)

**In game:** Drops a live 3D AI character into the street that steers around buildings and reacts to nearby players.

```js
const spot = eg.world.offset(player, 18, 0);
const id = await eg.npcs.spawn('guard', { lat: spot.lat, lon: spot.lon, tag: 'boss' });
```

### `eg.npcs.spawnMany(kind: string, list: SpawnOpts[]): Promise<(number | null)[]>`

Spawn up to 50 characters of one kind in a single call, returning their ids (or null for any that did not fit). *Private games.* (returns a Promise)

**In game:** Spawns an entire ambush squad or horde pack in a single call instead of awaiting dozens of separate spawns.

```js
const spots = [1, 2, 3, 4].map(i => ({
  ...eg.world.randomPoint(player, { minM: 25, maxM: 50 }),
  tag: 'squad'
}));
const ids = await eg.npcs.spawnMany('guard', spots);
```

### `eg.npcs.despawn(id: number)`

Take a character out of the world at once. *Private games.* (returns nothing)

**In game:** Removes one specific character from the world right away without leaving a body or death event.

```js
const near = await eg.npcs.near(player, 15, { max: 1 });
if (near[0]) eg.npcs.despawn(near[0]);
```

### `eg.npcs.despawnTag(tag: string): Promise<number>`

Take every character with a matching `tag` out of the world at once. Resolves to how many were removed. *Private games.* (returns a Promise)

**In game:** Despawns every character sharing a tag (like "wave-1" or "escort") in one shot and reports how many left.

```js
const removed = await eg.npcs.despawnTag('boss');
eg.ui.toast(null, eg.t('Cleared {n} guards.', { n: removed }));
```

### `eg.npcs.clear()`

Remove every character. *Private games.* (returns nothing)

**In game:** Removes every active NPC in the match at once—helpful when resetting an arena or ending a horde phase.

```js
eg.npcs.clear();
```

### `eg.npcs.setBrain(id: number, brain: 'idle' | 'wander' | 'chase' | 'flee' | 'guard' | 'patrol' | 'goto', opts?: { target?: player | point, route?: point[], home?: point, run?: boolean })`

Change what a character is doing. *Private games.* (returns nothing)

**In game:** Switches an NPC's live AI behavior (idle, wander, chase, flee, guard, patrol, goto), immediately changing where it runs.

```js
const [id] = await eg.npcs.near(player, 40, { max: 1 });
if (id) eg.npcs.setBrain(id, 'chase', { target: player, run: true });
```

### `eg.npcs.setBrainAll(filter: { kind?: string, tag?: string, spawner?: string }, brain: Brain, opts?: { target?: player | point, route?: point[], home?: point, run?: boolean }): Promise<number>`

Change what every living character matching `kind`, `tag` or `spawner` is doing. Resolves to how many were updated. *Private games.* (returns a Promise)

**In game:** Orders an entire tag, kind, or spawner group to flee, charge, or patrol together when a boss falls or an alarm sounds.

```js
await eg.npcs.setBrainAll({ tag: 'squad' }, 'flee', { target: player, run: true });
eg.ui.toast(null, 'The squad is retreating!', 'good');
```

### `eg.npcs.damage(id: number, amount: number, by?: player): Promise<{ hp: number, died: boolean } | null>`

Hurt a character. *Private games.* (returns a Promise)

**In game:** Applies direct script damage to an NPC (credited to `by`)—killing it triggers `onNpc` "died" and leaves a body briefly.

```js
for (const id of await eg.npcs.near(player, 8)) {
  await eg.npcs.damage(id, 50, player);
}
```

### `eg.npcs.heal(id: number, amount: number)`

Heal a character. *Private games.* (returns nothing)

**In game:** Restores health to a living NPC up to its kind's max HP—great for boss phases or healer enemies.

```js
for (const id of await eg.npcs.near(player, 20)) {
  eg.npcs.heal(id, 30);
}
```

### `eg.npcs.info(id: number): Promise<Npc | null>`

One character: { id, kind, lat, lon, heading, hp, alive, brain, target, spawner, tag }. *Private games.* (returns a Promise)

**In game:** Inspects a character's live coordinates, HP, brain, tag, and current target player.

```js
const [id] = await eg.npcs.near(player, 50, { max: 1 });
const npc = id && await eg.npcs.info(id);
if (npc) eg.ui.waypoint(player, npc);
```

### `eg.npcs.near(at: point, radiusM: number, opts?: { kind?: string, tag?: string, max?: number }): Promise<number[]>`

Ids of living characters within a radius, nearest first. *Private games.* (returns a Promise)

**In game:** Finds living NPC ids inside a radius sorted nearest-first for proximity radars, traps, or shockwaves.

```js
const threats = await eg.npcs.near(player, 25, { kind: 'guard' });
eg.ui.hud(player, [{ type: 'counter', text: 'Nearby guards', value: threats.length }]);
```

### `eg.npcs.count(opts?: { kind?: string, spawner?: string }): Promise<number>`

How many characters are alive. *Private games.* (returns a Promise)

**In game:** Counts living characters (total, by kind, or by spawner) to drive wave progress bars and round-clear checks.

```js
const alive = await eg.npcs.count({ spawner: 'horde' });
eg.ui.hud(null, [{ type: 'counter', text: 'Enemies left', value: alive }]);
```

## eg.spawners

Rules that keep characters around the players, or around a spot, without you placing each one.

### `eg.spawners.add(def: { id: string, kind: string, at?: point, radius?: number, count?: number, capNear?: number, capTotal?: number, perSecond?: number, respawnS?: number, hours?: [number, number], brain?: string, tag?: string, where?: { roadClass?: string[], minFromPlayersM?: number, maxFromPlayersM?: number } })`

Add or replace a spawner. With `at` it keeps `count` characters alive around that spot. Without, it keeps characters around the players wherever they go, appearing on ground that matches `where`, never closer than minFromPlayersM. *Private games.* (returns nothing)

**In game:** Continuously maintains NPCs around moving players (or around a fixed spot) just out of sight on valid ground.

```js
eg.spawners.add({
  id: 'pack', kind: 'guard', capNear: 6, capTotal: 30, perSecond: 1,
  where: { minFromPlayersM: 45, maxFromPlayersM: 100 }
});
```

### `eg.spawners.remove(id: string, opts?: { clear?: boolean })`

Remove a spawner; `clear` also removes the characters it made. *Private games.* (returns nothing)

**In game:** Deletes a spawner rule and optionally despawns all characters it produced.

```js
eg.spawners.remove('pack', { clear: true });
```

### `eg.spawners.enable(id: string, on: boolean)`

Switch a spawner on or off. *Private games.* (returns nothing)

**In game:** Pauses or resumes spawning without deleting the rule—ideal for wave breaks or day/night cycles.

```js
eg.spawners.enable('pack', false);
eg.ui.toast(null, 'Intermission: catch your breath!', 'good');
```

### `eg.spawners.setDensity(id: string, k: number)`

Scale a spawner (0 none, 1 as written, up to 4). *Private games.* (returns nothing)

**In game:** Scales a spawner's active population up (up to 4x) or down as difficulty escalates across waves.

```js
eg.spawners.setDensity('pack', 2.5); // 250% cap density
```

### `eg.spawners.burst(id: string, n: number)`

Spawn up to n right now, ignoring the rate. *Private games.* (returns nothing)

**In game:** Instantly releases a burst of up to N characters around players, ignoring normal per-second trickle rate.

```js
eg.spawners.burst('pack', 10);
eg.ui.banner(null, { title: 'AMBUSH!', tone: 'bad', seconds: 3 });
```

### `eg.spawners.clear(id: string)`

Remove the characters a spawner made. *Private games.* (returns nothing)

**In game:** Removes every active character created by one spawner while keeping the spawner itself ready for the next wave.

```js
eg.spawners.clear('pack');
```

### `eg.spawners.list(): Promise<{ id: string, kind: string, enabled: boolean, alive: number }[]>`

All active spawners with whether each is enabled and how many characters from it are alive. *Private games.* (returns a Promise)

**In game:** Returns each spawner's id, character kind, enabled state, and live headcount for admin/debug panels or wave monitors.

```js
const list = await eg.spawners.list();
const rows = list.map(s => s.id + ': ' + s.alive + ' alive');
eg.ui.card(player, { title: 'Spawners', lines: rows });
```

## eg.combat

Health, armor, shields, damage, death and respawning. Switch it on and players can fight your characters (and each other, if you allow it).

### `eg.combat.enable(opts?: { health?: number, respawnS?: number, pvp?: boolean, npcDamage?: boolean, safeS?: number, friendlyFire?: boolean, loadout?: Loadout })`

Switch combat on. Every player gets health (100 unless you say), a health and weapon bar, and the starting loadout; their shots and swings hurt your characters; your characters' attacks hurt them (npcDamage: false to decide that yourself in onNpc). A player at 0 health is down for respawnS seconds (5; 0 means until you call combat.respawn), then back with full health and safeS seconds (3) of protection. Players only hurt each other with pvp: true. *Private games.* (returns nothing)

**In game:** Activates server-validated weapons, health/armor bars, crosshair aiming, hit feedback, and automatic respawning.

```js
eg.combat.enable({ health: 100, respawnS: 6, pvp: true, loadout: { pistol: 36, bat: 1 } });
```

### `eg.combat.disable()`

Switch combat off: weapons are put away and nobody can be hurt by shots. Health and inventories are kept. *Private games.* (returns nothing)

**In game:** Holsters everyone's weapons and disables gunfire damage while preserving current health and inventory items.

```js
eg.combat.disable();
eg.ui.toast(null, 'Ceasefire! Weapons holstered.');
```

### `eg.combat.setPvp(on: boolean)`

Let players hurt each other, or stop them. *Private games.* (returns nothing)

**In game:** Toggles friendly/rival player-vs-player damage live mid-match (safe lobby -> PvP arena).

```js
eg.combat.setPvp(true);
eg.ui.banner(null, { title: 'PvP Enabled', tone: 'warn', seconds: 3 });
```

### `eg.combat.setHealth(player, hp: number, max?: number)`

Set a player's health (and, optionally, their maximum). 0 kills them. *Private games.* (returns nothing)

**In game:** Sets exact current and maximum HP on the player's health bar—great for juggernaut bosses or sudden-death 1 HP modes.

```js
eg.combat.setHealth(player, 200, 200); // juggernaut boss HP
```

### `eg.combat.setArmor(player, armor: number)`

Set a player's armor, 0 to 100. Armor soaks 60 % of each hit until it is used up. *Private games.* (returns nothing)

**In game:** Fills the player's armor meter (0–100); each incoming hit has 60% soaked by armor until depleted.

```js
eg.combat.setArmor(player, 100);
eg.ui.toast(player, 'Heavy armor equipped!', 'good');
```

### `eg.combat.setSafe(player, seconds: number)`

Give a player `seconds` (0 to 60) of spawn protection during which attacks do not hurt them. *Private games.* (returns nothing)

**In game:** Grants temporary spawn-protection invulnerability so players cannot be spawn-camped right after teleporting.

```js
eg.combat.setSafe(player, 8);
eg.ui.toast(player, '8 seconds of spawn shield!', 'good');
```

### `eg.combat.damage(player, amount: number, opts?: { by?: player, why?: string }): Promise<{ hp: number, died: boolean } | null>`

Hurt a player (a trap, a fall, a rule of your own). null when it did nothing: they are down already, or just respawned. *Private games.* (returns a Promise)

**In game:** Applies environmental or script damage (respecting armor and safe shields), flashes red, and triggers death at 0 HP.

```js
const res = await eg.combat.damage(player, 25, { why: 'lava' });
if (res && res.died) eg.ui.toast(player, 'Burned by hazard!', 'warn');
```

### `eg.combat.heal(player, amount: number)`

Give health back, up to their maximum. Call it from a timer for health that comes back by itself. *Private games.* (returns nothing)

**In game:** Restores health up to the player's maximum and updates their combat bar immediately.

```js
eg.combat.heal(player, 40);
eg.fx.flash(player, { color: 'green', seconds: 0.3 });
```

### `eg.combat.healAll(amount?: number)`

Heal every living player in the game (by `amount`, or back to full health when left out). *Private games.* (returns nothing)

**In game:** Tops up every living player's health (by an amount or to full max HP) at once between waves.

```js
eg.combat.healAll();
eg.ui.toast(null, 'Wave cleared — full heal!', 'good');
```

### `eg.combat.kill(player, why?: string)`

Put a player down at once. *Private games.* (returns nothing)

**In game:** Immediately knocks a player down (bypassing armor/shields) and fires `onPlayerDied` with your reason.

```js
eg.combat.kill(player, 'out_of_bounds');
```

### `eg.combat.respawn(player)`

Put a downed player back on their feet now, with full health. *Private games.* (returns nothing)

**In game:** Revives a downed player on their feet right away with full health and brief spawn protection.

```js
eg.combat.respawn(player);
eg.players.teleport(player, eg.world.offset(player, 20, 0));
```

### `eg.combat.reviveAll()`

Put every downed player in the game back on their feet now with full health. *Private games.* (returns nothing)

**In game:** Revives every downed teammate across the match at once when a team captures a checkpoint or clears a wave.

```js
eg.combat.reviveAll();
eg.ui.banner(null, { title: 'Squad Revived!', tone: 'good', seconds: 3 });
```

## eg.inventory

What each player carries: weapons, rounds, and any items of your own.

### `eg.inventory.give(player, item: string, count?: number)`

Give a player a weapon ("bat", "pistol", "smg", "shotgun"; a gun's count is its rounds) or any item of your own ("key", "medkit": lowercase ids the platform just counts for you). *Private games.* (returns nothing)

**In game:** Adds weapons and ammo onto the player's weapon wheel/bar or increments custom items tracked in their inventory.

```js
eg.inventory.give(player, 'smg', 90);
eg.inventory.give(player, 'medkit', 2);
```

### `eg.inventory.take(player, item: string, count?: number)`

Take some of an item away, or all of it when count is left out. *Private games.* (returns nothing)

**In game:** Consumes an item or weapon rounds when used in a shop, craft recipe, or medkit action.

```js
eg.inventory.take(player, 'medkit', 1);
eg.combat.heal(player, 50);
```

### `eg.inventory.setLoadout(player, loadout: Loadout)`

Replace everything a player carries: { pistol: 48, bat: 1, medkit: 2 }. Everyone always has fists. *Private games.* (returns nothing)

**In game:** Replaces everything the player carries with a clean class kit; fists remain available at all times.

```js
eg.inventory.setLoadout(player, { shotgun: 24, pistol: 36, bat: 1, key: 1 });
```

### `eg.inventory.equip(player, weapon: string)`

Put a weapon they carry in their hands. *Private games.* (returns nothing)

**In game:** Puts the chosen weapon directly into the player's hands so they don't have to cycle the weapon wheel.

```js
eg.inventory.give(player, 'shotgun', 16);
eg.inventory.equip(player, 'shotgun');
```

### `eg.inventory.get(player): Promise<{ [item: string]: number }>`

What a player carries now. *Private games.* (returns a Promise)

**In game:** Reads the full dictionary of weapons and custom items currently carried by a player.

```js
const bag = await eg.inventory.get(player);
eg.ui.toast(player, eg.t('Medkits: {n}', { n: bag.medkit || 0 }));
```

### `eg.inventory.has(player, item: string, count?: number): Promise<boolean>`

True when the player carries at least `count` (1 by default) of an item or weapon. *Private games.* (returns a Promise)

**In game:** Checks in one call whether a player holds enough of an item to open a door, buy an upgrade, or extract.

```js
if (await eg.inventory.has(player, 'key', 1)) {
  eg.inventory.take(player, 'key', 1);
  eg.ui.toast(player, 'Unlocked!', 'good');
} else {
  eg.ui.toast(player, 'Need a key first.', 'warn');
}
```

### `eg.inventory.clear(player)`

Remove everything from a player's inventory, leaving only fists. *Private games.* (returns nothing)

**In game:** Strips every weapon and custom item from the player, returning them to bare fists.

```js
eg.inventory.clear(player);
eg.ui.toast(player, 'Disarmed! Fists only.', 'warn');
```

## eg.fx

Effects in the world (sparks, smoke, fire, confetti, rings, explosions, screen flashes), seen by everyone near.

### `eg.fx.blood(at: point | player, opts?: { size?: number })`

A splash of blood. Shown only when your manifest says the game has blood ("content": { "blood": true }), and only to signed-in players who turned blood on in their settings. Hits in combat do this for you. *Private games.* (returns nothing)

**In game:** Draws a blood splash in 3D only when manifest `content.blood` is true AND the viewer opted into blood in Settings.

```js
eg.fx.blood(player, { size: 1.3 });
```

### `eg.fx.impact(at: point | player, opts?: { size?: number })`

A puff of dust, as when something hits the ground or a wall. *Private games.* (returns nothing)

**In game:** Kicks up a quick puff of 3D dust where something lands or strikes a wall.

```js
eg.fx.impact(eg.world.offset(player, 4, 0), { size: 1.5 });
```

### `eg.fx.sparks(at: point | player, opts?: { size?: number })`

A burst of sparks. *Private games.* (returns nothing)

**In game:** Bursts bright golden additive sparks at a vehicle collision, lockpick, or trap.

```js
eg.fx.sparks(player, { size: 1.4 });
```

### `eg.fx.smoke(at: point | player, opts?: { size?: number, seconds?: number })`

Smoke rising from a point for a few seconds. *Private games.* (returns nothing)

**In game:** Sends billowing gray smoke plumes rising into the air for several seconds to mark flares or wrecks.

```js
eg.fx.smoke(eg.world.offset(player, 10, 0), { size: 1.8, seconds: 5 });
```

### `eg.fx.fire(at: point | player, opts?: { size?: number, seconds?: number })`

Flickering flames rising at a point for `seconds` (2 by default, up to 12). *Private games.* (returns nothing)

**In game:** Spawns flickering additive flames rising from a hazard zone, wreck, or campfire for up to 12 seconds.

```js
eg.fx.fire(eg.world.offset(player, 8, 0), { size: 1.6, seconds: 6 });
```

### `eg.fx.confetti(at: point | player, opts?: { size?: number })`

A celebratory burst of colorful confetti around a point or player. *Private games.* (returns nothing)

**In game:** Showers colorful fluttering confetti around the winner in 3D space—awesome for podiums and milestone unlocks.

```js
eg.fx.confetti(player, { size: 1.4 });
eg.audio.cue(player, 'ui.race_finish');
```

### `eg.fx.ring(at: point | player, opts?: { color?: string, radius?: number, seconds?: number })`

An expanding shockwave or pulse ring on the ground. *Private games.* (returns nothing)

**In game:** Expands a crisp glowing pulse ring across the ground for radar pings, shockwaves, or zone captures.

```js
eg.fx.ring(player, { color: '#38bdf8', radius: 12, seconds: 1.1 });
```

### `eg.fx.explosion(at: point | player, opts?: { size?: number, damage?: number, radius?: number, by?: player })`

A blast everyone near sees and hears. With `damage` it hurts players and characters within `radius` metres (8), less the farther they are; `by` is the player credited. *Private games.* (returns nothing)

**In game:** Detonates a flash, fireball, and smoke cloud while dealing distance-scaled blast damage to players and NPCs.

```js
eg.fx.explosion(eg.world.offset(player, 12, 0), { size: 1.5, damage: 75, radius: 10, by: player });
```

### `eg.fx.flash(player | null, opts?: { color?: "red" | "white" | "green", seconds?: number })`

Flash the edges of a player's screen (null: everyone). *Private games.* (returns nothing)

**In game:** Flashes a red, white, or green vignette around the edges of the screen for hits, flashbangs, or heals.

```js
eg.fx.flash(player, { color: 'red', seconds: 0.4 });
```

## eg.ui

What a player sees: toasts, HUD cards, result cards, menus, rich multi-block windows, awaitable modal prompts & forms, banners, countdowns, hints, and GPS waypoints.

### `eg.ui.toast(player | null, text: string, tone?: 'info' | 'good' | 'warn')`

A short message. null sends it to everyone in the game. (returns nothing)

**In game:** Slides a sleek pill notification under the top compass (`"info"`, `"good"` emerald, or `"warn"` amber) that auto-fades.

```js
eg.ui.toast(player, eg.t('Picked up the package!'), 'good');
```

### `eg.ui.hud(player | null, parts: HudPart[] | null)`

Set a player's HUD card for this game (null clears it). See HUD_PARTS for the pieces. (returns nothing)

**In game:** Replaces the game's top-center HUD card with live distances, clocks, progress bars, counters, badges, and buttons.

```js
eg.ui.hud(player, [
  { type: 'title', text: 'Escort' },
  { type: 'badge', text: 'LIVE', tone: 'good' },
  { type: 'bar', value: 75, max: 100, text: 'Convoy 75%' }
]);
```

### `eg.ui.card(player, card: { title: string, lines?: string[], buttons?: Button[], seconds?: number } | null)`

A result card (shown in place of the HUD until closed or `seconds` pass). (returns nothing)

**In game:** Temporarily displays a bold result card over the HUD with summary lines and action buttons until clicked or `seconds` pass.

```js
eg.ui.card(player, {
  title: 'Delivery Complete!',
  lines: ['Reward: +250 pts', 'Time: {time:84}'],
  buttons: [{ id: 'again', label: 'Play again' }, { id: 'close', label: 'Close', action: 'close' }],
  seconds: 15
});
```

### `eg.ui.menu(player, menu: { id: string, title: string, tabs?: { id: string, label: string }[], tab?: string, text?: string, items?: { id: string, title: string, detail?: string, button?: string, disabled?: boolean }[], rows?: string[], note?: string } | null)`

Open (or replace, or with null close) a panel with a list of choices. A choice fires onUi with { from: "menu", id, item }; a tab fires { from: "menu", id, tab }. (returns nothing)

**In game:** Opens a clean docked left-side list menu with tabs, live "… away" distances on geo items, and action buttons.

```js
eg.ui.menu(player, {
  id: 'shop', title: 'Loadout Shop',
  tabs: [{ id: 'weapons', label: 'Weapons' }, { id: 'gear', label: 'Gear' }],
  tab: 'weapons',
  items: [{ id: 'smg', title: 'SMG', detail: '90 rounds · $150', button: 'Buy' }],
  note: 'Press J to toggle'
});
```

### `eg.ui.window(player | null, win: WindowDef | null)`

Open or update a structured window (up to 3 per player; null closes all). Supports centered modals or docked left/right panels with tabs, stats, bars, tables, callouts, badges, lists and buttons. Interactions fire onUi with from "window". (returns nothing)

**In game:** Opens a rich structured window (centered modal or docked left/right panel) with stat grids, tables, callouts, lists, badges, tabs, and buttons.

```js
eg.ui.window(player, {
  id: 'briefing', title: 'Heist Briefing', subtitle: 'Downtown Bank',
  position: 'center', width: 'md', backdrop: true,
  blocks: [
    { type: 'stats', items: [{ label: 'Crew', value: '3/4' }, { label: 'Payout', value: '$5,000', tone: 'good' }] },
    { type: 'callout', tone: 'warn', title: 'Silent Entry', text: 'Stay off cameras until the vault opens.' },
    { type: 'bar', value: 2, max: 3, text: 'Prep Tasks 2 / 3' }
  ],
  buttons: [{ id: 'ready', label: 'Ready Up', style: 'primary' }, { id: 'close', label: 'Later', action: 'close', style: 'ghost' }]
});
```

### `eg.ui.closeWindow(player | null, id?: string)`

Close one open window by id, or all open windows when `id` is omitted. (returns nothing)

**In game:** Closes one specific window by id (or all open windows for that player when id is omitted) without disturbing their HUD.

```js
eg.ui.closeWindow(player, 'briefing');
```

### `eg.ui.confirm(player, opts: ConfirmOpts): Promise<boolean>`

Open a Yes/No modal dialog for one player and await their answer (`true` when confirmed, `false` when cancelled, closed or timed out). (returns a Promise)

**In game:** Pops up a focus-trapped Yes/No confirmation modal, pauses driving keys cleanly, and resolves directly to `true` or `false` in your script.

```js
const sure = await eg.ui.confirm(player, {
  title: 'Start Sudden Death?',
  body: 'Respawns will be disabled for everyone.',
  ok: 'Start Now', cancel: 'Cancel', danger: true
});
if (sure) eg.ui.banner(null, { title: 'SUDDEN DEATH', tone: 'bad' });
```

### `eg.ui.prompt(player, opts: PromptOpts): Promise<string | null>`

Open a text-input modal dialog for one player and await what they type (up to 240 characters), or `null` when cancelled. (returns a Promise)

**In game:** Opens a focus-trapped text input dialog, releases pointer lock so the player can type, and awaits their sanitized string (or null on Cancel).

```js
const name = await eg.ui.prompt(player, {
  title: 'Name Your Squad',
  label: 'Team callsign',
  placeholder: 'e.g. Nighthawks',
  maxLength: 24
});
if (name) eg.ui.toast(player, eg.t('Callsign set: {name}', { name }), 'good');
```

### `eg.ui.choose(player, opts: ChooseOpts): Promise<string | null>`

Open a choice/dialogue picker modal for one player and await the chosen option's `id`, or `null` when cancelled. (returns a Promise)

**In game:** Shows an interactive choice/dialogue picker modal and awaits whichever option id the player clicks (or null if dismissed).

```js
const pick = await eg.ui.choose(player, {
  title: 'Choose Starting Class',
  body: 'Pick how you want to play this round.',
  options: [
    { id: 'medic', label: 'Field Medic', detail: '2x Medkits + Pistol' },
    { id: 'scout', label: 'Scout', detail: 'SMG + Fast Sprint' }
  ]
});
if (pick === 'medic') eg.inventory.give(player, 'medkit', 2);
```

### `eg.ui.form(player, opts: FormOpts): Promise<{ [key: string]: string | number | boolean } | null>`

Open a multi-field modal form (`text`, `number`, `select`, `checkbox`, `slider`, up to 8 fields) and await `{ [name]: value }`, or `null` when cancelled. (returns a Promise)

**In game:** Renders a full multi-field settings or creator modal (text, number, select, checkbox, slider) and awaits typed, validated values.

```js
const cfg = await eg.ui.form(player, {
  title: 'Match Settings',
  fields: [
    { name: 'rounds', label: 'Rounds', type: 'slider', min: 1, max: 10, value: 3 },
    { name: 'weather', label: 'Weather', type: 'select', options: [{ value: 'clear', label: 'Clear' }, { value: 'storm', label: 'Storm' }], value: 'clear' },
    { name: 'pvp', label: 'Allow PvP', type: 'checkbox', value: true }
  ],
  ok: 'Apply'
});
if (cfg) eg.world.setWeather(cfg.weather);
```

### `eg.ui.banner(player | null, banner: BannerDef | null)`

Show a bold announcement banner across the upper center of the screen (null clears it). (returns nothing)

**In game:** Displays a dramatic glass announcement banner across the upper-center viewport with colored accent border and subtitle.

```js
eg.ui.banner(null, {
  title: 'WAVE 5 — BOSS INCOMING',
  subtitle: 'Defend the central plaza',
  tone: 'bad',
  seconds: 4
});
```

### `eg.ui.hint(player | null, text: string | null)`

Show a subtle control or action hint pill near the bottom HUD (null clears it). (returns nothing)

**In game:** Shows a lightweight control/tip pill right above the bottom HUD bar without interrupting gameplay (pass null to clear).

```js
eg.ui.hint(player, 'Hold Shift to sprint · Press H to use a medkit');
```

### `eg.ui.countdown(player | null, opts: CountdownOpts | null)`

Show a big 3, 2, 1, GO! countdown overlay in the center of the screen (null cancels it). (returns nothing)

**In game:** Counts down 3... 2... 1... GO! in huge animated center-screen numerals with optional audio beeps.

```js
eg.ui.countdown(null, { seconds: 3, label: 'RACE STARTS IN', goText: 'DRIVE!', sound: true });
```

### `eg.ui.clear(player | null)`

Clear every game HUD, card, menu, window, banner, countdown and GPS waypoint for a player (null: everyone). (returns nothing)

**In game:** Instantly wipes every custom HUD card, menu, window, banner, countdown, and GPS route for a clean slate.

```js
eg.ui.clear(player);
```

### `eg.ui.waypoint(player, at: point | null, opts?: { hint?: string, hintM?: number })`

Guide a player to a point with the GPS (null lets go of it). `hint` is shown once when they arrive within hintM metres. (returns nothing)

**In game:** Locks the player's GPS route line and minimap beacon onto a point and triggers a hint pill once within `hintM` metres.

```js
const dest = eg.world.offset(player, 0, -350);
eg.ui.waypoint(player, dest, { hint: 'Arrived at drop-off!', hintM: 18 });
```

## eg.chat

Post game announcements, private clues, and team callouts straight into players' in-game chat feeds.

### `eg.chat.announce(text: string, opts?: { tone?: 'info' | 'good' | 'warn', label?: string })`

Post a game line into the chat window for everyone currently in this game. (returns nothing)

**In game:** Posts a formatted game event line directly into the in-game chat log of everyone in the match, translated per player.

```js
eg.chat.announce(eg.t('{name} captured the flag!', { name: player }), { label: 'Flag Rush', tone: 'good' });
```

### `eg.chat.tell(player, text: string, opts?: { tone?: 'info' | 'good' | 'warn', label?: string })`

Post a private game line into one player's chat window. (returns nothing)

**In game:** Posts a private message visible only in that one player's chat feed.

```js
eg.chat.tell(player, eg.t('Secret stash clue: look behind the gas station.'), { label: 'Informant' });
```

### `eg.chat.team(team: string, text: string, opts?: { tone?: 'info' | 'good' | 'warn', label?: string })`

Post a game line into the chat window of every player on one team. (returns nothing)

**In game:** Sends a tactical team-only chat alert exclusively to members of the named team.

```js
eg.chat.team('blue', 'Blue base shield is at 25%!', { label: 'Comms', tone: 'warn' });
```

## eg.audio

Library sound effects for players or locations, plus gamepad haptic rumble.

### `eg.audio.cue(player | null, id: string)`

Play a short sound from the library by id (for instance "ui.job_accept"). (returns nothing)

**In game:** Plays a crisp UI or feedback sound effect from the platform sound library for one player or everyone (null).

```js
eg.audio.cue(player, 'ui.job_accept');
```

### `eg.audio.cueNear(at: point, id: string, opts?: { radius?: number })`

Play a library sound for every player within `radius` metres of a point (150 by default, up to 1000). (returns nothing)

**In game:** Plays a spatial event sound for every player standing within `radius` metres of a landmark or explosion.

```js
eg.audio.cueNear(player, 'ui.job_deliver', { radius: 120 });
```

### `eg.audio.rumble(player | null, opts?: { strength?: number, seconds?: number })`

Vibrate a player's gamepad controller (`strength` 0.1 to 1, `seconds` 0.05 to 2; ignored when using keyboard). (returns nothing)

**In game:** Fires dual-motor haptic controller rumble on blasts, collisions, or heartbeats (safely ignored on keyboard/mouse).

```js
eg.audio.rumble(player, { strength: 0.8, seconds: 0.3 });
```

## eg.scores

Weekly and all-time leaderboards, personal bests, and player rank lookups for your game.

### `eg.scores.add(player, points: number, opts?: { meters?: number, board?: string }): Promise<{ week: number, all: number, runs: number } | null>`

Add points to a signed-in player on this game's weekly and all-time boards. Resolves to their totals, or null for a guest. `board` names a board of your own to add to instead (a count of wins, say); it is not shown on the game's leaderboard. (returns a Promise)

**In game:** Adds points (and optional distance) to a signed-in player's weekly and all-time public game leaderboards.

```js
const tot = await eg.scores.add(player, 150, { meters: 640 });
if (tot) eg.ui.toast(player, eg.t('Total score: {n}', { n: tot.all }), 'good');
```

### `eg.scores.setBest(player, board: string, ms: number, opts?: { meters?: number }): Promise<{ best: number, before: number | null, improved: boolean, rank: number | null } | null>`

Keep a signed-in player's best (lowest) time in milliseconds on a board you name, such as one per track. Resolves to their best now, what it was before, whether this run improved it, and their place on that board; null for a guest. (returns a Promise)

**In game:** Records a player's lowest time in milliseconds on a custom board (e.g. per track) and returns whether they beat their PB.

```js
const r = await eg.scores.setBest(player, 'sprint-1', 42_310, { meters: 1400 });
if (r && r.improved) eg.ui.toast(player, eg.t('New PB! Rank #{rank}', { rank: r.rank }), 'good');
```

### `eg.scores.bestOf(player, board: string): Promise<number | null>`

A player's best time on one of your time boards, or null. (returns a Promise)

**In game:** Reads a signed-in player's fastest saved time on a named board so you can display target times on HUDs.

```js
const pb = await eg.scores.bestOf(player, 'sprint-1');
if (pb != null) eg.ui.toast(player, eg.t('Your best: {s} s', { s: (pb / 1000).toFixed(2) }));
```

### `eg.scores.record(board: string): Promise<number | null>`

The best time anyone has set on one of your time boards, or null. (returns a Promise)

**In game:** Fetches the #1 fastest time anyone has ever set on a board to display a global ghost target to beat.

```js
const wr = await eg.scores.record('sprint-1');
if (wr != null) eg.ui.toast(player, eg.t('Track record: {s} s', { s: (wr / 1000).toFixed(2) }));
```

### `eg.scores.top(period: 'week' | 'all', limit?: number): Promise<{ rank: number, name: string, score: number, runs: number, meters: number }[]>`

The top of a board. (returns a Promise)

**In game:** Queries the top ranked players on your weekly or all-time board to populate an in-game leaderboard window or menu.

```js
const top = await eg.scores.top('week', 5);
eg.ui.menu(player, {
  id: 'lb', title: 'Weekly Top 5',
  rows: top.map(r => r.rank + '. ' + r.name + ' - ' + r.score + ' pts')
});
```

### `eg.scores.rankOf(player, opts?: { period?: 'week' | 'all', board?: string }): Promise<{ rank: number, score: number, runs: number } | null>`

A signed-in player's rank and total score on this game's weekly/all-time board or a custom board, or null. (returns a Promise)

**In game:** Looks up one signed-in player's exact leaderboard rank and score without fetching the entire leaderboard.

```js
const me = await eg.scores.rankOf(player, { period: 'week' });
if (me) eg.ui.toast(player, eg.t('Weekly rank #{rank} ({score} pts)', { rank: me.rank, score: me.score }));
```

## eg.saves

What your game keeps between sessions: a saved world's data in persistent games, and a little data per player in any game.

### `eg.saves.set(key: string, value: any)`

Keep a value with this saved world (persistent games: "instance": { "kind": "persistent" }). It is still there when players come back after everyone left, or after the server restarted: you get everything back in onLoad. Up to 200 keys and 256 KB per world. *Private games.* (returns nothing)

**In game:** Persists world state across restarts in a `"kind": "persistent"` world (restored automatically in `onLoad`).

```js
const wave = (eg.state.wave || 1) + 1;
eg.state.wave = wave;
eg.saves.set('wave', wave);
```

### `eg.saves.get(key?: string): Promise<any>`

One saved value of this world (null when there is none), or without a key everything saved, as { key: value }. *Private games.* (returns a Promise)

**In game:** Reads one saved key (or every key when omitted) from the persistent world storage at any point.

```js
const all = await eg.saves.get();
eg.ui.toast(player, eg.t('World day {d}', { d: all.day || 1 }));
```

### `eg.saves.remove(key: string)`

Forget one saved value of this world. *Private games.* (returns nothing)

**In game:** Deletes an obsolete key from persistent world storage to keep save data clean.

```js
eg.saves.remove('tempContract');
```

### `eg.saves.setPlayer(player, key: string, value: any)`

Keep a value for this player in your game, in any kind of game: an unlock, a best time, where they left off. It follows them into every match and world of this game. Up to 50 keys and 16 KB per player. (returns nothing)

**In game:** Stores persistent progress (XP, unlocks, stats) for that player across every match or world of your game.

```js
const xp = ((await eg.saves.getPlayer(player, 'xp')) || 0) + 100;
eg.saves.setPlayer(player, 'xp', xp);
```

### `eg.saves.getPlayer(player, key?: string): Promise<any>`

One value kept for this player (null when there is none), or without a key everything kept for them. (returns a Promise)

**In game:** Loads a player's saved unlocks or career XP when they join any lobby of your game.

```js
const xp = (await eg.saves.getPlayer(player, 'xp')) || 0;
eg.ui.hud(player, [{ type: 'counter', text: 'Career XP', value: xp }]);
```

### `eg.saves.removePlayer(player, key: string)`

Forget one value kept for this player. (returns nothing)

**In game:** Clears a saved key from one player's persistent data (e.g. resetting progress or completing a multi-session quest).

```js
eg.saves.removePlayer(player, 'activeBounty');
```

## eg.reports

A report of a round that its signed-in players and their organization can open later: each route on a map, with your numbers. The Response drill saves one after every drill.

### `eg.reports.save(report: { title: string, lines?: string[], points?: { label: string, at: point }[], players: { player: string, path?: [number, number, number][], stats?: { label: string, value: string }[] }[] }): Promise<{ id: string, url: string } | null>`

Save a report of the round that its signed-in players (and the admins of their organization) can open later: a map of each player's route (`path`: [lat, lon, seconds] points, up to 1500), their numbers, and your lines. `player` is a player's id. Show it with a card button whose action is "report" and whose id is the report id. Null when nobody signed in played. One report every 30 seconds per game. (returns a Promise)

**In game:** Generates a shareable post-match map & stats report page (`/reports/<id>`) that players can open in a single click.

```js
const rep = await eg.reports.save({
  title: 'Drill Summary',
  lines: ['Target response time: 4:00'],
  players: [{ player: player.id, stats: [{ label: 'Time', value: '3:12' }] }]
});
if (rep) eg.ui.card(player, { title: 'Drill Complete', buttons: [{ id: rep.id, label: 'Open Report', action: 'report' }] });
```

## eg.instance

Inspect and control the running game itself: title, phase, locks, player cap, uptime, restarts, and shutdown.

### `eg.instance.setPhase(phase: string)`

Name the part of the game that is running ("lobby", "round 2", "over"). It is yours to choose; it is shown where the game is listed. *Private games.* (returns nothing)

**In game:** Updates the public phase label shown in the lobby browser and instance status.

```js
eg.instance.setPhase('wave 3');
```

### `eg.instance.setTitle(title: string)`

Update the running instance's live title shown in the instance bar. *Private games.* (returns nothing)

**In game:** Updates the live match title displayed across everyone's top private-instance bar.

```js
eg.instance.setTitle('Night Shift · Wave 4');
```

### `eg.instance.lock(locked?: boolean)`

Stop new players joining (a round is under way), or with false let them in again. Players already in the game are not affected. *Private games.* (returns nothing)

**In game:** Blocks new players from joining mid-round by invite code while keeping current players uninterrupted (`lock(false)` reopens).

```js
eg.instance.lock(true);
eg.ui.toast(null, 'Match locked — round in progress.');
```

### `eg.instance.restart()`

Start the game over in place for a new round: the script starts again from onStart (after onLoad in a persistent game) with the players it has, and everything it put in the world is cleared. Saves are kept. *Private games.* (returns nothing)

**In game:** Clears temporary entities/NPCs and restarts the script cleanly from `onLoad`/`onStart` with the same players inside.

```js
eg.ui.banner(null, { title: 'New Round Starting!', tone: 'good' });
eg.timers.after(3, () => eg.instance.restart());
```

### `eg.instance.info(): { game: string, kind: string, title: string, version: string }`

About this running game. (answers at once)

**In game:** Reads the running game's id, instance kind ("match" or "persistent"), title, and manifest version.

```js
const inf = eg.instance.info();
eg.ui.toast(player, eg.t('Welcome to {title} v{v}', { title: inf.title, v: inf.version }));
```

### `eg.instance.playersMax(): number`

Maximum number of players allowed in this running instance. (answers at once)

**In game:** Returns the lobby capacity from `game.json` so lobby HUDs can display "4 / 8 players".

```js
eg.ui.hud(player, [{ type: 'counter', text: 'Players', value: eg.players.count() + ' / ' + eg.instance.playersMax() }]);
```

### `eg.instance.isLocked(): boolean`

True when the instance is currently locked against new joins. (answers at once)

**In game:** Lets scripts inspect whether the lobby currently accepts new arrivals before rendering lobby controls.

```js
const state = eg.instance.isLocked() ? 'Locked' : 'Open';
eg.ui.toast(player, eg.t('Lobby is {state}', { state }));
```

### `eg.instance.phase(): string`

The current phase string set by `instance.setPhase` (default "play" or "lobby"). (answers at once)

**In game:** Returns the active phase label set by `instance.setPhase` so late joiners see the right onboarding prompt.

```js
if (eg.instance.phase() === 'lobby') {
  eg.ui.hint(player, 'Round starts once host confirms.');
}
```

### `eg.instance.uptimeS(): number`

Seconds since this running script started. (answers at once)

**In game:** Returns whole seconds elapsed since the instance script booted—useful for survival records or idle checks.

```js
const mins = Math.floor(eg.instance.uptimeS() / 60);
eg.ui.toast(player, eg.t('Server uptime: {m} min', { m: mins }));
```

### `eg.instance.end(reason?: string)`

End the game and send everyone back to the shared world. *Private games.* (returns nothing)

**In game:** Closes the private match and gracefully returns every player to the shared Free Roam world.

```js
eg.ui.toast(null, 'Match complete! Returning to world.', 'good');
eg.timers.after(4, () => eg.instance.end('finished'));
```

## eg.timers

Schedule callbacks once or on an interval, inspect active timers, or clear them all at once.

### `eg.timers.after(seconds: number, fn: () => void): number`

Run a function once, later. Returns an id for timers.cancel. (answers at once)

**In game:** Schedules a one-off callback in `seconds` without risking frozen threads—ideal for round starts or delayed explosions.

```js
eg.timers.after(5, () => {
  eg.ui.banner(null, { title: 'Gates Open!', tone: 'good' });
});
```

### `eg.timers.every(seconds: number, fn: () => void): number`

Run a function again and again (at most ten times a second). (answers at once)

**In game:** Runs a repeating interval (down to 0.1 s) for capture ticks, poison hazards, or passive health regeneration.

```js
eg.state.tickId = eg.timers.every(1, () => {
  for (const p of eg.players.all()) eg.combat.heal(p, 2);
});
```

### `eg.timers.cancel(id: number)`

Stop a timer. (answers at once)

**In game:** Stops a specific timer by id—essential when cancelling a bomb defuse or round clock early.

```js
if (eg.state.tickId) {
  eg.timers.cancel(eg.state.tickId);
  eg.state.tickId = null;
}
```

### `eg.timers.cancelAll()`

Stop every active timer in this script at once. (answers at once)

**In game:** Stops every active `after` and `every` timer in one call when transitioning abruptly between phases.

```js
eg.timers.cancelAll();
eg.ui.toast(null, 'Sudden pause — all timers cleared.');
```

### `eg.timers.count(): number`

How many timers are currently active. (answers at once)

**In game:** Counts active timers so you can verify cleanup and stay well inside the 500-timer sandbox limit.

```js
console.log('Active timers:', eg.timers.count());
```

## eg.math

Convenient game math and randomness helpers: clamp, lerp, random integers, weighted loot rolls, shuffling, and seeded PRNGs.

### `eg.math.clamp(value: number, min: number, max: number): number`

Constrain a number between `min` and `max`. (answers at once)

**In game:** Keeps difficulty multipliers, scores, or speeds safely within bounded min/max limits.

```js
const level = eg.math.clamp((eg.state.wave || 0) + 1, 1, 20);
```

### `eg.math.lerp(a: number, b: number, t: number): number`

Linearly interpolate from `a` to `b` by fraction `t` (0 to 1). (answers at once)

**In game:** Smoothly blends difficulty, rewards, or enemy speeds between a start and end value as rounds progress.

```js
const speed = eg.math.lerp(4, 9, 0.5); // 6.5
```

### `eg.math.randomInt(min: number, max: number): number`

A random whole number from `min` through `max` (inclusive). (answers at once)

**In game:** Rolls an inclusive random integer for loot payouts, dice games, or wave sizes.

```js
const bonus = eg.math.randomInt(25, 100);
eg.ui.toast(player, eg.t('Found +{n} bonus points!', { n: bonus }), 'good');
```

### `eg.math.pick(list: any[]): any`

Return one random element from an array, or null when empty. (answers at once)

**In game:** Picks a random entry from any array (weather presets, spawn points, loot weapons, or quips).

```js
const wx = eg.math.pick(['clear', 'rain', 'fog', 'storm']);
eg.world.setWeather(wx);
```

### `eg.math.shuffle(list: any[]): any[]`

Return a new randomly shuffled copy of an array without mutating the original. (answers at once)

**In game:** Creates a fair, unbiased random ordering of players, checkpoints, or card decks without mutating the source array.

```js
const order = eg.math.shuffle(eg.players.all());
order.forEach((p, i) => eg.ui.toast(p, eg.t('Turn #{n}', { n: i + 1 })));
```

### `eg.math.weighted(entries: { item: any, weight: number }[]): any`

Pick one item at random proportional to positive `weight` values, or null when empty. (answers at once)

**In game:** Rolls rarity-weighted loot tables so common gear drops often while rare shotguns feel exciting.

```js
const prize = eg.math.weighted([
  { item: 'bat', weight: 60 },
  { item: 'pistol', weight: 30 },
  { item: 'shotgun', weight: 10 }
]);
eg.inventory.give(player, prize, prize === 'bat' ? 1 : 18);
```

### `eg.math.seed(seed: string | number): () => number`

Create a fast, deterministic random number generator returning numbers between 0 and 1. (answers at once)

**In game:** Creates a deterministic RNG stream so daily challenges or shared seeds produce identical spawns every run.

```js
const rng = eg.math.seed('daily-' + Math.floor(eg.world.now() / 86400000));
const dist = 80 + rng() * 200;
```

## HUD parts

The pieces of a HUD card (`eg.ui.hud`). Text may hold `{dist:1234}`, `{km:2.5}` or `{time:95}`, shown in the player's own units.

### `{ type: 'title', … }`

Fields: `{ text }`. The card's heading.

**In game:** Draws the bold heading line at the top of the player's floating HUD card.

```js
eg.ui.hud(player, [{ type: 'title', text: 'Flag Rush' }]);
```

### `{ type: 'text', … }`

Fields: `{ text }`. A line of text.

**In game:** Displays a formatted text line supporting automatic unit/time tokens (`{dist:1234}`, `{km:2.5}`, `{time:95}`).

```js
eg.ui.hud(player, [{ type: 'text', text: 'Reach the checkpoint before {time:90}' }]);
```

### `{ type: 'badge', … }`

Fields: `{ text, tone?: 'info' | 'good' | 'warn' | 'bad' }`. A colored status pill on the HUD card.

**In game:** Renders a vivid pill tag (`info`, `good`, `warn`, or `bad`) on the HUD card to highlight status at a glance.

```js
eg.ui.hud(player, [{ type: 'badge', text: 'OVERTIME', tone: 'warn' }]);
```

### `{ type: 'distance', … }`

Fields: `{ to: point, text? }`. Live distance from the player to a point, in their units, then the text.

**In game:** Live-updates the exact remaining distance every navigation tick in the player's preferred metric or imperial units.

```js
const goal = eg.world.offset(player, 240, 0);
eg.ui.hud(player, [{ type: 'distance', to: goal, text: 'to extraction' }]);
```

### `{ type: 'bearing', … }`

Fields: `{ to: point, text? }`. Live compass direction and distance from the player to a point.

**In game:** Live-updates a compass cardinal direction plus distance (e.g. "NE · 255 m to beacon") as the player moves.

```js
const target = eg.world.offset(player, 180, -180);
eg.ui.hud(player, [{ type: 'bearing', to: target, text: 'to beacon' }]);
```

### `{ type: 'timer', … }`

Fields: `{ since?: ms, until?: ms, par?: seconds, text? }`. A running clock: time since a moment (with an optional par), or time left until one.

**In game:** Ticks smoothly client-side every second using the synced server clock (`since` counts up with optional `par`, `until` counts down).

```js
eg.ui.hud(player, [{ type: 'timer', until: eg.world.now() + 60_000, text: 'left' }]);
```

### `{ type: 'bar', … }`

Fields: `{ value, max, text? }`. A progress bar.

**In game:** Draws an animated horizontal progress bar filled proportionally to `value / max` with an optional overlay caption.

```js
eg.ui.hud(player, [{ type: 'bar', value: 3, max: 5, text: 'Checkpoints 3 / 5' }]);
```

### `{ type: 'counter', … }`

Fields: `{ text, value }`. A labelled number.

**In game:** Pairs a muted label with a crisp emphasized number or short readout value.

```js
eg.ui.hud(player, [{ type: 'counter', text: 'Wave', value: 4 }]);
```

### `{ type: 'list', … }`

Fields: `{ items: { label, value?, highlight? }[] }`. A compact multi-row status list or mini scoreboard inside the HUD (up to 6 rows).

**In game:** Shows a compact multi-row leaderboard or checklist (up to 6 rows) directly inside the HUD card.

```js
eg.ui.hud(player, [{
  type: 'list',
  items: [
    { label: '1. Mira', value: 420, highlight: true },
    { label: '2. Alex', value: 380 }
  ]
}]);
```

### `{ type: 'divider', … }`

Fields: `{}`. A thin horizontal separator line between sections of the HUD card.

**In game:** Inserts a crisp horizontal divider line to visually separate sections inside longer HUD cards.

```js
eg.ui.hud(player, [
  { type: 'title', text: 'Heist' },
  { type: 'divider' },
  { type: 'counter', text: 'Loot', value: '$1,200' }
]);
```

### `{ type: 'button', … }`

Fields: `{ id, label, action?: 'signin' | 'waypoint' | 'close' | 'report' }`. A button. Fires onUi { from: "hud", id }, or does a built-in action ("report": opens the saved report whose id is the button id).

**In game:** Places a clickable button right on the HUD card that sends `onUi` (`from: "hud"`) or runs built-in actions (`signin`, `waypoint`, `close`, `report`).

```js
eg.ui.hud(player, [{ type: 'button', id: 'shop', label: 'Open Shop' }]);
```

### `{ type: 'teams', … }`

Fields: `{}`. The teams and their scores as they are when you send it, the player's own team marked.

**In game:** Renders color-coded pill badges for every defined team and its score, highlighting the viewing player's own team.

```js
eg.ui.hud(player, [{ type: 'teams' }]);
```

## eg.state

A plain object that is yours for as long as the game runs.

**In game:** A plain JavaScript object preserved in memory across all event handlers for as long as the match runs (cleared on restart/close).

```js
eg.state.round = (eg.state.round || 0) + 1;
eg.state.scores = {};
eg.ui.toast(null, eg.t('Round {n} begin!', { n: eg.state.round }));
```

## eg.t

### `eg.t(text: string, values?: { [name: string]: string | number | Player }): string`

Text players see, in English with its values filled in, marked so that each player gets it in their own language: eg.ui.toast(player, eg.t('{n, plural, one {# flag} other {# flags}} to go', { n })). Write the text out in quotes where you call it; put the parts that change in as {names} (a player becomes their name). Use the result anywhere players see text: toasts, the HUD, cards, menus, labels, waypoint hints. Translations come from your lang/<code>.json files and, once the game is live and played, from the platform. (answers at once)

**In game:** Marks text for per-player translation (from `lang/*.json` or live AI translations) while rendering English + ICU plurals automatically.

```js
const left = 3;
eg.ui.toast(player, eg.t('{n, plural, one {# flag} other {# flags}} remaining', { n: left }), 'good');
```

How translating works, step by step: the guide, "Translating your game" (guide.md).
