EARTH GAMESƏVVƏL ERİŞİM
Home›Developers›Examples
SDK EXAMPLES5 COMPLETE GAMES

Example games & source browser

Read the full server.js and game.json for every game shipped in the Earth Games kit — from a 30-line starter to full multi-system games.

Flag Hunt

Minimal starter: spawns a flag 60 m north of each player anywhere on Earth and updates their HUD.

starter
$npx earthgames new my-blank --template blank
blank/server.js
js
// The rules of your game. This file runs on Earth Games' servers, once for each running copy of
// the game. It reacts to events (a player joined, entered a zone, pressed a button) and calls
// `eg` to change the world and what players see. The full list: docs/api.md, or hover in your editor.
//
// This starter puts a flag 60 metres north of wherever each player starts and counts who reaches it.
// Nothing in it is a fixed coordinate, so it plays anywhere on Earth.
//
// Text players see goes through eg.t('…'): it reaches each player in their own language once the game
// has translations (your own in lang/<code>.json, see docs/guide.md "Translating your game").
const found = new Map(); // player id → flags reached
 
function hud(player) {
  eg.ui.hud(player, [
    { type: 'title', text: eg.t('My Game') },
    { type: 'counter', text: eg.t('Flags'), value: found.get(player.id) || 0 },
  ]);
}
function placeFlag(player) {
  const at = eg.world.offset(player, 0, -60); // 60 m north of them
  eg.entities.add({ id: `flag-${player.id}`, kind: 'zone', at, radius: 6, label: eg.t('Flag'), style: 'default', radar: true, visibleTo: player, trigger: {} });
  eg.ui.waypoint(player, at, { hint: eg.t('Walk into the ring') });
}
 
export default {
  onStart() {
    console.log('The game started.'); // shows in "earthgames dev" and in the in-game console (only you see it: no eg.t)
  },
  onPlayerJoin(player) {
    found.set(player.id, 0);
    eg.ui.toast(player, eg.t('Find the flag, {name}.', { name: player }), 'info');
    hud(player);
    placeFlag(player);
  },
  onZone(player, entityId, what) {
    if (what !== 'enter' || entityId !== `flag-${player.id}`) return;
    const n = (found.get(player.id) || 0) + 1;
    found.set(player.id, n);
    eg.audio.cue(player, 'ui.job_deliver');
    eg.ui.toast(player, eg.t('{n, plural, one {Your first flag.} other {That makes # flags.}} Here is another.', { n }), 'good');
    hud(player);
    placeFlag(player); // the same id again moves the flag
  },
  onPlayerLeave(player) {
    found.delete(player.id);
  },
};

Pursuit

Rule-based spawners keep chasers 50–120 m around players on any street without a single hardcoded coordinate.

starter
$npx earthgames new my-pursuit --template pursuit
pursuit/server.js
js
// Pursuit: an official Earth Games example of a private game that plays anywhere.
// A pack of chasers keeps appearing around the players, out of sight, and runs at them. Every hit
// counts against you; the HUD shows how long you have lasted and how often you were caught.
// Nothing here is tied to a place: the spawner is a rule ("on open ground, 50 to 120 m from any
// player"), so the game is the same in a city centre or a field.
// Every text players see is marked with eg.t, and lang/fr.json has it in French: a player who
// chose French gets "Ils arrivent. Ne vous arrêtez pas." where everyone else reads the English.
const caught = new Map(); // player id → times caught
let startedAt = 0;
 
function hud(player) {
  eg.ui.hud(player, [
    { type: 'title', text: eg.t('Pursuit') },
    { type: 'timer', since: startedAt, text: eg.t('on the run') },
    { type: 'counter', text: eg.t('Caught'), value: caught.get(player.id) || 0 },
  ]);
}
 
export default {
  onStart() {
    startedAt = eg.world.now();
    eg.npcs.kinds([{ id: 'chaser', name: 'Chaser', brain: 'chase', speed: 1.6, runSpeed: 5.5, sight: 120, attack: { range: 1.4, damage: 10, cooldownS: 1.5 } }]);
    eg.spawners.add({ id: 'pack', kind: 'chaser', capNear: 10, capTotal: 40, perSecond: 1, where: { minFromPlayersM: 50, maxFromPlayersM: 120 } });
  },
  onPlayerJoin(player) {
    caught.set(player.id, caught.get(player.id) || 0);
    eg.ui.toast(player, eg.t('They are coming. Keep moving.'), 'warn');
    hud(player);
  },
  onPlayerLeave(player) { caught.delete(player.id); },
  onNpc(event) {
    if (event.ev !== 'attack' || !event.player) return;
    const n = (caught.get(event.player.id) || 0) + 1;
    caught.set(event.player.id, n);
    if (n % 5 === 0) eg.ui.toast(event.player, eg.t('{n, plural, one {Caught # time.} other {Caught # times.}} Keep going.', { n }), 'warn');
    hud(event.player);
  },
};

Horde

Wave survival with escalating enemy classes, custom medkit actions, weapon unlocks, explosions, and leaderboards.

