1// The rules of your game. This file runs on Earth Games' servers, once for each running copy of2// the game. It reacts to events (a player joined, entered a zone, pressed a button) and calls3// `eg` to change the world and what players see. The full list: docs/api.md, or hover in your editor.4//5// This starter puts a flag 60 metres north of wherever each player starts and counts who reaches it.6// Nothing in it is a fixed coordinate, so it plays anywhere on Earth.7//8// Text players see goes through eg.t('โฆ'): it reaches each player in their own language once the game9// has translations (your own in lang/<code>.json, see docs/guide.md "Translating your game").10const found = newMap(); // player id โ flags reached1112functionhud(player) {13eg.ui.hud(player, [14 { type: 'title', text: eg.t('My Game') },15 { type: 'counter', text: eg.t('Flags'), value: found.get(player.id) || 0 },16 ]);17}18functionplaceFlag(player) {19const at = eg.world.offset(player, 0, -60); // 60 m north of them20eg.entities.add({ id: `flag-${player.id}`, kind: 'zone', at, radius: 6, label: eg.t('Flag'), style: 'default', radar: true, visibleTo: player, trigger: {} });21eg.ui.waypoint(player, at, { hint: eg.t('Walk into the ring') });22}2324exportdefault {25onStart() {26 console.log('The game started.'); // shows in "earthgames dev" and in the in-game console (only you see it: no eg.t)27 },28onPlayerJoin(player) {29 found.set(player.id, 0);30eg.ui.toast(player, eg.t('Find the flag, {name}.', { name: player }), 'info');31hud(player);32placeFlag(player);33 },34onZone(player, entityId, what) {35if (what !== 'enter' || entityId !== `flag-${player.id}`) return;36const n = (found.get(player.id) || 0) + 1;37 found.set(player.id, n);38eg.audio.cue(player, 'ui.job_deliver');39eg.ui.toast(player, eg.t('{n, plural, one {Your first flag.} other {That makes # flags.}} Here is another.', { n }), 'good');40hud(player);41placeFlag(player); // the same id again moves the flag42 },43onPlayerLeave(player) {44 found.delete(player.id);45 },46};
blank/game.json
json
1{2"id": "my-game",3"title": "My Game",4"summary": "Say in a sentence or two what players do in your game.",5"version": "0.1.0",6"api": 1,7"instance": { "kind": "match", "maxPlayers": 8 },8"area": { "anywhere": true },9"content": { "violence": "none" }10}
Pursuit
Rule-based spawners keep chasers 50โ120 m around players on any street without a single hardcoded coordinate.
1// Pursuit: an official Earth Games example of a private game that plays anywhere.2// A pack of chasers keeps appearing around the players, out of sight, and runs at them. Every hit3// counts against you; the HUD shows how long you have lasted and how often you were caught.4// Nothing here is tied to a place: the spawner is a rule ("on open ground, 50 to 120 m from any5// player"), so the game is the same in a city centre or a field.6// Every text players see is marked with eg.t, and lang/fr.json has it in French: a player who7// chose French gets "Ils arrivent. Ne vous arrรชtez pas." where everyone else reads the English.8const caught = newMap(); // player id โ times caught9let startedAt = 0;1011functionhud(player) {12eg.ui.hud(player, [13 { type: 'title', text: eg.t('Pursuit') },14 { type: 'timer', since: startedAt, text: eg.t('on the run') },15 { type: 'counter', text: eg.t('Caught'), value: caught.get(player.id) || 0 },16 ]);17}1819exportdefault {20onStart() {21 startedAt = eg.world.now();22eg.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 } }]);23eg.spawners.add({ id: 'pack', kind: 'chaser', capNear: 10, capTotal: 40, perSecond: 1, where: { minFromPlayersM: 50, maxFromPlayersM: 120 } });24 },25onPlayerJoin(player) {26 caught.set(player.id, caught.get(player.id) || 0);27eg.ui.toast(player, eg.t('They are coming. Keep moving.'), 'warn');28hud(player);29 },30onPlayerLeave(player) { caught.delete(player.id); },31onNpc(event) {32if (event.ev !== 'attack' || !event.player) return;33const n = (caught.get(event.player.id) || 0) + 1;34 caught.set(event.player.id, n);35if (n % 5 === 0) eg.ui.toast(event.player, eg.t('{n, plural, one {Caught # time.} other {Caught # times.}} Keep going.', { n }), 'warn');36hud(event.player);37 },38};
pursuit/game.json
json
1{2"id": "pursuit",3"title": "Pursuit",4"summary": "A pack is after you, wherever you are. Keep moving and see how long you can go without being caught. A small example of a private game that plays anywhere.",5"version": "1.0.0",6"api": 1,7"instance": { "kind": "match", "maxPlayers": 8 },8"area": { "anywhere": true },9"content": { "violence": "mild" },10"world": { "traffic": 0, "pedestrians": 0 }11}
Horde
Wave survival with escalating enemy classes, custom medkit actions, weapon unlocks, explosions, and leaderboards.
1// Horde: an official Earth Games example of combat in a private game that plays anywhere.2// Waves of attackers appear around the players, out of sight, and run in. Clear a wave and the3// next one is bigger; every few waves a new kind joins and everyone is handed a better weapon.4// When every player is down at the same time the run is over: it is scored and starts again.5//6// What it shows:7// eg.combat health, respawns and weapons are the platform's; this script only sets the rules8// eg.inventory weapons and rounds, plus an item of the game's own (medkits, used with H)9// eg.spawners rule-placed ("40 to 90 m from any player"), so there is not one coordinate here10// eg.fx a blast when a brute goes down11// onNpc counts kills from 'died', and keeps each wave's numbers honest12const KINDS = [13 { 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 } },14 { 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 } },15 { 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 } },16];17const START = { pistol: 60, bat: 1, medkit: 2 };18const BREAK_S = 8, OVER_S = 12;19/** How many of each kind wave n holds, for this many players. */20functionwaveOf(n, players) {21const k = 1 + .6 * (Math.max(1, players) - 1);22return { 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 };23}2425let wave = 0, phase = 'wait'; // wait (nobody here) | fight | break | over26let left = { walker: 0, runner: 0, brute: 0 }; // still to appear this wave27const alive = newMap(); // character id โ kind28const kills = newMap(); // player id โ kills this run29let dirty = false, timer = 0;3031const remaining = () => alive.size + left.walker + left.runner + left.brute;32functionhud(player) {33eg.ui.hud(player, [34 { type: 'title', text: phase === 'break' ? `Wave ${wave} cleared` : phase === 'over' ? 'Overrun' : `Wave ${wave}` },35 { type: 'counter', text: 'Left', value: phase === 'fight' ? remaining() : 0 },36 { type: 'counter', text: 'Kills', value: kills.get(player.id) || 0 },37 ]);38}39const hudAll = () => { for (const p ofeg.players.all()) hud(p); };4041functionstartWave() {42 wave++; phase = 'fight';43 left = waveOf(wave, eg.players.count());44for (const k of KINDS) eg.spawners.enable(k.id, left[k.id] > 0);45eg.ui.toast(null, wave === 1 ? 'They are coming. Left mouse fires, Q changes weapon, H uses a medkit.' : `Wave ${wave}.`, 'warn');46hudAll();47}48functionendWave() {49 phase = 'break';50for (const p ofeg.players.all()) {51eg.combat.heal(p, 40); eg.inventory.give(p, 'pistol', 30);52if (wave === 2) { eg.inventory.give(p, 'shotgun', 18); eg.ui.toast(p, 'Shotgun. Q changes weapon.', 'good'); }53if (wave === 4) { eg.inventory.give(p, 'smg', 120); eg.ui.toast(p, 'SMG. Q changes weapon.', 'good'); }54if (wave > 4) { eg.inventory.give(p, 'shotgun', 12); eg.inventory.give(p, 'smg', 60); }55if (wave % 3 === 0) eg.inventory.give(p, 'medkit', 1);56 }57eg.audio.cue(null, 'ui.job_deliver');58hudAll();59 timer = eg.timers.after(BREAK_S, startWave);60}61functionstop() {62eg.timers.cancel(timer);63for (const k of KINDS) eg.spawners.enable(k.id, false);64eg.npcs.clear(); alive.clear(); left = { walker: 0, runner: 0, brute: 0 };65}66functiongameOver() {67 phase = 'over'; stop();68for (const p ofeg.players.all()) {69const mine = kills.get(p.id) || 0;70eg.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' }] });71if (!p.guest && wave > 1) eg.scores.add(p, (wave - 1) * 100 + mine * 10);72 }73hudAll();74 timer = eg.timers.after(OVER_S, () => {75 wave = 0; kills.clear();76for (const p ofeg.players.all()) { eg.combat.respawn(p); eg.inventory.setLoadout(p, START); }77startWave();78 });79}8081exportdefault {82onStart() {83eg.npcs.kinds(KINDS);84eg.combat.enable({ health: 100, respawnS: 10, loadout: START });85for (const k of KINDS) {86eg.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 } });87eg.spawners.enable(k.id, false);88 }89eg.timers.every(.5, () => { if (dirty) { dirty = false; hudAll(); } });90 },91onPlayerJoin(player) {92 kills.set(player.id, kills.get(player.id) || 0);93hud(player);94if (phase === 'wait') { phase = 'break'; eg.ui.toast(player, 'Get ready.', 'info'); timer = eg.timers.after(4, startWave); }95 },96onPlayerLeave(player) {97 kills.delete(player.id);98if (eg.players.count() === 0) { stop(); wave = 0; phase = 'wait'; }99 },100onPlayerDied(player) {101if (phase !== 'fight') return;102if (eg.players.all().every(p => p.dead || p.id === player.id)) gameOver();103elseeg.ui.toast(null, `${player.name} is down.`, 'warn');104 },105asynconUi(player, what) {106if (what.from !== 'action' || what.id !== 'medkit') return;107const me = eg.players.get(player);108if (!me || me.dead) return;109const inv = awaiteg.inventory.get(player);110if (!(inv.medkit > 0)) returneg.ui.toast(player, 'No medkits left.', 'warn');111eg.inventory.take(player, 'medkit', 1); eg.combat.heal(player, 50);112eg.fx.flash(player, { color: 'green' });113eg.ui.toast(player, `Medkit used. ${inv.medkit - 1} left.`, 'good');114 },115onNpc(event) {116if (event.ev === 'spawned') {117 alive.set(event.id, event.kind);118if (phase !== 'fight') returneg.npcs.despawn(event.id); // one that appeared just as the wave ended119if (--left[event.kind] <= 0) eg.spawners.enable(event.kind, false);120 } elseif (event.ev === 'died') {121if (!alive.delete(event.id)) return;122if (event.player) kills.set(event.player.id, (kills.get(event.player.id) || 0) + 1);123if (event.kind === 'brute') eg.fx.explosion({ lat: event.lat, lon: event.lon }, { size: .5 });124if (phase === 'fight' && remaining() <= 0) returnendWave();125 } elseif (event.ev === 'gone') {126// Left far behind and removed while still alive: it goes back on the wave's list.127const kind = alive.get(event.id); if (!kind || !alive.delete(event.id) || phase !== 'fight') return;128 left[kind]++; eg.spawners.enable(kind, true);129 } elsereturn;130 dirty = true;131 },132};
horde/game.json
json
1{2"id": "horde",3"title": "Horde",4"summary": "Hold out against wave after wave, wherever you are standing. Every wave is bigger and meaner; bring friends. An example of combat, inventories and effects in a game that plays anywhere.",5"version": "1.0.0",6"api": 1,7"instance": { "kind": "match", "maxPlayers": 8 },8"area": { "anywhere": true },9"content": { "violence": "strong", "blood": true, "notice": "You fight crowds of attackers with guns and a bat." },10"world": { "traffic": 0, "pedestrians": 0 },11"actions": [{ "id": "medkit", "label": "Use a medkit", "key": "KeyH" }]12}
First Responder
Emergency dispatch built from real hospitals, police stations, and streets around players, with signal hunting and sirens.
Reference example in sdk/examples/responder/ (note: team-only badges/garage calls can be omitted in community games).
responder/server.js
js
1// First Responder: an official Earth Games example. Everything this game does, it does through the2// public API (`eg`). Three calls marked "team only" below are for games made by the Earth Games3// team (cash, badges, and players wanted in another of our games); leave them out and the rest is4// a game anyone can make.5//6// How it plays: open Dispatch (J), take a call, get to the flare and stop (or hover) inside it.7// Medevac pick the patient up at the scene, then set down at the nearest real hospital8// Search & Rescue the beacon is somewhere in the search circle: follow the signal bar to it9// Street emergency get to the scene fast10// Interceptor catch up with a reckless driver (or, team only, a player the police are after)11// Beating the par time pays 20 % more; so does a co-pilot riding with you (25 %). Y is the siren.12//13// It works anywhere the map is built: every call is made from real hospitals, police stations and14// named streets around whoever is playing (eg.world.placesNear), never from fixed coordinates.1516const CALL_LIMIT_S = 8 * 60, ACCEPT_MAX_M = 8000, CREW_MULT = 1.25, ON_TIME_MULT = 1.2;17const 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;18const km = (a, b) => eg.world.distance(a, b) / 1000;19/** The point `m` metres from another, along a bearing (0 north, ฯ/2 east). */20const along = (from, m, bearing) => eg.world.offset(from, Math.sin(bearing) * m, -Math.cos(bearing) * m);21functionangleOf(seed) { // the same angle for the same text: a player's calls do not jump about within a minute22let h = 2166136261;23for (let i = 0; i < seed.length; i++) h = Math.imul(h ^ seed.charCodeAt(i), 16777619);24return ((h >>> 0) % 360) * Math.PI / 180;25}26functionnearest(list, from, minM, maxM) {27let best = null, bd = Infinity;28for (const s of list) { const d = eg.world.distance(from, s); if (d >= minM && d <= maxM && d < bd) { bd = d; best = s; } }29return best;30}31/** 0 to 1: how strong the beacon's signal is from here. */32const signal = (at, beacon) => Math.max(0, Math.min(1, 1 - eg.world.distance(at, beacon) / ELT_RANGE_M));3334// ---- the calls on offer: four around each player, new every minute ---------------------------------35const offers = newMap(); // offer id โ call (the last few hundred shown)36asyncfunctioncallsFor(p) {37const minute = Math.floor(eg.world.now() / 60000), base = angleOf(`${p.id}:${minute}`), here = { lat: p.lat, lon: p.lon };38const [places, wanted] = await Promise.all([39eg.world.placesNear(here, { maxM: 6000, kinds: ['hospital', 'police', 'street'], max: 64 }),40eg.players.wanted(here, WANTED_M), // team only41 ]);42constof = kind => places.filter(s => s.kind === kind);43const hospital = nearest(of('hospital'), here, 250, 6000) || { ...along(here, 1350, base + 2.4), name: 'Regional Trauma Center' };44const medScene = nearest([...of('street'), ...of('police')], here, 500, 2600) || { ...along(here, 1100, base + .5), name: 'Highway Milepost Incident' };45const sarScene = { ...along(here, 1450, base + 1.8), name: 'Downed ELT Transponder' };46const street = nearest([...of('police'), ...of('street')], here, 280, 1800) || { ...along(here, 760, base + 4.5), name: 'Box-Alarm Intersection Call' };47const outlaw = wanted[0] || null;48const 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' };49const medKm = km(here, medScene) + km(medScene, hospital), sarKm = km(here, sarScene), stKm = km(here, street), chKm = km(here, chase);50const id = tag => `${tag}.${p.id}.${minute.toString(36)}`, at = s => ({ lat: s.lat, lon: s.lon, name: s.name });51const calls = [52 { 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}`,53 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) },54 { 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',55 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) },56 { 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}`,57 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) },58 { 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',59 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 },60 ];61for (const c of calls) { offers.delete(c.id); offers.set(c.id, c); }62while (offers.size > 400) offers.delete(offers.keys().next().value);63return calls;64}6566// ---- a call in progress ----------------------------------------------------------------------------67const runs = newMap(); // player id โ the call they are on68let runN = 0;69const REASONS = { abandoned: 'Dispatch cancelled.', expired: 'The call timed out.', left: 'The call closed when you left First Responder.' };70const searching = r => r.call.kind === 'sar' && r.stage === 'scene';71const target = r => (r.stage === 'hospital' ? r.call.dropoff : r.call.scene);7273functionshow(r) {74const p = eg.players.get(r.id); if (!p) return;75const c = r.call, t = target(r), toHospital = r.stage === 'hospital';76eg.ui.hud(p, [77 { type: 'title', text: `[${toHospital ? 'TRANSPORT' : c.badge}] ${toHospital ? `Deliver the patient to ${c.dropoff.name}` : c.label}` },78 { type: 'distance', to: searching(r) ? c.search : t },79 { type: 'timer', since: r.acceptedAt, par: c.parS },80 ...(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' : ''}` }] : []),81 ...(p.riders ? [{ type: 'text', text: 'Co-pilot on board: +25 %' }] : []),82 { type: 'button', id: 'siren', label: r.siren ? 'Siren on' : 'Siren' },83 { type: 'button', id: 'route', label: 'Route', action: 'waypoint' },84 { type: 'button', id: 'board', label: 'Dispatch' },85 { type: 'button', id: 'abandon', label: 'Abandon' },86 ]);87}88functionguide(r) {89const 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';90eg.ui.waypoint(r.id, searching(r) ? r.call.search : target(r), { hint, hintM: searching(r) ? SAR_SEARCH_R : ZONE_R });91}92functionsetZone(r) {93for (const id of [r.zone, r.ring]) if (id) eg.entities.remove(id);94const t = target(r), sar = searching(r);95// The beacon itself is not on the radar: the signal bar is how you find it. The search circle is.96 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;97 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,98 label: r.stage === 'hospital' ? `Drop-off: ${t.name}` : t.name, trigger: { dwellS: sar ? .9 : 1.5, maxSpeed: STOP_SPEED } });99}100functionendRun(r) {101for (const id of [r.zone, r.ring]) if (id) eg.entities.remove(id);102eg.timers.cancel(r.clock); eg.timers.cancel(r.limit);103if (runs.get(r.id) === r) runs.delete(r.id);104if (r.siren) eg.vehicles.siren(r.id, false);105eg.players.setBusy(r.id, false); eg.ui.hud(r.id, null); eg.ui.waypoint(r.id, null);106}107functionvoidRun(r, reason) {108endRun(r);109const text = REASONS[reason] || 'Dispatch ended.';110eg.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 });111eg.ui.toast(r.id, text, reason === 'abandoned' ? 'info' : 'warn');112eg.audio.cue(r.id, 'ui.job_fail');113}114/** Once a second while a call runs: the beacon's signal, and where a live suspect has got to. */115asyncfunctionwatch(r) {116const p = eg.players.get(r.id); if (!p || runs.get(r.id) !== r) return;117if (searching(r)) { const s = signal(p, r.call.scene); if (Math.abs(s - r.signal) >= .03) { r.signal = s; show(r); } }118if (r.call.target && ++r.ticks % 2 === 0) {119const now = (awaiteg.players.wanted(r.call.scene, 6000)).find(w => w.id === r.call.target); // team only120if (now && runs.get(r.id) === r && eg.world.distance(now, r.call.scene) > 25) {121 r.call.scene.lat = now.lat; r.call.scene.lon = now.lon;122eg.entities.update(r.zone, { at: r.call.scene }); guide(r); show(r);123 }124 }125}126asyncfunctioncomplete(player, r) {127endRun(r);128const c = r.call, seconds = Math.max(1, Math.round((eg.world.now() - r.acceptedAt) / 1000)), onTime = seconds <= c.parS, crew = (player.riders || 0) > 0;129const mult = (onTime ? ON_TIME_MULT : 1) * (crew ? CREW_MULT : 1), points = Math.round(c.points * mult), cash = Math.round(c.cash * mult);130const wallet = awaiteg.players.pay(player, cash); // team only131const lines = [`{time:${seconds}} (par {time:${c.parS}}${onTime ? ', +20 % on time' : ''})${crew ? ' ยท +25 % co-pilot' : ''} ยท Wallet $${wallet}`];132const buttons = [{ id: 'board', label: 'Next call' }, { id: 'close', label: 'Close', action: 'close' }];133let badge = '';134if (player.guest) { lines.push('Sign in to keep your points and climb the leaderboard.'); buttons.unshift({ id: 'signin', label: 'Sign in', action: 'signin' }); }135else {136const totals = awaiteg.scores.add(player, points, { meters: Math.round(c.km * 1000) });137if (totals) {138if (awaiteg.players.award(player, { id: 'responder:first', label: 'First Responder' })) badge = ' ยท ๐ First Responder'; // team only139 lines.push(`This week ${totals.week} ยท All time ${totals.all} pts ยท ${totals.runs} calls${badge}`);140 }141 }142eg.players.finishRun(player);143eg.ui.card(player, { title: `${c.title} complete: +${points} pts ยท +$${cash}`, lines, buttons, seconds: 12 });144eg.ui.toast(player, `Call complete! +${points} pts ยท +$${cash}${crew ? ' (co-pilot +25 %)' : ''}${badge}`, 'good');145eg.audio.cue(player, 'ui.job_deliver');146}147asyncfunctionaccept(player, offerId) {148if (runs.has(player.id)) returneg.ui.toast(player, 'Finish or abandon your active call first.', 'warn');149const offer = offers.get(String(offerId));150if (!offer) { eg.ui.toast(player, 'That call has gone. Here are the calls now.', 'warn'); returnshowBoard(player); }151let p = eg.players.get(player); if (!p) return;152if (eg.world.distance(p, offer.scene) > ACCEPT_MAX_M) returneg.ui.toast(player, 'That call is too far away.', 'warn');153if (!(awaiteg.players.startRun(player))) return; // free players have a daily number of runs; the platform has told them154 p = eg.players.get(player); if (!p || runs.has(p.id)) return;155const now = eg.world.now();156const 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 };157 r.signal = searching(r) ? signal(p, r.call.scene) : 0;158 runs.set(r.id, r);159 r.clock = eg.timers.every(1, () => watch(r));160 r.limit = eg.timers.after(CALL_LIMIT_S, () => { if (runs.get(r.id) === r) voidRun(r, 'expired'); });161eg.players.setBusy(p, true); setZone(r);162eg.ui.menu(p, null); eg.audio.cue(p, 'ui.job_accept'); show(r); guide(r);163}164functionsiren(player) {165const r = runs.get(player.id);166if (!r) returneg.ui.toast(player, 'The siren is for calls: take one from Dispatch (J).', 'info');167 r.siren = !r.siren; eg.vehicles.siren(player, r.siren); show(r);168}169170// ---- the Dispatch panel ----------------------------------------------------------------------------171const TABS = [{ id: 'calls', label: 'Calls' }, { id: 'week', label: 'This week' }, { id: 'all', label: 'All time' }];172asyncfunctionshowBoard(player, tab = 'calls') {173const p = eg.players.get(player); if (!p) return;174const wallet = awaiteg.players.pay(p, 0); // team only (0: just read it)175const menu = { id: 'board', title: `First Responder ยท $${wallet}`, tabs: TABS, tab, note: 'Any vehicle will do; the helicopter is quickest for Medevac and Search & Rescue.' };176if (tab !== 'calls') {177const rows = awaiteg.scores.top(tab === 'week' ? 'week' : 'all', 20);178returneg.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`) });179 }180const calls = awaitcallsFor(p), busy = runs.has(p.id);181eg.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.',182 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 })) });183}184185exportdefault {186onPlayerLeave(player) { const r = runs.get(player.id); if (r) endRun(r); },187onZone(player, entityId, what) {188const r = runs.get(player.id); if (what !== 'dwell' || !r || r.zone !== entityId) return;189if (r.stage === 'scene' && r.call.dropoff) {190 r.stage = 'hospital'; setZone(r); show(r); guide(r);191eg.ui.toast(player, `Patient on board: head to ${r.call.dropoff.name}`, 'good'); eg.audio.cue(player, 'ui.job_load');192return;193 }194returncomplete(player, r);195 },196onUi(player, what) {197if (what.id === 'siren') returnsiren(player);198if (what.id === 'abandon') { const r = runs.get(player.id); if (r) voidRun(r, 'abandoned'); return; }199if (what.from === 'menu' && what.id === 'board') return what.item ? accept(player, what.item) : showBoard(player, what.tab || 'calls');200if (what.id === 'board') returnshowBoard(player);201 },202};
responder/game.json
json
1{2"id": "responder",3"title": "First Responder",4"summary": "Answer emergency calls anywhere on the map: fly or drive a patient to the nearest hospital, hunt down a rescue beacon by its signal, or race to a street emergency. Bring a co-pilot for a bonus.",5"version": "1.0.0",6"api": 1,7"instance": { "kind": "world" },8"area": { "built": true },9"world": { "traffic": 1, "pedestrians": 1 },10"actions": [11 { "id": "board", "label": "Dispatch", "key": "panel" },12 { "id": "siren", "label": "Siren", "key": "KeyY" }13 ],14"capabilities": ["badges"]15}
Racing
Street-circuit time trials with per-class par times, medals, start-line multiplayer heats, and track leaderboards.
Reference example in sdk/examples/racing/ (note: team-only badges/garage calls can be omitted in community games).
racing/server.js
js
1// Racing: an official Earth Games example. Everything this game does, it does through the public2// API (`eg`). One call marked "team only" (a prize car in the garage) is for games made by the3// Earth Games team; the rest is a game anyone can make.4//5// How it plays: open the board (J, or F at a start beacon), pick a track, drive to its start and6// stop in the ring. The lights count down, and the platform times you through every gate7// (eg.race.offer): this script never sees a position and cannot be told a time by a player.8// What it decides is what a finish is worth:9// - a best time per track and class of car (eg.scores.setBest), so a city car and a supercar10// both have something to win;11// - a medal against the track's targets for that class;12// - points: for a track's first finish of the day, for a better time, and for a better medal13// than before. The area's featured track of the week pays double;14// - every first gold on a track and class counts toward the trophy cars.15// Line up with other players on the same start and you all go on the same lights.16//17// It works anywhere the map is built: tracks come from eg.race.tracksNear, wherever players are.18// To race on a course of your own instead, give eg.race.course your points and offer its id.1920const POINTS = { finish: 40, pb: 20, bronze: 20, silver: 40, gold: 80, studio: 120 }, MAX_SCORED_PER_DAY = 40, BEACONS_MAX = 300;21const MEDALS = { studio: 1.1, gold: 1.22, silver: 1.4, bronze: 1.7 }, MEDAL_ORDER = ['studio', 'gold', 'silver', 'bronze'];22const MEDAL_NAME = { studio: 'โ Studio time', gold: '๐ฅ Gold', silver: '๐ฅ Silver', bronze: '๐ฅ Bronze' };23const CLASS_NAMES = { D: 'Class D ยท Everyday', C: 'Class C ยท Street', B: 'Class B ยท Sport', A: 'Class A ยท Performance', S: 'Class S ยท Super', M: 'Bikes' };24const TROPHIES = [{ id: 'torrente', name: 'Torrente 83 Turbo', golds: 3 }, { id: 'aurelian', name: 'Aurelian 67', golds: 8 }, { id: 'halcyon', name: 'Halcyon 70', golds: 15 }];25const VOID = {26 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.',27 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.',28 expired: 'Race timed out.', cancelled: 'Race abandoned.',29};30const medalFor = (ms, par) => MEDAL_ORDER.find(m => ms <= Math.round(par * MEDALS[m])) || null;31const isGold = m => m === 'gold' || m === 'studio';32const boardOf = (track, cls) => `t:${track}:${cls}`;33/** 83456 โ "1:23.46"; under a minute "23.46". */34functionclock(ms) {35if (ms == null) return'โ';36const cs = Math.round(Math.max(0, ms) / 10), m = Math.floor(cs / 6000), s = Math.floor(cs / 100) % 60, c = cs % 100;37return m ? `${m}:${String(s).padStart(2, '0')}.${String(c).padStart(2, '0')}` : `${s}.${String(c).padStart(2, '0')}`;38}39const ordinal = n => `${n}${n % 100 >= 11 && n % 100 <= 13 ? 'th' : ['th', 'st', 'nd', 'rd'][n % 10] || 'th'}`;40const kindLine = t => `${t.kind === 'circuit' ? `Circuit ยท ${t.laps} laps` : 'Sprint'} ยท {km:${(t.lengthM / 1000).toFixed(2)}}`;4142const known = newMap(); // track id โ its summary (the tracks shown to someone lately)43const beacons = newMap(); // track id โ the marker on its start44const picks = newMap(); // player id โ the track they last picked45const dayUse = newMap(); // player id โ { day, scored, tracks }46functionremember(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); }4748// ---- start beacons: one on every track's start, where players are ----------------------------------49asyncfunctionplaceBeacons(center) {50const list = awaiteg.race.tracksNear(center, { maxM: 2500, max: 24 });51remember(list);52for (const t of list) {53if (beacons.has(t.id)) continue;54 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'] } }));55if (beacons.size > BEACONS_MAX) { const [old, id] = beacons.entries().next().value; beacons.delete(old); eg.entities.remove(id); }56 }57}5859// ---- the board -------------------------------------------------------------------------------------60const TABS = [{ id: 'tracks', label: 'Tracks' }, { id: 'week', label: 'This week' }, { id: 'all', label: 'All time' }];61asyncfunctionshowBoard(player, tab = 'tracks') {62const p = eg.players.get(player); if (!p) return;63const 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.' };64if (tab !== 'tracks') {65const rows = awaiteg.scores.top(tab === 'week' ? 'week' : 'all', 20);66returneg.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`) });67 }68const cls = p.car ? p.car.cls : 'C', list = awaiteg.race.tracksNear(p, { maxM: 6000, max: 12 });69remember(list);70const items = await Promise.all(list.map(async t => {71const board = boardOf(t.id, cls), [mine, record] = await Promise.all([eg.scores.bestOf(p, board), eg.scores.record(board)]);72return { id: t.id, title: `${t.featured ? 'โ ' : ''}${t.name}`, to: t.start, button: 'Race',73 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' : ''}` };74 }));75eg.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.' });76}77asyncfunctionpick(player, trackId) {78const p = eg.players.get(player), t = known.get(String(trackId)); if (!p) return;79if (!t) { eg.ui.toast(p, 'That track is not available here. Here are the tracks near you.', 'warn'); returnshowBoard(p); }80if (!(awaiteg.players.startRun(p))) return; // free players have a daily number of runs; the platform has told them81const r = awaiteg.race.offer(p, t.id);82if (!r.ok) returneg.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');83 picks.set(p.id, t);84const cls = p.car ? p.car.cls : 'C';85eg.ui.menu(p, null); eg.ui.card(p, null); eg.audio.cue(p, 'ui.job_accept');86eg.ui.waypoint(p, t.start, { hint: 'Stop in the ring and wait for the lights', hintM: 30 });87eg.ui.hud(p, [88 { type: 'title', text: t.name },89 { type: 'distance', to: t.start, text: 'to the start line' },90 { type: 'text', text: `${kindLine(t)} ยท ${CLASS_NAMES[cls]} ยท gold ${clock(t.par[cls] * MEDALS.gold)}` },91 { type: 'button', id: 'route', label: 'Route', action: 'waypoint' },92 { type: 'button', id: 'abandon', label: 'Abandon' },93 ]);94}9596// ---- what a finish is worth ------------------------------------------------------------------------97asyncfunctionfinished(player, e) {98const medal = medalFor(e.ms, e.par), day = Math.floor(eg.world.now() / 864e5);99const 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` : ''}`];100const buttons = [{ id: 'again', label: 'Race again' }, { id: 'board', label: 'Tracks' }, { id: 'close', label: 'Close', action: 'close' }];101let points = 0, prize = '';102if (player.guest) { lines.push('Sign in to keep your times and climb the boards.'); buttons.unshift({ id: 'signin', label: 'Sign in', action: 'signin' }); }103else {104const best = awaiteg.scores.setBest(player, boardOf(e.track, e.cls), e.ms, { meters: e.lengthM });105if (best) {106let use = dayUse.get(player.id); if (!use || use.day !== day) use = { day, scored: 0, tracks: newSet() };107const wasMedal = best.before == null ? null : medalFor(best.before, e.par), better = medal && (!wasMedal || MEDAL_ORDER.indexOf(medal) < MEDAL_ORDER.indexOf(wasMedal));108if (use.scored < MAX_SCORED_PER_DAY) {109if (!use.tracks.has(e.track)) points += POINTS.finish;110if (best.improved && best.before != null) points += POINTS.pb;111if (better) points += POINTS[medal];112if (e.featured) points *= 2;113 }114 use.tracks.add(e.track); if (points) use.scored++; dayUse.set(player.id, use);115const totals = points ? awaiteg.scores.add(player, points, { meters: e.lengthM }) : null;116 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` : ''}`);117if (totals) lines.push(`+${points} pts${e.featured ? ' (featured track: double)' : ''} ยท This week ${totals.week} ยท All time ${totals.all}`);118// The first gold on this track in this class: one more toward the trophy cars.119if (isGold(medal) && !isGold(wasMedal)) {120const golds = (awaiteg.scores.add(player, 1, { board: 'golds' }))?.all || 0;121for (const car of TROPHIES) if (car.golds <= golds && awaiteg.players.grantCar(player, car.id)) { prize = car.name; break; } // team only; one at a time122const next = TROPHIES.find(c => c.golds > golds);123 lines.push(prize ? `๐ ${golds} golds: the ${prize} is in your garage!` : next ? `${golds} of ${next.golds} golds toward the ${next.name}` : `${golds} golds`);124 }125 }126 }127eg.players.finishRun(player);128eg.ui.card(player, { title: `${e.name}: ${clock(e.ms)}`, lines, buttons, seconds: 30 });129eg.ui.toast(player, `${clock(e.ms)}${medal ? ` ยท ${MEDAL_NAME[medal]}` : ''}${points ? ` ยท +${points} pts` : ''}${prize ? ` ยท ๐ ${prize}` : ''}`, 'good');130}131132exportdefault {133onPlayerArea(player, area) { returnplaceBeacons(area.center); },134onPlayerLeave(player) { picks.delete(player.id); },135onInteract(player, entityId) { if (entityId.startsWith('t.')) returnpick(player, entityId.slice(2)); },136onRace(player, e) {137if (e.ev === 'start') { eg.ui.hud(player, null); eg.ui.waypoint(player, null); return; } // the race view takes over the screen138if (e.ev === 'finish') returnfinished(player, e);139if (e.ev !== 'void') return;140eg.ui.hud(player, null); eg.ui.waypoint(player, null);141const text = VOID[e.reason] || 'Race cancelled.';142eg.ui.card(player, { title: text, buttons: [{ id: 'again', label: 'Try again' }, { id: 'board', label: 'Tracks' }, { id: 'close', label: 'Close', action: 'close' }], seconds: 12 });143eg.ui.toast(player, text, e.reason === 'cancelled' ? 'info' : 'warn');144 },145onUi(player, what) {146if (what.id === 'abandon') returneg.race.cancel(player);147if (what.id === 'again') { const t = picks.get(player.id); return t ? pick(player, t.id) : showBoard(player); }148if (what.from === 'menu' && what.id === 'board') return what.item ? pick(player, what.item) : showBoard(player, what.tab || 'tracks');149if (what.id === 'board') returnshowBoard(player);150 },151};
racing/game.json
json
1{2"id": "racing",3"title": "Racing",4"summary": "Time trials on real streets. Pick a track, stop on the start line and go when the lights go out: a time for your car's class, a medal, and points. Line up with friends to race on the same lights.",5"version": "1.0.0",6"api": 1,7"instance": { "kind": "world" },8"area": { "built": true },9"world": { "traffic": 1, "pedestrians": 1 },10"actions": [{ "id": "board", "label": "Tracks", "key": "panel" }],11"capabilities": ["badges"]12}