server.js to reload active instances in placeeg.* globals and handlers via jsconfig.jsonHow the runtime works
A game is a folder with two files: game.json declares metadata, player modes, and content flags, while server.js exports event handlers. The platform handles 3D rendering, physics, vehicles, combat validation, and networking — your script calls eg.* to shape the rules.
Scaffold with earthgames new. Get full eg.* autocomplete from bundled earthgames.d.ts.
earthgames devValidates locally, pushes drafts to your private dev slot, and streams live server logs to your terminal.
Runs one VM per instance. Reacts to joins, zones, combat, races, and timers within strict CPU budgets.
Pushes zones, NPCs, HUD cards, menus, waypoints, and audio cues to everyone in your match.
Explore real shipped games
Every game below runs on the public eg API and ships inside the SDK. Inspect the real rules scripts or scaffold one locally in one command.
// 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');
// ... full source on /developers/examples#blank// 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: 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 },
]);
}
// ... full source on /developers/examples#horde// 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([
// ... full source on /developers/examples#responder// 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')}`;
}
// ... full source on /developers/examples#racingStart in five minutes
- Turn on maker mode & mint a token
Open your Account Developer Console, accept the maker rules, and generate a token (
egdev_…). - Scaffold a project (Node.js 20+)setupsh
$ npx earthgames new my-game $ cd my-game $ npx earthgames login --token egdev_… - Run it live on the 3D world
Checks your manifest and script, uploads a private draft, and prints a direct launch URL.
watch & reloadsh$ npx earthgames dev - Edit & hot-reload with live telemetry
Save
server.jsand your running match restarts in ~1 second with you still inside. Script output fromconsole.logstreams to your terminal and the in-game console (`key). - Test multiplayer before publishing
Drafts run in a private copy of the world. Share the invite code with friends to playtest together — zero review required for private drafts.
Built-in platform systems
placesNear — zero hardcoded coordinates.Explore spatial APIs →
eg.npcsAutonomous AI crowdsDefine character kinds and behaviors (chase, guard, patrol, flee). The engine handles pathing and hundreds of active NPCs.Explore NPC APIs →
eg.combat & eg.inventoryServer-authoritative combatEnable health, armor, weapons, damage, explosions, fire/confetti/ring FX, and custom items in one call. Hit detection runs server-side.Explore combat APIs →
eg.ui & eg.audioRich HUDs, windows & modalsShow structured multi-block windows, awaitable confirms/forms, banners, countdowns, badges, chat announcements, and haptic feedback.Explore UI APIs →
eg.saves & eg.scoresPersistence & leaderboardsStore per-player progress across matches, run persistent multi-day worlds, and publish weekly/all-time scoreboards.Explore persistence APIs →
eg.raceStreet & custom racingOffer tracks built from real streets or define custom gate courses with synchronized start lights, splits, and class par times.Explore racing APIs →
Sandbox model & guarantees
Limits are transparent live budgets — visible in real time inside the in-game dev console — rather than guesswork.
What your script controls
- Full control over entities, spawners, combat, teams, races, saves, and UI inside your running instance.
- Cross-session player persistence and persistent world state with automatic save hooks (
onLoad). - Live telemetry in your terminal and the in-game dev panel (
`): console output, handler CPU ms, and dropped events.
Security & runtime boundaries
- Zero network access (no
fetch), no filesystem access, and no arbitrary HTML injection into player pages. - Player privacy by design: scripts see only a display name and a game-scoped opaque ID.
- Single-file ES module (
server.js) with deterministic turn budgets (8 ms / handler); useeg.timersandeg.world.now().
Publishing & maker rewards
Run npx earthgames submit when ready. Every submission is reviewed by the Earth Games team before going live on Games with its own URL (/games/<id>) and maker profile. Updating an approved game bumps "version" while players stay on the live build until review finishes.
Rewards are discretionary thank-yous (no revenue share). See full reward rules or check live monthly stats in your Developer Console.
No code? Build right inside the 3D world
Press P in Earth Games and open Make a game to place zones visually, wire rule cards, playtest with friends, and submit for review.
Documentation & machine-readable SDK
eg.* method, signature, and HUD part generated from the runtime table.Search API →
03 · Manifest & Specsgame.json, assets & limitsManifest schema, live marker color swatches, weapon stats, character models, sounds, and budgets.Inspect specs →
Join the Earth Games Discord
Voice chat for heists, convoys and Cannonball races, live town launch pings, daily photo/place trivia, and in-game chat. Joining unlocks the Discord Explorer badge, +25 Credits, and 5× town votes.