intermediate
$npx earthgames new my-horde --template horde
horde/server.js
js
// Horde: an official Earth Games example of combat in a private game that plays anywhere.
// Waves of attackers appear around the players, out of sight, and run in. Clear a wave and the
// next one is bigger; every few waves a new kind joins and everyone is handed a better weapon.
// When every player is down at the same time the run is over: it is scored and starts again.
//
// What it shows:
//   eg.combat      health, respawns and weapons are the platform's; this script only sets the rules
//   eg.inventory   weapons and rounds, plus an item of the game's own (medkits, used with H)
//   eg.spawners    rule-placed ("40 to 90 m from any player"), so there is not one coordinate here
//   eg.fx          a blast when a brute goes down
//   onNpc          counts kills from 'died', and keeps each wave's numbers honest
const KINDS = [
  { id: 'walker', name: 'Walker', brain: 'chase', speed: 1.3, runSpeed: 3.2, health: 60, sight: 150, attack: { range: 1.4, damage: 12, cooldownS: 1.4 } },
  { id: 'runner', name: 'Runner', brain: 'chase', speed: 1.8, runSpeed: 6.2, health: 40, sight: 150, attack: { range: 1.4, damage: 8, cooldownS: 1.0 } },
  { id: 'brute', name: 'Brute', brain: 'chase', scale: 1.25, speed: 1.2, runSpeed: 3.8, health: 260, sight: 150, attack: { range: 1.7, damage: 30, cooldownS: 2.0, windupS: .7 } },
];
const START = { pistol: 60, bat: 1, medkit: 2 };
const BREAK_S = 8, OVER_S = 12;
/** How many of each kind wave n holds, for this many players. */
function waveOf(n, players) {
  const k = 1 + .6 * (Math.max(1, players) - 1);
  return { walker: Math.round((5 + n * 2) * k), runner: n >= 3 ? Math.round((n - 1) * 1.5 * k) : 0, brute: n >= 5 ? Math.round((n - 3) / 2 * k) : 0 };
}
 
let wave = 0, phase = 'wait'; // wait (nobody here) | fight | break | over
let left = { walker: 0, runner: 0, brute: 0 }; // still to appear this wave
const alive = new Map(); // character id → kind
const kills = new Map(); // player id → kills this run
let dirty = false, timer = 0;
 
const remaining = () => alive.size + left.walker + left.runner + left.brute;
function hud(player) {
  eg.ui.hud(player, [
    { type: 'title', text: phase === 'break' ? `Wave ${wave} cleared` : phase === 'over' ? 'Overrun' : `Wave ${wave}` },
    { type: 'counter', text: 'Left', value: phase === 'fight' ? remaining() : 0 },
    { type: 'counter', text: 'Kills', value: kills.get(player.id) || 0 },
  ]);
}
const hudAll = () => { for (const p of eg.players.all()) hud(p); };
 
function startWave() {
  wave++; phase = 'fight';
  left = waveOf(wave, eg.players.count());
  for (const k of KINDS) eg.spawners.enable(k.id, left[k.id] > 0);
  eg.ui.toast(null, wave === 1 ? 'They are coming. Left mouse fires, Q changes weapon, H uses a medkit.' : `Wave ${wave}.`, 'warn');
  hudAll();
}
function endWave() {
  phase = 'break';
  for (const p of eg.players.all()) {
    eg.combat.heal(p, 40); eg.inventory.give(p, 'pistol', 30);
    if (wave === 2) { eg.inventory.give(p, 'shotgun', 18); eg.ui.toast(p, 'Shotgun. Q changes weapon.', 'good'); }
    if (wave === 4) { eg.inventory.give(p, 'smg', 120); eg.ui.toast(p, 'SMG. Q changes weapon.', 'good'); }
    if (wave > 4) { eg.inventory.give(p, 'shotgun', 12); eg.inventory.give(p, 'smg', 60); }
    if (wave % 3 === 0) eg.inventory.give(p, 'medkit', 1);
  }
  eg.audio.cue(null, 'ui.job_deliver');
  hudAll();
  timer = eg.timers.after(BREAK_S, startWave);
}
function stop() {
  eg.timers.cancel(timer);
  for (const k of KINDS) eg.spawners.enable(k.id, false);
  eg.npcs.clear(); alive.clear(); left = { walker: 0, runner: 0, brute: 0 };
}
function gameOver() {
  phase = 'over'; stop();
  for (const p of eg.players.all()) {
    const mine = kills.get(p.id) || 0;
    eg.ui.card(p, { title: `Overrun on wave ${wave}`, lines: [`${mine} ${mine === 1 ? 'kill' : 'kills'}`, `Starting again in ${OVER_S} seconds.`], seconds: OVER_S, buttons: [{ id: 'close', label: 'Close', action: 'close' }] });
    if (!p.guest && wave > 1) eg.scores.add(p, (wave - 1) * 100 + mine * 10);
  }
  hudAll();
  timer = eg.timers.after(OVER_S, () => {
    wave = 0; kills.clear();
    for (const p of eg.players.all()) { eg.combat.respawn(p); eg.inventory.setLoadout(p, START); }
    startWave();
  });
}
 
export default {
  onStart() {
    eg.npcs.kinds(KINDS);
    eg.combat.enable({ health: 100, respawnS: 10, loadout: START });
    for (const k of KINDS) {
      eg.spawners.add({ id: k.id, kind: k.id, capNear: k.id === 'brute' ? 2 : 14, capTotal: 60, perSecond: k.id === 'brute' ? .3 : 1.5, where: { minFromPlayersM: 40, maxFromPlayersM: 90 } });
      eg.spawners.enable(k.id, false);
    }
    eg.timers.every(.5, () => { if (dirty) { dirty = false; hudAll(); } });
  },
  onPlayerJoin(player) {
    kills.set(player.id, kills.get(player.id) || 0);
    hud(player);
    if (phase === 'wait') { phase = 'break'; eg.ui.toast(player, 'Get ready.', 'info'); timer = eg.timers.after(4, startWave); }
  },
  onPlayerLeave(player) {
    kills.delete(player.id);
    if (eg.players.count() === 0) { stop(); wave = 0; phase = 'wait'; }
  },
  onPlayerDied(player) {
    if (phase !== 'fight') return;
    if (eg.players.all().every(p => p.dead || p.id === player.id)) gameOver();
    else eg.ui.toast(null, `${player.name} is down.`, 'warn');
  },
  async onUi(player, what) {
    if (what.from !== 'action' || what.id !== 'medkit') return;
    const me = eg.players.get(player);
    if (!me || me.dead) return;
    const inv = await eg.inventory.get(player);
    if (!(inv.medkit > 0)) return eg.ui.toast(player, 'No medkits left.', 'warn');
    eg.inventory.take(player, 'medkit', 1); eg.combat.heal(player, 50);
    eg.fx.flash(player, { color: 'green' });
    eg.ui.toast(player, `Medkit used. ${inv.medkit - 1} left.`, 'good');
  },
  onNpc(event) {
    if (event.ev === 'spawned') {
      alive.set(event.id, event.kind);
      if (phase !== 'fight') return eg.npcs.despawn(event.id); // one that appeared just as the wave ended
      if (--left[event.kind] <= 0) eg.spawners.enable(event.kind, false);
    } else if (event.ev === 'died') {
      if (!alive.delete(event.id)) return;
      if (event.player) kills.set(event.player.id, (kills.get(event.player.id) || 0) + 1);
      if (event.kind === 'brute') eg.fx.explosion({ lat: event.lat, lon: event.lon }, { size: .5 });
      if (phase === 'fight' && remaining() <= 0) return endWave();
    } else if (event.ev === 'gone') {
      // Left far behind and removed while still alive: it goes back on the wave's list.
      const kind = alive.get(event.id); if (!kind || !alive.delete(event.id) || phase !== 'fight') return;
      left[kind]++; eg.spawners.enable(kind, true);
    } else return;
    dirty = true;
  },
};

First Responder

Emergency dispatch built from real hospitals, police stations, and streets around players, with signal hunting and sirens.

advanced

Reference example in sdk/examples/responder/ (note: team-only badges/garage calls can be omitted in community games).

responder/server.js
js
// First Responder: an official Earth Games example. Everything this game does, it does through the
// public API (`eg`). Three calls marked "team only" below are for games made by the Earth Games
// team (cash, badges, and players wanted in another of our games); leave them out and the rest is
// a game anyone can make.
//
// How it plays: open Dispatch (J), take a call, get to the flare and stop (or hover) inside it.
//   Medevac          pick the patient up at the scene, then set down at the nearest real hospital
//   Search & Rescue  the beacon is somewhere in the search circle: follow the signal bar to it
//   Street emergency get to the scene fast
//   Interceptor      catch up with a reckless driver (or, team only, a player the police are after)
// Beating the par time pays 20 % more; so does a co-pilot riding with you (25 %). Y is the siren.
//
// It works anywhere the map is built: every call is made from real hospitals, police stations and
// named streets around whoever is playing (eg.world.placesNear), never from fixed coordinates.
 
const CALL_LIMIT_S = 8 * 60, ACCEPT_MAX_M = 8000, CREW_MULT = 1.25, ON_TIME_MULT = 1.2;
const STOP_SPEED = 4.5, ZONE_R = 22, SAR_ZONE_R = 18, SAR_SEARCH_R = 240, SAR_OFFSET_M = 85, ELT_RANGE_M = 480, WANTED_M = 4500;
const km = (a, b) => eg.world.distance(a, b) / 1000;
/** The point `m` metres from another, along a bearing (0 north, π/2 east). */
const along = (from, m, bearing) => eg.world.offset(from, Math.sin(bearing) * m, -Math.cos(bearing) * m);
function angleOf(seed) { // the same angle for the same text: a player's calls do not jump about within a minute
  let h = 2166136261;
  for (let i = 0; i < seed.length; i++) h = Math.imul(h ^ seed.charCodeAt(i), 16777619);
  return ((h >>> 0) % 360) * Math.PI / 180;
}
function nearest(list, from, minM, maxM) {
  let best = null, bd = Infinity;
  for (const s of list) { const d = eg.world.distance(from, s); if (d >= minM && d <= maxM && d < bd) { bd = d; best = s; } }
  return best;
}
/** 0 to 1: how strong the beacon's signal is from here. */
const signal = (at, beacon) => Math.max(0, Math.min(1, 1 - eg.world.distance(at, beacon) / ELT_RANGE_M));
 
// ---- the calls on offer: four around each player, new every minute ---------------------------------
const offers = new Map(); // offer id → call (the last few hundred shown)
async function callsFor(p) {
  const minute = Math.floor(eg.world.now() / 60000), base = angleOf(`${p.id}:${minute}`), here = { lat: p.lat, lon: p.lon };
  const [places, wanted] = await Promise.all([
    eg.world.placesNear(here, { maxM: 6000, kinds: ['hospital', 'police', 'street'], max: 64 }),
    eg.players.wanted(here, WANTED_M),                                         // team only
  ]);
  const of = kind => places.filter(s => s.kind === kind);
  const hospital = nearest(of('hospital'), here, 250, 6000) || { ...along(here, 1350, base + 2.4), name: 'Regional Trauma Center' };
  const medScene = nearest([...of('street'), ...of('police')], here, 500, 2600) || { ...along(here, 1100, base + .5), name: 'Highway Milepost Incident' };
  const sarScene = { ...along(here, 1450, base + 1.8), name: 'Downed ELT Transponder' };
  const street = nearest([...of('police'), ...of('street')], here, 280, 1800) || { ...along(here, 760, base + 4.5), name: 'Box-Alarm Intersection Call' };
  const outlaw = wanted[0] || null;
  const chase = outlaw ? { lat: outlaw.lat, lon: outlaw.lon, name: `Suspect ${outlaw.name} (Heat ${outlaw.level})` } : { ...along(here, 1250, base + 5.3), name: 'High-Speed Stolen Sedan' };
  const medKm = km(here, medScene) + km(medScene, hospital), sarKm = km(here, sarScene), stKm = km(here, street), chKm = km(here, chase);
  const id = tag => `${tag}.${p.id}.${minute.toString(36)}`, at = s => ({ lat: s.lat, lon: s.lon, name: s.name });
  const calls = [
    { id: id('med'), kind: 'medevac', title: 'Medevac Transport', badge: 'MEDEVAC', label: `Stabilize the patient and take them to ${hospital.name}`, summary: `${medScene.name} → ${hospital.name}`,
      scene: at(medScene), dropoff: at(hospital), km: Math.max(.4, medKm), parS: Math.max(95, Math.round(medKm * 55 + 45)), points: Math.round(160 + medKm * 25), cash: Math.round(420 + medKm * 60) },
    { id: id('sar'), kind: 'sar', title: 'Search & Rescue', badge: 'ELT SAR', label: 'Find the beacon inside the search circle', summary: 'Follow the rising signal to a downed beacon',
      scene: at(sarScene), search: along(sarScene, SAR_OFFSET_M, base + 3.9), km: Math.max(.5, sarKm), parS: Math.max(120, Math.round(sarKm * 60 + 60)), points: Math.round(180 + sarKm * 25), cash: Math.round(460 + sarKm * 65) },
    { id: id('emg'), kind: 'emergency', title: 'Street Emergency', badge: '10-52', label: `Get to ${street.name} and hold steady`, summary: `Rapid response near ${street.name}`,
      scene: at(street), km: Math.max(.3, stKm), parS: Math.max(70, Math.round(stKm * 50 + 35)), points: Math.round(115 + stKm * 20), cash: Math.round(290 + stKm * 50) },
    { id: id('int'), kind: 'intercept', title: 'Live Interceptor', badge: 'INTERCEPT', label: `Intercept ${chase.name}`, summary: outlaw ? `Live pursuit, heat ${outlaw.level}` : 'Catch up with a reckless driver',
      scene: at(chase), target: outlaw ? outlaw.id : null, km: Math.max(.4, chKm), parS: Math.max(100, Math.round(chKm * 55 + 45)), points: outlaw ? 240 : 190, cash: outlaw ? 600 : 480 },
  ];
  for (const c of calls) { offers.delete(c.id); offers.set(c.id, c); }
  while (offers.size > 400) offers.delete(offers.keys().next().value);
  return calls;
}
 
// ---- a call in progress ----------------------------------------------------------------------------
const runs = new Map(); // player id → the call they are on
let runN = 0;
const REASONS = { abandoned: 'Dispatch cancelled.', expired: 'The call timed out.', left: 'The call closed when you left First Responder.' };
const searching = r => r.call.kind === 'sar' && r.stage === 'scene';
const target = r => (r.stage === 'hospital' ? r.call.dropoff : r.call.scene);
 
function show(r) {
  const p = eg.players.get(r.id); if (!p) return;
  const c = r.call, t = target(r), toHospital = r.stage === 'hospital';
  eg.ui.hud(p, [
    { type: 'title', text: `[${toHospital ? 'TRANSPORT' : c.badge}] ${toHospital ? `Deliver the patient to ${c.dropoff.name}` : c.label}` },
    { type: 'distance', to: searching(r) ? c.search : t },
    { type: 'timer', since: r.acceptedAt, par: c.parS },
    ...(searching(r) ? [{ type: 'bar', value: Math.round(r.signal * 100), max: 100, text: `Signal ${Math.round(r.signal * 100)} %${r.signal >= .8 ? ': very close' : r.signal >= .45 ? ': warming up' : ''}` }] : []),
    ...(p.riders ? [{ type: 'text', text: 'Co-pilot on board: +25 %' }] : []),
    { type: 'button', id: 'siren', label: r.siren ? 'Siren on' : 'Siren' },
    { type: 'button', id: 'route', label: 'Route', action: 'waypoint' },
    { type: 'button', id: 'board', label: 'Dispatch' },
    { type: 'button', id: 'abandon', label: 'Abandon' },
  ]);
}
function guide(r) {
  const hint = r.stage === 'scene' && r.call.dropoff ? 'Stop or hover inside the flare to pick up the patient' : 'Stop or hover inside the flare to finish the call';
  eg.ui.waypoint(r.id, searching(r) ? r.call.search : target(r), { hint, hintM: searching(r) ? SAR_SEARCH_R : ZONE_R });
}
function setZone(r) {
  for (const id of [r.zone, r.ring]) if (id) eg.entities.remove(id);
  const t = target(r), sar = searching(r);
  // The beacon itself is not on the radar: the signal bar is how you find it. The search circle is.
  r.ring = sar ? eg.entities.add({ id: `call-${r.n}-search`, kind: 'zone', at: r.call.search, radius: SAR_SEARCH_R, radar: true, style: 'pickup', visibleTo: r.id, label: 'Search area' }) : null;
  r.zone = eg.entities.add({ id: `call-${r.n}-${r.stage}`, kind: 'zone', at: t, radius: sar ? SAR_ZONE_R : ZONE_R, radar: !sar, style: r.stage === 'hospital' ? 'dropoff' : 'hot', visibleTo: r.id,
    label: r.stage === 'hospital' ? `Drop-off: ${t.name}` : t.name, trigger: { dwellS: sar ? .9 : 1.5, maxSpeed: STOP_SPEED } });
}
function endRun(r) {
  for (const id of [r.zone, r.ring]) if (id) eg.entities.remove(id);
  eg.timers.cancel(r.clock); eg.timers.cancel(r.limit);
  if (runs.get(r.id) === r) runs.delete(r.id);
  if (r.siren) eg.vehicles.siren(r.id, false);
  eg.players.setBusy(r.id, false); eg.ui.hud(r.id, null); eg.ui.waypoint(r.id, null);
}
function voidRun(r, reason) {
  endRun(r);
  const text = REASONS[reason] || 'Dispatch ended.';
  eg.ui.card(r.id, { title: text, lines: ['Open Dispatch (J) for another call.'], buttons: [{ id: 'board', label: 'Dispatch' }, { id: 'close', label: 'Close', action: 'close' }], seconds: 10 });
  eg.ui.toast(r.id, text, reason === 'abandoned' ? 'info' : 'warn');
  eg.audio.cue(r.id, 'ui.job_fail');
}
/** Once a second while a call runs: the beacon's signal, and where a live suspect has got to. */
async function watch(r) {
  const p = eg.players.get(r.id); if (!p || runs.get(r.id) !== r) return;
  if (searching(r)) { const s = signal(p, r.call.scene); if (Math.abs(s - r.signal) >= .03) { r.signal = s; show(r); } }
  if (r.call.target && ++r.ticks % 2 === 0) {
    const now = (await eg.players.wanted(r.call.scene, 6000)).find(w => w.id === r.call.target);   // team only
    if (now && runs.get(r.id) === r && eg.world.distance(now, r.call.scene) > 25) {
      r.call.scene.lat = now.lat; r.call.scene.lon = now.lon;
      eg.entities.update(r.zone, { at: r.call.scene }); guide(r); show(r);
    }
  }
}
async function complete(player, r) {
  endRun(r);
  const c = r.call, seconds = Math.max(1, Math.round((eg.world.now() - r.acceptedAt) / 1000)), onTime = seconds <= c.parS, crew = (player.riders || 0) > 0;
  const mult = (onTime ? ON_TIME_MULT : 1) * (crew ? CREW_MULT : 1), points = Math.round(c.points * mult), cash = Math.round(c.cash * mult);
  const wallet = await eg.players.pay(player, cash);                              // team only
  const lines = [`{time:${seconds}} (par {time:${c.parS}}${onTime ? ', +20 % on time' : ''})${crew ? ' · +25 % co-pilot' : ''} · Wallet $${wallet}`];
  const buttons = [{ id: 'board', label: 'Next call' }, { id: 'close', label: 'Close', action: 'close' }];
  let badge = '';
  if (player.guest) { lines.push('Sign in to keep your points and climb the leaderboard.'); buttons.unshift({ id: 'signin', label: 'Sign in', action: 'signin' }); }
  else {
    const totals = await eg.scores.add(player, points, { meters: Math.round(c.km * 1000) });
    if (totals) {
      if (await eg.players.award(player, { id: 'responder:first', label: 'First Responder' })) badge = ' · 🏅 First Responder';   // team only
      lines.push(`This week ${totals.week} · All time ${totals.all} pts · ${totals.runs} calls${badge}`);
    }
  }
  eg.players.finishRun(player);
  eg.ui.card(player, { title: `${c.title} complete: +${points} pts · +$${cash}`, lines, buttons, seconds: 12 });
  eg.ui.toast(player, `Call complete! +${points} pts · +$${cash}${crew ? ' (co-pilot +25 %)' : ''}${badge}`, 'good');
  eg.audio.cue(player, 'ui.job_deliver');
}
async function accept(player, offerId) {
  if (runs.has(player.id)) return eg.ui.toast(player, 'Finish or abandon your active call first.', 'warn');
  const offer = offers.get(String(offerId));
  if (!offer) { eg.ui.toast(player, 'That call has gone. Here are the calls now.', 'warn'); return showBoard(player); }
  let p = eg.players.get(player); if (!p) return;
  if (eg.world.distance(p, offer.scene) > ACCEPT_MAX_M) return eg.ui.toast(player, 'That call is too far away.', 'warn');
  if (!(await eg.players.startRun(player))) return;       // free players have a daily number of runs; the platform has told them
  p = eg.players.get(player); if (!p || runs.has(p.id)) return;
  const now = eg.world.now();
  const r = { id: p.id, n: ++runN, call: { ...offer, scene: { ...offer.scene } }, stage: 'scene', acceptedAt: now, signal: 0, siren: false, ticks: 0, zone: null, ring: null, clock: 0, limit: 0 };
  r.signal = searching(r) ? signal(p, r.call.scene) : 0;
  runs.set(r.id, r);
  r.clock = eg.timers.every(1, () => watch(r));
  r.limit = eg.timers.after(CALL_LIMIT_S, () => { if (runs.get(r.id) === r) voidRun(r, 'expired'); });
  eg.players.setBusy(p, true); setZone(r);
  eg.ui.menu(p, null); eg.audio.cue(p, 'ui.job_accept'); show(r); guide(r);
}
function siren(player) {
  const r = runs.get(player.id);
  if (!r) return eg.ui.toast(player, 'The siren is for calls: take one from Dispatch (J).', 'info');
  r.siren = !r.siren; eg.vehicles.siren(player, r.siren); show(r);
}
 
// ---- the Dispatch panel ----------------------------------------------------------------------------
const TABS = [{ id: 'calls', label: 'Calls' }, { id: 'week', label: 'This week' }, { id: 'all', label: 'All time' }];
async function showBoard(player, tab = 'calls') {
  const p = eg.players.get(player); if (!p) return;
  const wallet = await eg.players.pay(p, 0);                                     // team only (0: just read it)
  const menu = { id: 'board', title: `First Responder · $${wallet}`, tabs: TABS, tab, note: 'Any vehicle will do; the helicopter is quickest for Medevac and Search & Rescue.' };
  if (tab !== 'calls') {
    const rows = await eg.scores.top(tab === 'week' ? 'week' : 'all', 20);
    return eg.ui.menu(p, { ...menu, text: rows.length ? '' : 'No calls finished yet.', rows: rows.map(x => `${x.rank}. ${x.name}: ${x.score} pts · ${x.runs} calls`) });
  }
  const calls = await callsFor(p), busy = runs.has(p.id);
  eg.ui.menu(p, { ...menu, text: p.riders ? 'Co-pilot on board: +25 % on every call.' : 'A co-pilot riding with you adds 25 % to every call.',
    items: calls.map(c => ({ id: c.id, title: `[${c.badge}] ${c.title}`, detail: `${c.summary}${c.target ? ' · LIVE TARGET' : ''} · {km:${c.km.toFixed(2)}} · par {time:${c.parS}} · ${c.points} pts · $${c.cash}`, button: 'Respond', disabled: busy })) });
}
 
export default {
  onPlayerLeave(player) { const r = runs.get(player.id); if (r) endRun(r); },
  onZone(player, entityId, what) {
    const r = runs.get(player.id); if (what !== 'dwell' || !r || r.zone !== entityId) return;
    if (r.stage === 'scene' && r.call.dropoff) {
      r.stage = 'hospital'; setZone(r); show(r); guide(r);
      eg.ui.toast(player, `Patient on board: head to ${r.call.dropoff.name}`, 'good'); eg.audio.cue(player, 'ui.job_load');
      return;
    }
    return complete(player, r);
  },
  onUi(player, what) {
    if (what.id === 'siren') return siren(player);
    if (what.id === 'abandon') { const r = runs.get(player.id); if (r) voidRun(r, 'abandoned'); return; }
    if (what.from === 'menu' && what.id === 'board') return what.item ? accept(player, what.item) : showBoard(player, what.tab || 'calls');
    if (what.id === 'board') return showBoard(player);
  },
};

Racing

Street-circuit time trials with per-class par times, medals, start-line multiplayer heats, and track leaderboards.

advanced

Reference example in sdk/examples/racing/ (note: team-only badges/garage calls can be omitted in community games).

racing/server.js
js
// Racing: an official Earth Games example. Everything this game does, it does through the public
// API (`eg`). One call marked "team only" (a prize car in the garage) is for games made by the
// Earth Games team; the rest is a game anyone can make.
//
// How it plays: open the board (J, or F at a start beacon), pick a track, drive to its start and
// stop in the ring. The lights count down, and the platform times you through every gate
// (eg.race.offer): this script never sees a position and cannot be told a time by a player.
// What it decides is what a finish is worth:
//   - a best time per track and class of car (eg.scores.setBest), so a city car and a supercar
//     both have something to win;
//   - a medal against the track's targets for that class;
//   - points: for a track's first finish of the day, for a better time, and for a better medal
//     than before. The area's featured track of the week pays double;
//   - every first gold on a track and class counts toward the trophy cars.
// Line up with other players on the same start and you all go on the same lights.
//
// It works anywhere the map is built: tracks come from eg.race.tracksNear, wherever players are.
// To race on a course of your own instead, give eg.race.course your points and offer its id.
 
const POINTS = { finish: 40, pb: 20, bronze: 20, silver: 40, gold: 80, studio: 120 }, MAX_SCORED_PER_DAY = 40, BEACONS_MAX = 300;
const MEDALS = { studio: 1.1, gold: 1.22, silver: 1.4, bronze: 1.7 }, MEDAL_ORDER = ['studio', 'gold', 'silver', 'bronze'];
const MEDAL_NAME = { studio: '★ Studio time', gold: '🥇 Gold', silver: '🥈 Silver', bronze: '🥉 Bronze' };
const CLASS_NAMES = { D: 'Class D · Everyday', C: 'Class C · Street', B: 'Class B · Sport', A: 'Class A · Performance', S: 'Class S · Super', M: 'Bikes' };
const TROPHIES = [{ id: 'torrente', name: 'Torrente 83 Turbo', golds: 3 }, { id: 'aurelian', name: 'Aurelian 67', golds: 8 }, { id: 'halcyon', name: 'Halcyon 70', golds: 15 }];
const VOID = {
  teleport: 'Run void: you jumped ahead after the lights.', correct: 'Run void: the server lost track of your car.', fly: 'Run void: races are driven, not flown.',
  onfoot: 'Run void: you left your car.', swap: 'Run void: you changed cars mid-race.', fast: 'Run void: that sector was faster than your car can go.',
  expired: 'Race timed out.', cancelled: 'Race abandoned.',
};
const medalFor = (ms, par) => MEDAL_ORDER.find(m => ms <= Math.round(par * MEDALS[m])) || null;
const isGold = m => m === 'gold' || m === 'studio';
const boardOf = (track, cls) => `t:${track}:${cls}`;
/** 83456 → "1:23.46"; under a minute "23.46". */
function clock(ms) {
  if (ms == null) return '–';
  const cs = Math.round(Math.max(0, ms) / 10), m = Math.floor(cs / 6000), s = Math.floor(cs / 100) % 60, c = cs % 100;
  return m ? `${m}:${String(s).padStart(2, '0')}.${String(c).padStart(2, '0')}` : `${s}.${String(c).padStart(2, '0')}`;
}
const ordinal = n => `${n}${n % 100 >= 11 && n % 100 <= 13 ? 'th' : ['th', 'st', 'nd', 'rd'][n % 10] || 'th'}`;
const kindLine = t => `${t.kind === 'circuit' ? `Circuit · ${t.laps} laps` : 'Sprint'} · {km:${(t.lengthM / 1000).toFixed(2)}}`;
 
const known = new Map();   // track id → its summary (the tracks shown to someone lately)
const beacons = new Map(); // track id → the marker on its start
const picks = new Map();   // player id → the track they last picked
const dayUse = new Map();  // player id → { day, scored, tracks }
function remember(list) { for (const t of list) { known.delete(t.id); known.set(t.id, t); } while (known.size > 2000) known.delete(known.keys().next().value); }
 
// ---- start beacons: one on every track's start, where players are ----------------------------------
async function placeBeacons(center) {
  const list = await eg.race.tracksNear(center, { maxM: 2500, max: 24 });
  remember(list);
  for (const t of list) {
    if (beacons.has(t.id)) continue;
    beacons.set(t.id, eg.entities.add({ id: `t.${t.id}`, kind: 'marker', at: t.start, style: 'race', radar: true, label: `${t.name} · race start`, interact: { verb: `Race: ${t.name}`.slice(0, 40), reach: 14, modes: ['walk', 'drive'] } }));
    if (beacons.size > BEACONS_MAX) { const [old, id] = beacons.entries().next().value; beacons.delete(old); eg.entities.remove(id); }
  }
}
 
// ---- the board -------------------------------------------------------------------------------------
const TABS = [{ id: 'tracks', label: 'Tracks' }, { id: 'week', label: 'This week' }, { id: 'all', label: 'All time' }];
async function showBoard(player, tab = 'tracks') {
  const p = eg.players.get(player); if (!p) return;
  const menu = { id: 'board', title: 'Racing', tabs: TABS, tab, note: 'Stop in the ring on the start line and wait for the lights. Others who line up with you start with you.' };
  if (tab !== 'tracks') {
    const rows = await eg.scores.top(tab === 'week' ? 'week' : 'all', 20);
    return eg.ui.menu(p, { ...menu, text: rows.length ? '' : 'Nobody has scored yet.', rows: rows.map(x => `${x.rank}. ${x.name}: ${x.score} pts · ${x.runs} races`) });
  }
  const cls = p.car ? p.car.cls : 'C', list = await eg.race.tracksNear(p, { maxM: 6000, max: 12 });
  remember(list);
  const items = await Promise.all(list.map(async t => {
    const board = boardOf(t.id, cls), [mine, record] = await Promise.all([eg.scores.bestOf(p, board), eg.scores.record(board)]);
    return { id: t.id, title: `${t.featured ? '★ ' : ''}${t.name}`, to: t.start, button: 'Race',
      detail: `${kindLine(t)} · gold ${clock(t.par[cls] * MEDALS.gold)}${mine != null ? ` · your best ${clock(mine)}` : ''}${record != null ? ` · record ${clock(record)}` : ''}${t.featured ? ' · double points this week' : ''}` };
  }));
  eg.ui.menu(p, { ...menu, items, text: !items.length ? 'There are no tracks around here yet. Drive on: they appear wherever there are streets.' : p.car ? `Your car: ${CLASS_NAMES[cls]}` : 'Get in a car or on a bike to race.' });
}
async function pick(player, trackId) {
  const p = eg.players.get(player), t = known.get(String(trackId)); if (!p) return;
  if (!t) { eg.ui.toast(p, 'That track is not available here. Here are the tracks near you.', 'warn'); return showBoard(p); }
  if (!(await eg.players.startRun(p))) return;            // free players have a daily number of runs; the platform has told them
  const r = await eg.race.offer(p, t.id);
  if (!r.ok) return eg.ui.toast(p, r.why === 'racing' ? 'Finish or abandon your current race first.' : r.why === 'far' ? 'That start line is too far away. Open the board where you are.' : 'That track is not available right now.', 'warn');
  picks.set(p.id, t);
  const cls = p.car ? p.car.cls : 'C';
  eg.ui.menu(p, null); eg.ui.card(p, null); eg.audio.cue(p, 'ui.job_accept');
  eg.ui.waypoint(p, t.start, { hint: 'Stop in the ring and wait for the lights', hintM: 30 });
  eg.ui.hud(p, [
    { type: 'title', text: t.name },
    { type: 'distance', to: t.start, text: 'to the start line' },
    { type: 'text', text: `${kindLine(t)} · ${CLASS_NAMES[cls]} · gold ${clock(t.par[cls] * MEDALS.gold)}` },
    { type: 'button', id: 'route', label: 'Route', action: 'waypoint' },
    { type: 'button', id: 'abandon', label: 'Abandon' },
  ]);
}
 
// ---- what a finish is worth ------------------------------------------------------------------------
async function finished(player, e) {
  const medal = medalFor(e.ms, e.par), day = Math.floor(eg.world.now() / 864e5);
  const lines = [`${CLASS_NAMES[e.cls] || e.cls} · ${medal ? MEDAL_NAME[medal] : `bronze is ${clock(e.par * MEDALS.bronze)}`}${e.place ? ` · ${ordinal(e.place)} of ${e.of} in the heat` : ''}`];
  const buttons = [{ id: 'again', label: 'Race again' }, { id: 'board', label: 'Tracks' }, { id: 'close', label: 'Close', action: 'close' }];
  let points = 0, prize = '';
  if (player.guest) { lines.push('Sign in to keep your times and climb the boards.'); buttons.unshift({ id: 'signin', label: 'Sign in', action: 'signin' }); }
  else {
    const best = await eg.scores.setBest(player, boardOf(e.track, e.cls), e.ms, { meters: e.lengthM });
    if (best) {
      let use = dayUse.get(player.id); if (!use || use.day !== day) use = { day, scored: 0, tracks: new Set() };
      const wasMedal = best.before == null ? null : medalFor(best.before, e.par), better = medal && (!wasMedal || MEDAL_ORDER.indexOf(medal) < MEDAL_ORDER.indexOf(wasMedal));
      if (use.scored < MAX_SCORED_PER_DAY) {
        if (!use.tracks.has(e.track)) points += POINTS.finish;
        if (best.improved && best.before != null) points += POINTS.pb;
        if (better) points += POINTS[medal];
        if (e.featured) points *= 2;
      }
      use.tracks.add(e.track); if (points) use.scored++; dayUse.set(player.id, use);
      const totals = points ? await eg.scores.add(player, points, { meters: e.lengthM }) : null;
      lines.push(`${best.improved ? (best.before != null ? `New best, ${((best.before - e.ms) / 1000).toFixed(2)} s quicker` : 'Your first time here') : `Your best is ${clock(best.best)}`}${best.rank ? ` · ${ordinal(best.rank)} on this track` : ''}`);
      if (totals) lines.push(`+${points} pts${e.featured ? ' (featured track: double)' : ''} · This week ${totals.week} · All time ${totals.all}`);
      // The first gold on this track in this class: one more toward the trophy cars.
      if (isGold(medal) && !isGold(wasMedal)) {
        const golds = (await eg.scores.add(player, 1, { board: 'golds' }))?.all || 0;
        for (const car of TROPHIES) if (car.golds <= golds && await eg.players.grantCar(player, car.id)) { prize = car.name; break; }   // team only; one at a time
        const next = TROPHIES.find(c => c.golds > golds);
        lines.push(prize ? `🏆 ${golds} golds: the ${prize} is in your garage!` : next ? `${golds} of ${next.golds} golds toward the ${next.name}` : `${golds} golds`);
      }
    }
  }
  eg.players.finishRun(player);
  eg.ui.card(player, { title: `${e.name}: ${clock(e.ms)}`, lines, buttons, seconds: 30 });
  eg.ui.toast(player, `${clock(e.ms)}${medal ? ` · ${MEDAL_NAME[medal]}` : ''}${points ? ` · +${points} pts` : ''}${prize ? ` · 🏆 ${prize}` : ''}`, 'good');
}
 
export default {
  onPlayerArea(player, area) { return placeBeacons(area.center); },
  onPlayerLeave(player) { picks.delete(player.id); },
  onInteract(player, entityId) { if (entityId.startsWith('t.')) return pick(player, entityId.slice(2)); },
  onRace(player, e) {
    if (e.ev === 'start') { eg.ui.hud(player, null); eg.ui.waypoint(player, null); return; } // the race view takes over the screen
    if (e.ev === 'finish') return finished(player, e);
    if (e.ev !== 'void') return;
    eg.ui.hud(player, null); eg.ui.waypoint(player, null);
    const text = VOID[e.reason] || 'Race cancelled.';
    eg.ui.card(player, { title: text, buttons: [{ id: 'again', label: 'Try again' }, { id: 'board', label: 'Tracks' }, { id: 'close', label: 'Close', action: 'close' }], seconds: 12 });
    eg.ui.toast(player, text, e.reason === 'cancelled' ? 'info' : 'warn');
  },
  onUi(player, what) {
    if (what.id === 'abandon') return eg.race.cancel(player);
    if (what.id === 'again') { const t = picks.get(player.id); return t ? pick(player, t.id) : showBoard(player); }
    if (what.from === 'menu' && what.id === 'board') return what.item ? pick(player, what.item) : showBoard(player, what.tab || 'tracks');
    if (what.id === 'board') return showBoard(player);
  },
};