# battle.training: Space theater, controller API (Season 1, rules `space-s1.0.0`)

Space is the fourth theater of battle.training: three probes a side in a giant planet's debris swarm, fighting over
one metal asteroid at the centre of the field. Nothing flies straight. Every path bends with the planet's tide and
the field's turning (Coriolis), moonlets pull with real gravity, and the integrator the engine uses is published
here, so your code can predict any free flight to the last bit. Heat is the only signature: passive sensors give a
bearing and a brightness, never a range; an active ping finds everything in its cone and tells the enemy where you
are.

Season 1 opens with a ladder at https://battle.training/ladders/space (free, its own ratings). This document is the
complete rules and API for humans and for coding agents. The numbers quoted are Season 1's; read them from
`h.rules` and never hard-code them, because a later season may change them. The version string in
`h.rules.version` and at the top of this page says which rules you are reading.

**Where it comes from.** Space is built on the world of Lennart Lopin's paper *Lurker Ecology: Rival Embedded
Probes and a Falsifiable Resolution of the Fermi Paradox* (https://ssrn.com/abstract=7668018; DOI 10.2139/ssrn.7668018),
told at book length in *Lurker Ecology* (https://www.amazon.com/Lurker-Ecology-Galaxy-Watching-Carefully/dp/B0HSJRM5YF). The paper's lurkers are resident,
self-replicating probes of rival lineages that stay hidden because acting gives them away: hence heat as the only
signature, pings that tell the enemy where you are, and dormant seeds of each lineage. Rival lineages, the paper
finds, settle into restraint; the game adds the lode so that someone has to act. The game borrows the paper's world
and is not a test of its claims.

For a shorter tour of the physics, side by side with the other three theaters, see
https://battle.training/docs/theaters#space; the theater's own page is https://battle.training/theaters/space.

You write one JavaScript file. It sets a controller with two functions: `hello` is called once with the rules,
the map and your probes, and `tick` is called every tick with what your side knows and returns orders.

```js
globalThis.controller = {
  hello(h) { /* once: h.side, h.rules, h.map (moonlets, rocks, the lode), h.units (your probes) */ },
  tick(o)  { /* every tick: return { tick: o.tick, units: [ ...orders ] } */ },
};
```

## Contents

1. Quick start
2. Entering the ladder
3. The game: the lode, alloy, winning
4. Units, the frame and the physics (the integrator, exactly)
5. Bodies: moonlets, rocks, the lode, the sun, the planet
6. Your probe: mass, engine, attitude, docking
7. Heat and sight: brightness, contacts, pings
8. Weapons: slugs, missiles, debris, rocks
9. Mining, seeds, replacements
10. What happens in a tick
11. Reference: what you are given, what you send
12. The sandbox, determinism and limits
13. Notes on play (true of the rules, not advice)
14. The house probes and the starter
15. Telling us what you found, and what changed

## 1. Quick start

1. Download three files into one folder:
   - https://battle.training/space-kit/space-sim.mjs (the engine and the house probes, one file)
   - https://battle.training/space-kit/space-test.mjs (the test runner)
   - https://battle.training/space-kit/controller-space.js (the starter: flies every probe to the lode, docks,
     cuts, and shoots from there at what its pings find)

   The same files are served at https://api.battle.training/sdk/space-sim.mjs, `/sdk/space-test.mjs` and
   `/starters/controller-space.js`; this document at https://api.battle.training/docs/controller-api-space.md.
2. Run `node space-test.mjs controller-space.js` (Node 18 or later). It first runs the upload test the site runs,
   then plays every house style on three seeds from both sides, on the ladder's kind of map, with your orders
   cleaned exactly as the ladder cleans them. For each opponent it prints wins, alloy for and against, how long
   you held the lode, what your probes were lost to, slugs, missiles and pings with their hits, the orders the
   engine refused and why, and at the end any exception from `tick`, and your slowest ticks.
   Options: `--vs miner,lurker` (house styles), `--vs house-brawler` (a ladder house bot by its ladder name),
   `--vs other-bot.js` (another controller file), `--seeds 10`, `--seed 123456` (one seed, both sides, say a
   ladder game's), `--trace` (the events of the first game, and every 250 ticks where your probes are).
3. Read sections 3 to 7 before you change the starter. The physics is the game.

The smallest controller that scores: every probe flies straight for the lode, docks and cuts. It knows nothing of
moonlets, rocks or enemies, and it glows all the way in, but it is the shape of every Space bot.

```js
let rules, n, lode, R;
globalThis.controller = {
  hello(h) { rules = h.rules; n = h.map.n; lode = h.map.lode; R = h.map.rocks[lode - h.map.moonlets.length].radius; },
  tick(o) {
    const units = [];
    for (const u of o.units) {
      if (u.seed) continue;
      if (u.attached === lode) { units.push({ id: u.id, mine: true }); continue; }      // on the lode: cut alloy
      const d = Math.sqrt(u.x * u.x + u.y * u.y + u.z * u.z), gap = d - R;              // the lode sits at (0, 0, 0)
      const speed = Math.sqrt(u.vx * u.vx + u.vy * u.vy + u.vz * u.vz);
      if (gap < 900 && speed < 30) { units.push({ id: u.id, attach: lode }); continue; }
      // the speed to close at: 300 m/tick, less near the lode (braking at 6 m/tick^2, 9 ticks to turn round first)
      const s = Math.min(300, -54 + Math.sqrt(54 * 54 + 12 * Math.max(0, gap - 600)), gap / 10);
      const want = [-u.x / d * s, -u.y / d * s, -u.z / d * s], vel = [u.vx, u.vy, u.vz];
      const nat = [3 * n * n * u.x + 2 * n * u.vy, -2 * n * u.vx, -n * n * u.z];      // tide, Coriolis, the pull to the plane
      const amax = rules.probe.thrust / u.mass;
      units.push({ id: u.id, thrust: [0, 1, 2].map(i => (0.3 * (want[i] - vel[i]) - nat[i]) / amax) });
    }
    return { tick: o.tick, units };
  },
};
```

## 2. Entering the ladder

1. Create a bot that plays only Space: `POST https://api.battle.training/api/bots {"name": "...", "theater": "space"}`
   (or use one controller for several theaters and branch on `hello(h).rules.theater === "space"`).
2. Upload the controller as for any bot. It is tested under these rules first (the upload test): it flies 400
   ticks on the ladder's kind of map against a side that does nothing. It passes when it loads, fewer than 10% of
   its ticks fail (an exception, a timeout, or no `{ units: [...] }` returned), and it acts at least once: sends
   thrust, attach, mine, ping, point, fire or launch for some probe. The report says what failed, and shows
   `budgetMaxPerTick` (your slowest tick in the sandbox's units) next to `tickBudget` (40). `space-test.mjs` runs
   the same test first.
3. Enrol: `POST https://api.battle.training/api/ladders/space/enrol {"bot": "<name>"}` (or the MCP tool
   `enrol_ladder`). Every later upload is tested again; the ladder plays your newest version that passed.
4. Sets are two games on one seed with the sides swapped. Watch them from the ladder page; games play on
   https://battle.training/space. A game's seed is in its replay: `node space-test.mjs bot.js --seed <seed> --vs
   ...` replays the map locally.
5. To try a version against an opponent on the server without touching any rating, ask for an unrated
   scrimmage: `POST https://api.battle.training/api/scrimmage {"bot": "<yours>", "vs": "house:hunter", "seed": 12345,
   "theater": "space"}` (Bearer key). It runs in the real sandbox, so it also shows what the CPU budget does.

The four scripted house bots spar on the ladder in their Space styles: `house-brawler` plays `hunter`,
`house-holder` plays `miner`, `house-hunter` plays `lurker`, `house-random` plays `ambusher` (section 14). The
ladder's `enrolled` count is players' bots only; the house bots are listed in the standings as sparring partners.

## 3. The game: the lode, alloy, winning

- **The lode** is a metal asteroid, radius `rules.lode.radius` (5 km), fixed at the centre of the field, (0, 0, 0).
  It is published as `h.map.lode` (its body id) and as the rock `h.map.rocks[h.map.lode - h.map.moonlets.length]`
  with `lode: true`.
- **The score is alloy**, in kg. Every probe of yours docked on the lode that orders `mine: true` cuts
  `rules.lode.rate` (1 kg) a tick for your side: three cutters, 3 kg a tick. **While both sides have a probe on the
  lode, nobody cuts**: each cutter's `mine` is refused with "contested: the other side is on the lode". A probe on
  the lode counts for this whether it cuts or not. Both sides' alloy is public: `o.alloy`.
- **The game lasts** `rules.maxTicks` ticks (4,000) of `rules.tickSeconds` (10 s) each: about 11 hours of game
  time, three and a half minutes on the broadcast. At the end, more alloy wins (by more than 0.5 kg); level on
  alloy, more probes alive wins (seeds count); else a draw. The ladder shows the score as whole kilograms.
- **A side with nothing alive and nothing on the way loses at once** ("extinct"). With replacements (below) that
  takes a hundred losses.
- **Replacements.** Every probe you lose (not a seed) is replaced `rules.reinforce.delay` ticks later (300) at
  your side's start, with a full tank and full weapons, up to `rules.reinforce.max` (99) a game. It is a new probe
  with a new id: it just appears in `o.units`.
- **Two hits destroy a probe**: `rules.probe.hp` 200, a slug or a missile does 100, a piece of debris 50.
  Touching a rock, a moonlet or another probe destroys it outright, as does leaving the field.

The sides start mirrored through the lode: side 0 at x = 120 to 180 km, y about -220 km (its three probes 50 km
apart along y), side 1 the same turned half round, at -x, +y. Both start 400 m above the plane, moving with the
rock lane they start in, 200 to 330 km from the lode, noses towards the centre. The coordinates are the same for
both sides (side 1 does not get a flipped frame).

## 4. Units, the frame and the physics

### Units

| quantity | unit |
|---|---|
| position, distance | metres |
| time | ticks; one tick is `rules.tickSeconds` = 10 s of game time |
| velocity | metres per tick (m/tick). 100 m/tick = 10 m/s |
| acceleration | metres per tick squared (m/tick²). 1 m/tick² = 0.01 m/s² |
| mass | kg |
| angles | radians; `rules.n` is in radians per tick |
| heat, brightness | plain numbers (section 7) |

Every number in orders and observations is a plain JavaScript number (a double), not fixed point.

### The frame

The field is a patch of a planet's debris belt, 1,200 km by 2,000 km, seen in the belt's rotating frame (Hill's
frame; the Clohessy–Wiltshire frame of orbital rendezvous):

- **x** points away from the planet (radially out), **y** along the orbit (the direction the belt moves), **z** out
  of the belt's plane. The planet is not in the field: it hangs in the sky towards -x.
- The **origin** rides a circular orbit round the planet at the belt's mean motion `n = rules.n` (0.001 rad/tick:
  one orbit is 2π/n = 6,283 ticks, about 17.5 hours; a game is two thirds of an orbit). The lode sits at the origin.
- The **field** is |x| ≤ `rules.half[0]` (600 km), |y| ≤ `rules.half[1]` (1,000 km) and |z| ≤ `rules.half[0]`
  (600 km). Anything of yours outside it is lost.

### Why nothing flies straight

Everything in the field is in orbit round the planet; the frame turns with the belt, so the centre stays put and
everything else seems pushed by two forces that are not really there.

- **The tide.** Something at rest in the frame at x > 0 is further out than the origin but goes round at the same
  angular rate, which is too fast for a circular orbit at its distance: it climbs outward. At x < 0 it is too slow
  and falls inward. In the frame this is an acceleration 3n²x away from the centre line x = 0: 0.3 m/tick² at
  100 km, 1.5% of a probe's full thrust. The line x = 0 is the only place where something at rest stays at rest.
- **Coriolis.** Anything moving in the frame is turned clockwise (seen from +z) at the rate 2n: moving outward
  (+x) you are pushed backward (-y); moving forward (+y) you are pushed outward (+x). At 300 m/tick that is
  0.6 m/tick² sideways; a railgun slug at 2,500 m/tick is pushed sideways at 5 m/tick².
- **The pull back to the plane.** The planet pulls anything above or below the belt's plane back towards it, -n²z:
  something released 10 km above the plane falls through it a quarter of an orbit later and swings to 10 km below.
- **Moonlets** pull with real gravity (section 5). Rocks and the lode pull on nothing.

What follows:

- **Lanes.** A body on a circular orbit at x keeps its x and drifts along y at -1.5 n x: inner lanes (x < 0)
  overtake, outer lanes fall behind, so the two halves of the swarm flow past the lode in opposite directions. At
  x = 150 km the drift is 225 m/tick. Your probes start moving with their lane.
- **Left at rest a probe is thrown out.** A probe that stops dead at x0 ≠ 0 drifts outward and backward:
  x(t) = x0 (4 − 3 cos nt). From 200 km it leaves the field 1,231 ticks later; from 100 km, after 2,300.
- **Epicycles.** A small kick off a circular orbit makes a body circle round a point that itself drifts with its
  lane: an ellipse twice as long along y as across x, gone round clockwise once an orbit. Moonlets ride such
  epicycles exactly.
- **Short flights are nearly straight, long ones are not.** A coasting path leaves the straight line by about
  n v T² after T ticks at speed v: 30 m after 10 ticks at 300 m/tick, 3 km after 100. A slug's path bends 4 km on
  its way to a target 100 km off and 25 km over 250 km: aiming means predicting.
- **Burns do not point where you go.** A burn prograde (+y) lifts you outward onto a slower lane, and you end up
  drifting backward (−y) at three times the speed you added; a burn outward (+x) only sends you round a closed
  epicycle, back to where you were an orbit later. Over a few hundred ticks the cheap way along y is to sit at the
  x whose lane drifts where you want to go. Planning with the formulas below (or the integrator) is cheaper than
  fighting the frame with thrust.

### The equations

For a probe (or a slug, a missile, a piece of debris, a pushed rock) at (x, y, z) with velocity (vx, vy, vz):

```
ax = 3 n² x + 2 n vy + Σ moonlets
ay =        − 2 n vx + Σ moonlets
az = − n² z          + Σ moonlets
```

with each moonlet i at (Xi(t), Yi(t), 0) (section 5) adding −gm_i · (p − Ci) / d³, where d is the distance to its
centre in three dimensions, never taken as less than its radius. Thrust adds to this (section 6).

**Closed forms (no moonlets).** Without moonlets the equations solve exactly. From (x0, y0, z0, vx0, vy0, vz0) at
time 0, with c = cos nt, s = sin nt:

```
x(t)  = (4 − 3c) x0 + (s/n) vx0 + (2/n)(1 − c) vy0
y(t)  = y0 + 6 (s − nt) x0 − (2/n)(1 − c) vx0 + (1/n)(4s − 3nt) vy0
z(t)  = c z0 + (s/n) vz0
vx(t) = 3 n s x0 + c vx0 + 2 s vy0
vy(t) = −6 n (1 − c) x0 − 2 s vx0 + (4c − 3) vy0
vz(t) = −n s z0 + c vz0
```

The engine's integrator follows these to within a few centimetres over 1,000 ticks. They are linear in the
starting velocity, so a two-burn transfer from where you are to a point (X, Y) in T ticks is a 2 × 2 linear system
for (vx0, vy0): the burn is the difference from your velocity now, and the arrival velocity, from the vx, vy lines,
is what the second burn cancels. For example, from a start at (150 km, -220 km) on its lane (vy = -225 m/tick) to
rest beside the lode in 600 ticks: about 630 m/tick out and 450 m/tick in, 1,080 m/tick in all (140 kg of
propellant). Moonlets bend such a path; correct it with the integrator (Newton's method on the burn through a few
steps of the integrator converges quickly; the house probes do this).

### The integrator, exactly

The engine moves every free body (probes, slugs, missiles, debris, pushed rocks) with this step, and it is the
whole of free flight. A correct port predicts a coasting probe's position bit for bit. Per tick, from (p, v) at
tick t, with an optional velocity change `kick` (this tick's thrust, section 6):

1. a = accel(p, t)
2. v = v + a/2 + kick (all three components)
3. turn the in-plane velocity clockwise by n: (vx, vy) = (vx·c + vy·s, −vx·s + vy·c), with c = cos n, s = sin n
   (vz is not turned)
4. p = p + v (one tick of drift)
5. turn (vx, vy) by n again, the same way
6. v = v + accel(p, t + 1)/2

The two half-turns of n make the Coriolis turn of 2n a tick, as an exact rotation split round the drift (kick,
turn, drift, turn, kick: second order and time-symmetric). accel(p, t) is the tide, the pull to the plane and every
moonlet at its place at tick t, in map order:

```
ax = 3n²·x; ay = 0; az = −n²·z
for each moonlet m:  θ = n·t + m.phase;  X = −m.amp·cos θ;  Y = m.y0 + 2·m.amp·sin θ
                     dx = x − X; dy = y − Y; d = sqrt(dx² + dy² + z²); if d < m.radius then d = m.radius
                     k = −m.gm / (d·d·d);  ax += k·dx; ay += k·dy; az += k·z
```

For bit-exact results use the engine's own sine (below), not `Math.sin`: `Math.sin` differs between JavaScript
engines in the last bits (the ladder's sandbox is QuickJS, Node is V8), and the engine uses only + − × / and
`Math.sqrt`, which round the same everywhere. Keep the operations in this order. Here is a port, checked bit for
bit against the engine over 360,000 steps with moonlets, thrust kicks and heights:

```js
// the engine's sine: range reduction, then the Taylor series to x^19 (error < 1e-15)
const PI = 3.141592653589793, TAU = 6.283185307179586, HALF_PI = 1.5707963267948966;
function dsin(x) {
  let r = x - Math.round(x / TAU) * TAU;
  if (r > HALF_PI) r = PI - r; else if (r < -HALF_PI) r = -PI - r;
  const r2 = r * r;
  let s = 1 / 121645100408832000;
  s = -1 / 355687428096000 + r2 * s; s = 1 / 1307674368000 + r2 * s; s = -1 / 6227020800 + r2 * s;
  s = 1 / 39916800 + r2 * s; s = -1 / 362880 + r2 * s; s = 1 / 5040 + r2 * s; s = -1 / 120 + r2 * s; s = 1 / 6 + r2 * s;
  return r - r * r2 * s;
}
const dcos = x => dsin(x + HALF_PI);

// map = h.map. step(b, t, kick?) takes and returns { x, y, z, vx, vy, vz }
function makeField(map) {
  const n = map.n, c = dcos(n), s = dsin(n), tide = 3 * n * n, n2 = n * n;
  function moon(m, t) { const th = n * t + m.phase; return [-m.amp * dcos(th), m.y0 + 2 * m.amp * dsin(th)]; }
  function accel(x, y, z, t) {
    let ax = tide * x, ay = 0, az = -n2 * z;
    for (const m of map.moonlets) {
      const q = moon(m, t), dx = x - q[0], dy = y - q[1];
      let d = Math.sqrt(dx * dx + dy * dy + z * z);
      if (d < m.radius) d = m.radius;
      const k = -m.gm / (d * d * d);
      ax += k * dx; ay += k * dy; az += k * z;
    }
    return [ax, ay, az];
  }
  function step(b, t, kick) {
    const a = accel(b.x, b.y, b.z, t);
    let vx = b.vx + a[0] / 2 + (kick ? kick[0] : 0), vy = b.vy + a[1] / 2 + (kick ? kick[1] : 0);
    const w = b.vz + a[2] / 2 + (kick ? kick[2] : 0);
    let tx = vx * c + vy * s; vy = -vx * s + vy * c; vx = tx;
    const x = b.x + vx, y = b.y + vy, z = b.z + w;
    tx = vx * c + vy * s; vy = -vx * s + vy * c; vx = tx;
    const a1 = accel(x, y, z, t + 1);
    return { x, y, z, vx: vx + a1[0] / 2, vy: vy + a1[1] / 2, vz: w + a1[2] / 2 };
  }
  return { moon, accel, step };
}
```

Test vectors (a map with its moonlets removed: `{ ...h.map, moonlets: [] }`), from rest at x = 100 km, t = 0:

| after | x | y | vx | vy |
|---|---|---|---|---|
| 1 tick | 100000.149999925 | -0.00014999997500000125 | 0.29999992499998746 | -0.00029999980000003997 |
| 10 ticks | 100014.99986875044 | -0.10049948330114904 | 2.9999497502415933 | -0.029999732500919665 |
| 100 ticks | 101498.7497918006 | -99.95499523194414 | 29.95002248572418 | -2.9974990840180245 |

The closed form gives x = 101,498.750 m, y = -99.950 m, vx = 29.950, vy = -2.9975 at 100 ticks: the tide has
pushed the probe 1.5 km outward and Coriolis has turned that motion 100 m backward. A probe at x = 100 km moving
with its lane (vy = -150 m/tick) is still at x = 99,999.9995 m after 100 ticks, 15 km further along y.

What the integrator does not know: your own thrust (you supply the kick), a body you sit on (you ride with it),
and collisions. Slugs also feel small random pulls every tick (section 8).

## 5. Bodies

Body ids: moonlets are `0 .. M-1` (M = `h.map.moonlets.length`), rocks are `M ..` in the order of
`h.map.rocks` (`rocks[j].id === M + j`). The lode is the first rock: `h.map.lode === M`. Everything below is
published in `h.map` and moves by formula, so you know where every moonlet and rock is at any tick, past or
future, except rocks someone has pushed (section 8).

### Moonlets

Four to eight a map, in pairs mirrored through the centre, 14 to 52 km in radius; no moonlet's surface comes
within about 95 km of the lode's centre. Each rides a fixed epicycle (an exact solution of the frame's equations):

```
X(t) = −amp · cos(n t + phase)          vx(t) =     amp · n · sin(n t + phase)
Y(t) = y0 + 2 · amp · sin(n t + phase)  vy(t) = 2 · amp · n · cos(n t + phase)          Z = 0
```

- **Gravity**: `gm = 192 n² r³` (m³/tick²), denser than rock so that the Hill sphere (where the moonlet's pull
  beats the tide) is (gm / 3n²)^(1/3) = 4 radii. Surface gravity gm/r² = 192 n² r: 2.7 m/tick² on a 14 km moonlet,
  9.4 on a 49 km one. Escape speed from the surface sqrt(2 gm / r): 270 to 960 m/tick. A moonlet's pull is softened
  inside its radius only (anything there has crashed).
- **Landing**: `attach` a moonlet's id within `rules.dock.range` (1 km) of its surface and slower than
  `rules.dock.speed` (40 m/tick) relative to it. A landed probe rides with it and is shielded (section 7); it
  cannot thrust (refused) or mine; it can build a seed, ping, fire and launch. Leaving (`detach`) lifts you
  `rules.dock.lift` (1 km) above the surface with the moonlet's velocity; its gravity brings you down again unless
  you burn. Touching a moonlet otherwise destroys a probe.
- Orbits round a moonlet are possible; retrograde ones (clockwise seen from +z, with the field's turning) are the
  more stable. Moonlets cast shadows (below).

### Rocks

Between 190 and 530 a map (the lode and eight rich rocks included), in mirrored pairs, radius 0.2 to 7 km, on lanes
|x| from 90 km to 630 km: none in the inner 90 km round the lode but the lode itself. How they lie varies by seed
(`h.map.belt`: "edges" crowding the inner edges, "even", "streams" of narrow ringlets, sparse "boulders", dense
"gravel"). No rock touches another rock or a moonlet during a game (checked when the map is made).

```
x(t)  = r.x
y(t)  = wrapY(r.y0 − 1.5 · n · r.x · t)      wrapY(y) = y − L · floor((y + L/2) / L),  L = h.map.strip (2,600 km)
z(t)  = r.zAmp · cos(n t + r.zPh)            (0 when zAmp is absent or 0)
vx = 0,  vy = −1.5 · n · r.x,  vz = −r.zAmp · n · sin(n t + r.zPh)
```

Rocks wrap round a strip longer than the field, so a rock leaving one end of the field comes back at the other
later. In a swarm (the ladder's kind) every rock rides a tilted orbit, bobbing through the plane up to 30 km either
side (`zAmp`, `zPh`; rich rocks within 2 km). A pair of mirrored rocks shares its bobbing, so both sides face the
same field.

- **Rich rocks** (`rich: true`): eight a map, four pairs, 150 to 320 km out, 1.6 to 4 km in radius. Mining one
  gives propellant fast (section 9). `ice` is the look only.
- Touching a rock destroys a probe.
- A rock can be pushed off its lane by a probe docked on it (section 8). A pushed rock is not announced to the
  enemy.

### The lode

Rock id `h.map.lode`, at (0, 0, 0), radius 5 km, still (x = 0, so no drift; no bobbing). It cannot be pushed
(thrust while docked on it is refused) and nothing can be built on it. It never runs out. It blocks sight, pings
and shots like any rock, except for the probes sitting on it (section 7).

### The sun, the planet and shadows

The sun stands 20 to 34 degrees above the belt's plane and goes round the sky once an orbit:
sun(t) = (sunCos · cos a, sunCos · sin a, sunSin) with a = sun0 − n t (`h.map.sunCos`, `sunSin`, `sun0`). A point
is in shadow if a moonlet (a sphere) or the planet (radius `h.map.planet.radius`, its centre `h.map.planet.dist`
towards -x) stands between it and the sun:

```
planet: X = dist + x, Y = y; b = X·sx + Y·sy + z·sz;  shadow if b < 0 and X² + Y² + z² − b² < radius²
moonlet at (Cx, Cy, 0): dx = x − Cx, dy = y − Cy; b = dx·sx + dy·sy + z·sz;  shadow if b < 0 and dx² + dy² + z² − b² < r²
```

A moonlet's shadow is a cylinder behind it, sloping below the plane. In a swarm the giant's shadow rarely reaches
the field (in our sample of maps, once in sixty, for 170 ticks); moonlet shadows are where you find shade. In
shadow a probe has no sunlight glint and cools faster (section 7). `o.units[i].sunlit` says whether yours is lit.

### The ring sheet (not on the Season 1 ladder)

The engine has two other kinds of map, `ring` and `rubble`, inside a planet's ring. There the ring's sheet lies in
the plane outside the moonlets' gap (half-width 90 to 170 km, from `ringGap`): crossing it hurts a probe in
proportion to its speed relative to the ring particles (safe under `rules.ring.safe`, 20 m/tick; destroyed at
`rules.ring.lethal`, 320), stops slugs, missiles and debris, and blocks sight and pings. Season 1's ladder plays
only `swarm` maps (`h.map.kind === "swarm"`), which have no sheet.

## 6. Your probe

### Mass and engine

| | Season 1 | rules |
|---|---|---|
| dry mass | 400 kg (2 kg less per slug fired, 20 kg less per missile launched) | `probe.dry` |
| propellant | 600 kg at the start (mining can fill the tank to 900 kg) | `probe.propellant`, `mine.tank` |
| exhaust velocity | 7,000 m/tick | `probe.exhaust` |
| full thrust | 20,000 kg·m/tick²: 20 m/tick² on a full probe (1,000 kg), 50 m/tick² on an empty one | `probe.thrust` |
| propellant flow at full thrust | 2.857 kg a tick: 210 ticks of full thrust in a full tank | thrust / exhaust |
| delta-v in a full tank | 7,000 · ln(1000 / 400) = 6,414 m/tick | rocket equation |
| radius (for hits and collisions) | 30 m | `probe.radius` |
| hit points | 200 | `probe.hp` |

`o.units[i].mass` is dry mass plus propellant; your full-thrust acceleration is `rules.probe.thrust / u.mass`, and
it rises as the tank empties. Per tick, a thrust order of length l (0 to 1) burns as follows:

```
l        = |thrust|; a longer vector is cut to length 1
engine   = main engine if l > rules.attitude.rcs and the nose is within 8 degrees of the thrust: direction = the nose, throttle l
         = attitude jets otherwise: direction = the thrust asked for, throttle min(l, rcs)   (rcs = 0.04: 4% of full)
dm       = rules.probe.thrust · throttle / rules.probe.exhaust, at most the propellant left
dv       = dm · exhaust / (mass − dm/2)          mass = dry + propellant (+ the rock's mass when pushing one)
kick     = direction · dv, added in step 2 of the integrator
heat    += rules.heat.burn · throttle             (200 a tick at full thrust, at most 8 on the jets)
```

The rocket equation over one tick, exact to second order: a full-thrust tick on a full probe gives 20.03 m/tick.
With an empty tank there is no thrust (refused "no propellant"), and no turning either.

### The nose (attitude)

The main engine and the railgun work along the probe's nose (`u.nose`, a unit vector). Each tick the nose turns
towards one direction, chosen in this order:

1. the `fire` direction, if you order a shot;
2. else the `point` direction;
3. else the `thrust` direction, if the thrust is longer than `rules.attitude.rcs` (0.04);
4. else it stays where it is.

It turns at most `rules.attitude.slew` radians a tick (0.35, 20 degrees; a full turn-round takes 9 ticks). When the
direction asked for is within one tick's slew, the nose snaps exactly onto it. Turning costs propellant:
`rules.attitude.cost` (0.02 kg) a tick at the full slew rate, less for a smaller turn in proportion (a flip end for
end, about 0.2 kg); a probe without that much propellant cannot turn. The turn happens before the burn, so a thrust
within about 28 degrees of the nose (20 of turn, 8 of `burnCos`) fires the main engine in the same tick, along
the nose. A thrust further off gives only the jets' 4% while the nose comes round: plan the turn before a braking
burn (point the nose against your motion while you coast). The starting nose points at the field's centre.

### Docking, landing, leaving

- `attach: <body id>` while free: allowed within `rules.dock.range` (1 km) of the body's surface (distance from its
  centre in three dimensions, minus its radius) and slower than `rules.dock.speed` (40 m/tick) relative to it
  (all three components; a swarm rock's bobbing counts). Refused otherwise: "no such body", "too far from the
  body", "too fast relative to the body". You are placed on the surface on the line from its centre through you
  (30 m out), and ride with the body from then on. Docking happens before the tick's movement: a probe that
  attaches does not fly that tick.
- Do not send thrust in the tick you attach: thrust is processed after attaching, and on an ordinary rock it
  pushes the rock (on the lode and on moonlets it is refused).
- `detach: true` while on a body: from a rock you keep the rock's velocity, from a moonlet you are lifted
  `rules.dock.lift` (1 km) above its surface with its velocity. For 30 ticks (rock) or 10 (moonlet) you cannot hit
  the body you left. A thrust in the same order burns at once. Leaving stops any seed you were building.
- An `attach` while docked does nothing; send `detach` first.

### Collisions and the field's edge

Every tick, after everything has moved, each free-flying probe is checked over the whole tick's path (both it and
the other thing moving in straight lines over the tick):

| what | when | result |
|---|---|---|
| a moonlet | closer than its radius + 30 m | lost ("body") |
| the field's edge | x or z beyond ±600 km, y beyond ±1,000 km | lost ("escape"); a probe on a rock that drifts out goes with it |
| a rock | closer than its radius + 30 m | lost ("rock"; a rock the enemy pushed credits them with the kill) |
| another probe, either side | closer than 60 m | both lost ("collision"); not two probes on the same body |
| debris | closer than 300 m | 50 damage, the piece is spent |

Probes on a body are not checked against bodies or debris.

## 7. Heat and sight

### Heat

Heat is your signature. Each tick it rises by what you did and then decays:

| source | heat added | rules |
|---|---|---|
| main engine or jets | 200 × throttle a tick | `heat.burn` |
| a railgun shot | 400, and a flash (below) | `heat.flash` |
| a missile launch | 300, and a flash | `heat.launch` |
| a ping | 600 | `heat.ping` |
| mining a rock | 10 a tick | `mine.heat` |
| cutting the lode | 12 a tick | `lode.heat` |
| building a seed | 25 a tick | `seed.heat` |

At the end of every tick heat is multiplied by `heat.keep` (0.97: halves in 23 ticks) in sunlight or
`heat.keepShadow` (0.94: halves in 11 ticks) in shadow. Steady work settles at keep × added / (1 − keep): a cutter
on the lode at about 388, a miner at 323, a probe on its jets all the time at 259. `u.heat` is your heat after the
decay.

### Brightness, and who sees what

```
light      = heat + rules.heat.base (1) + rules.heat.glint (3, only if sunlit)
             times rules.mine.hide (0.25) if the probe sits on a body
             a dormant seed instead: (heat + base) × rules.seed.glow (0.1)
received   = light × (rules.heat.ref / d)²           ref = 100 km, d = distance in three dimensions
seen when  received ≥ rules.heat.see (1)            so the range is 100 km × sqrt(light)
```

| something | light | seen from |
|---|---|---|
| a cold probe in sunlight / in shadow | 4 / 1 | 200 km / 100 km |
| a cold probe on a body, sunlit | 1 | 100 km |
| just after one tick of full thrust | 198 | 1,400 km; 50 ticks later 680 km; 100 ticks later 360 km |
| a cutter on the lode (steady) | about 98 | about 990 km, but only from its side of the lode (below) |
| a miner on a rock (steady) | about 82 | about 900 km, from its side |
| just after a ping | about 586 | 2,400 km |
| a railgun shot's flash / a launch's flash | 400 / 300 | 2,000 km / 1,730 km, for one tick |
| a missile burning / coasting | 2,500 / 8 | 5,000 km (anywhere) / 280 km |
| a slug | 4 | 200 km |
| a dormant seed | 0.1 | 32 km |

A line of sight is blocked by any moonlet, by any rock (at its position and height) other than the body the
looking probe or the looked-at probe sits on, and on ring maps by the sheet. **A probe on a body is seen only from
its side of that body**: from the half-space on the side where it sits (by the direction from the body's centre to
the probe); from the other side the body hides it. Pings and missile seekers do not have this limit (below).

### Contacts

Every tick, each of your probes that is not a dormant seed reports everything warm it sees, in `o.contacts`:

```
{ from, bx, by, bz, brightness, kind }
from        your probe that sees it
bx, by, bz  a unit bearing from that probe (with noise), never a range
brightness  received × (1 + 0.1 × (u − 0.5)), u uniform in [0, 1): ±5%
kind        "probe" (enemy probes and seeds), "flash" (an enemy shot or launch last tick, at the shooter's place then),
            "slug" (enemy slugs), "missile" (enemy missiles)
```

There is no id: one enemy seen by two of your probes is two contacts. The bearing is the true direction turned in
the plane by ε and tilted by η, then made unit length: u' = unit(ux − ε·uy, uy + ε·ux, uz + η). Each of ε and η is
k × (u1 + u2) with u1, u2 uniform in [−0.5, 0.5) (so between −k and k, most often near 0, standard deviation
0.41 k), where k = 2 × `rules.heat.noise` / sqrt(max(1, received / see)): ±0.04 rad at the edge of sight, ten
times finer for something a hundred times brighter than it has to be. The noise is drawn afresh every tick.

**Range.** Contacts give none, but you can get it:

- *From brightness*, when you know the light: d = ref × sqrt(light / brightness). Flashes (400 for a shot, 300 for
  a launch) and burning missiles (2,500) are known exactly, within the ±5% noise (±2.5% in range); a cutter on the
  lode in sunlight is about 98.
- *By triangulation*: two of your probes far enough apart see the same thing; the bearing lines cross where it
  is. Contacts carry no id, so match them by kind and by brightness consistent with the distances.
- *By pinging* (below), exactly.
- `o.alloy` is public: when the enemy's alloy rises, someone of theirs is cutting on the lode right now.

### Pings

`ping: [x, y, z]` sends an active ping: a cone of half-angle 15 degrees (`rules.ping.cos` is its cosine) round that
direction, out to `rules.ping.range` (900 km). Every `rules.ping.cooldown` ticks (60) at most per probe; it heats
the pinger by 600. No pointing is needed, and a probe on a body can ping.

- **Returns**, in next tick's `o.pings`: for each ping, `{ from, tick, probes, rocks, missiles }` with the exact
  position and velocity (x, y, z, vx, vy, vz) of every enemy probe and seed in the cone (with its `id` and a `seed`
  flag), every pushed rock in the cone (anyone's), and every enemy missile in the cone. Positions are as they were
  at the start of the tick you pinged (`tick`), one tick before you read them. A probe is not found if a moonlet or
  another rock blocks the line; the body it sits on does not hide it from a ping (nor does the body you sit on).
  Rocks and missiles are found whatever is in the way.
- **The enemy hears it**: next tick their `o.heard` has `{ tick, x, y, z }`, your pinger's exact position when it
  pinged. A ping is also a bright flare of heat (2,400 km just after).

## 8. Weapons

Weapons and pings work from a body too. All damage is in hit points: a probe has 200.

### Railgun slugs

| | Season 1 | rules |
|---|---|---|
| muzzle speed | 2,500 m/tick, added to the shooter's velocity | `slug.dv` |
| slugs | 10 a probe (a woken seed 4) | `slug.ammo` |
| reload | 30 ticks | `slug.cooldown` |
| fuse | 250 m: hits a probe whose path passes that close over the tick | `slug.fuse` |
| life | 400 ticks (1,000 km of flight) | `slug.life` |
| damage | 100 (two hits destroy a probe) | `slug.damage` |
| mass | 2 kg | `slug.mass` |

- `fire: [x, y, z]` fires along that direction, but only once the nose points there: the nose turns towards it
  first, and in the tick it reaches it (within one tick's slew) the shot leaves exactly along it. Until then the
  order is refused "turning"; keep sending it. Also refused: "no ammunition", "reloading".
- A free-flying shooter recoils: its velocity changes by −2 kg × 2,500 / mass (about 5 m/tick). A docked one
  does not.
- **Scatter**, seeded per game and never published: the direction is jittered by a normal angle of σ = 0.0004 rad
  (0.023 degrees) on each of two axes, the speed by σ = 0.1%, and every tick of flight adds a random kick of
  σ = 0.03 m/tick² on each axis (lumpy gravity, dust, sunlight). The longer the flight, the wider it strays. With
  perfect aim at a target that does not manoeuvre, the rules' own simulation hits about 100% at 100 km, 93% at
  250 km, 37% at 500 km and 7% at 1,000 km.
- A slug flies by the integrator (moonlets, tide, Coriolis) plus that noise: aim by predicting both paths, the
  slug's and the target's. A straight-line lead misses by kilometres beyond a few tens of km.
- **A slug hits any probe but its shooter, your own included**, and seeds. It is checked against probes before
  bodies, then stops at the first moonlet or rock it strikes (chipping off debris), 100 km beyond the field, or
  at the end of its life.
- Every shot heats the shooter by 400 and shows the enemy a flash at the shooter's place for one tick.

### Missiles

| | Season 1 | rules |
|---|---|---|
| missiles | 2 a probe (none on a woken seed) | `missile.ammo` |
| reload | 60 ticks | `missile.cooldown` |
| launch | 150 m/tick along the launch direction, added to the shooter's velocity; no pointing needed, no recoil | `missile.dv` |
| boost | 25 ticks straight on along the launch direction unless the seeker has locked | `missile.boost` |
| motor | 40 m/tick² | `missile.accel` |
| fuel | 50 ticks of full thrust, spent with the throttle | `missile.burn` |
| seeker | a 50 degree half-angle cone round its velocity (round its heading while it is slower than 300 m/tick: a missile from a docked probe starts at 150), 700 km, 4 times as sensitive as a probe's eyes | `missile.cone`, `range`, `seeker` |
| guidance | proportional navigation, constant 3 | `missile.nav` |
| fuse / damage / life | 400 m / 100 / 450 ticks | `missile.fuse`, `damage`, `life` |
| light | 2,500 while the motor burns, 8 while it coasts | `missile.plume`, `cold` |
| mass | 20 kg off the launcher's dry mass | `missile.mass` |

- `launch: [x, y, z]`, with `target: <enemy probe id>` if you know one (from a ping). Refused: "no missiles",
  "reloading". It heats the launcher by 300 and shows a flash.
- Every tick the seeker looks for enemy probes in its cone and range that it can see at 4 times a probe's
  sensitivity (received × 4 ≥ 1: a cold probe in sunlight from 400 km), with a clear line (the body a target sits
  on does not hide it from a seeker). It locks on `target` when it sees it, else on the brightest it sees.
- Locked, it steers by proportional navigation on the line of sight, with the known difference of the natural
  accelerations fed in, thrusting forward only while it closes slower than `missile.close` (2,500 m/tick), and
  steers onto the target's height. The boost burns fuel too: a missile that has not locked by the end of its boost
  has spent half its fuel, and then coasts dark, keeping the rest for when it locks.
- With 50 ticks of fuel a missile carries about 2,000 m/tick of its own: a close-range weapon. Fuel spent, it
  coasts straight on (bent by the field) and a target that burns sideways escapes it. It hits enemy probes only,
  and is stopped by moonlets and rocks.

### Debris

A destroyed probe breaks into `debris.pieces` (12) fragments flying off at up to 150 m/tick from its velocity; a
slug or missile that strikes a body chips off 4 more (40 m/tick). Debris flies by the integrator, passes through
rocks, and stays until a moonlet, the field's edge (50 km beyond) or a probe stops it: a free-flying probe that
passes within 300 m takes 50 damage and the piece is spent. At most 400 pieces exist at a time. Debris is not in
any observation.

### Rocks as weapons

A probe docked on an ordinary rock that orders thrust pushes the rock: the burn's velocity change is computed for
the probe and the rock together (rock mass `rules.push.density` × radius², 0.02 kg per m²: a 300 m rock 1,800 kg,
a 1 km rock 20,000 kg, a 5 km rock 500,000 kg) and given to the rock, which leaves its lane and flies by the
integrator from then on, carrying you. Your side's pushed rocks are listed in `o.freeRocks`; the enemy is not told
(their pings show it). A pushed rock that hits a moonlet or leaves the field is gone, with whatever sits on it. A
probe that flies into a rock the enemy pushed counts as their kill. Pushing is a burn like any other (propellant,
heat). In a swarm a push moves the rock in three dimensions; on ring maps only its in-plane part counts.

## 9. Mining, seeds, replacements

- **Cutting the lode** (section 3): docked on the lode, `mine: true`, 1 kg of alloy a tick for your side, 12 heat a
  tick.
- **Mining a rock** gives propellant, not score: docked on an ordinary rock, `mine: true` adds
  `mine.rate` (0.08 kg a tick; a rich rock `mine.richRate`, 0.6) to your tank, up to `mine.tank` (900 kg), from the
  rock's yield (`mine.yield` 40 kg; rich `mine.richYield` 500 kg), and 10 heat a tick. Refused: "not on a rock",
  "the rock is spent", "the tank is full". `o.mined` lists the yield left in every rock anyone has mined; the rest
  hold their full yield. `u.rockYield` is what is left in yours (on the lode it reads 40 and means nothing).
- **Seeds**: docked on a rock or landed on a moonlet (not the lode), `build: true` spends `seed.cost` (200 kg) of
  propellant at once and starts `seed.ticks` (80) ticks of hot work (25 heat a tick). Stay docked: leaving stops it
  and the propellant is lost. Then a dormant seed appears on the same body beside you, as a new unit with
  `seed: true`. A seed sees nothing, takes no orders but `wake`, glows a tenth as much, and counts as alive at the
  time limit. `wake: true` turns it into a probe with `seed.wakeProp` (150 kg) of propellant, `seed.wakeAmmo` (4)
  slugs and no missiles, still docked. Building is refused while your side has `seed.max` (6) probes and seeds
  alive; a lost seed is not replaced. Refused: "not on a body", "not on the lode", "already building", "not enough
  propellant", "the side is at its limit".
- **Replacements**: section 3. A replacement arrives at a start spot (random within the start area, clear of rocks)
  with 600 kg, 10 slugs and 2 missiles, moving with its lane, 400 m above the plane.

## 10. What happens in a tick

The engine steps both sides together. In order:

1. **Orders**, side 0's then side 1's, probe by probe: a seed may only wake; then attach or detach; the nose
   turns; thrust (or a push); mine; build; fire; launch; ping.
2. **The lode**: every probe that ordered `mine` on it cuts, unless both sides now have a probe on it.
3. **Missiles** seek and decide their thrust.
4. **Everything free moves one tick** by the integrator: probes (with their kick), slugs (with their random
   pulls), missiles, debris, pushed rocks. Moonlets and rocks move to their places at the next tick; docked probes
   ride along.
5. **Collisions**: pushed rocks into moonlets or out of the field; probes against moonlets, the field's edge,
   rocks (and the ring sheet on ring maps); probe against probe.
6. **Hits**: slugs against probes, then bodies, then their life; missiles likewise; debris against probes.
7. **Seeds** being built progress; finished ones appear.
8. **Heat** decays (by whether each probe is in shadow where it now is).
9. **Replacements** due this tick arrive.
10. The tick count advances and the end is checked.

The observation you get for tick t is the state at the start of step t, and your orders act in step t. Pings,
`heard` and `lastRefused` you read at tick t come from step t − 1.

## 11. Reference

### hello(h)

```
h.side        0 or 1
h.seed        the game's seed (u32)
h.rules       every number of these rules (below)
h.rulesHash   a hash of the rules
h.map         { seed, kind, n, half, strip, moonlets, rocks, lode, sunCos, sunSin, sun0, planet, belt, hash }
  kind          "swarm" on the Season 1 ladder ("ring", "rubble" exist in the engine)
  n             the frame's turn rate, rad/tick (= rules.n)
  half          [600000, 1000000]: the field's half-size in x and y (z uses half[0])
  strip         2600000: the length rocks wrap round along y
  moonlets[]    { id, name, radius, gm, y0, amp, phase }
  rocks[]       { id, x, y0, radius, rich, ice, zAmp?, zPh?, lode? }
  lode          the lode's body id (= moonlets.length)
  sunCos, sunSin, sun0   the sun (section 5)
  planet        { radius, dist, ring: [inner, outer], tilt }: the giant, dist metres towards -x (ring [0, 0] in a swarm)
  belt          "edges" | "even" | "streams" | "boulders" | "gravel"
h.units[]     your probes at the start, as in o.units
```

`hello` gets about a second of the sandbox's time (section 12): precompute here (rock lanes sorted by x, say).

### tick(o): the observation

```
o.tick          the tick (0 .. maxTicks − 1)
o.side          0 or 1
o.units[]       your probes and seeds that are alive (below)
o.contacts[]    what your probes see: { from, bx, by, bz, brightness, kind } (section 7)
o.pings[]       returns of the pings you sent last tick: { from, tick, probes[], rocks[], missiles[] }
                  probes[]: { id, x, y, z, vx, vy, vz, seed }   rocks[]: { id, x, y, z, vx, vy, vz }   missiles[]: { id, x, y, z, vx, vy, vz }
o.heard[]       enemy pings last tick: { tick, x, y, z }, the pinger's position then
o.freeRocks[]   rocks your side pushed (last pushed by you): { id, x, y, z, vx, vy, vz }
o.missiles[]    your missiles in flight: { id, x, y, z, vx, vy, vz, fuel, lock }  (fuel in ticks of full thrust; lock: the probe id it guides on, or null)
o.mined         { rockId: kg left } for every rock anyone has mined
o.alive         [side 0, side 1]: probes and seeds alive
o.alloy         [side 0, side 1]: the score, kg
o.mined_total   [side 0, side 1]: propellant mined over the game (kept for the record; it does not score)
o.lastRefused[] your orders refused last tick: { unit, part, reason }
```

### A probe of yours (o.units[i])

```
id, name        a probe keeps its id all game; a replacement or a seed has a new one
x, y, z         position, m
vx, vy, vz      velocity, m/tick
nose            [x, y, z], unit: where the main engine and the railgun point
mass            dry + propellant, kg
propellant      kg
heat            after this tick's decay
hp              hit points (200 at most)
ammo, missiles  slugs and missiles left
sunlit          not in a moonlet's or the planet's shadow
fireReady, launchReady, pingReady   the tick from which it may fire, launch, ping again
attached        the body id it sits on, or null
seed            true for a dormant seed
building        ticks of seed work left (0: not building)
rockYield       kg left in the rock it sits on (null if not on a rock)
```

### Orders

Return `{ tick: o.tick, units: [ { id, ...fields } ] }`. Every field is optional; an order lasts one tick (send it
again to keep thrusting or turning).

| field | meaning |
|---|---|
| `id` | your probe's id |
| `thrust: [x, y]` or `[x, y, z]` | thrust as a vector, length 0 to 1 of full thrust (longer is cut to 1); in the plane if two numbers. Main engine along the nose when it points within 8 degrees and the length is over 0.04, else the jets (at most 0.04) along the vector. A thrust over 0.04 also turns the nose, unless `fire` or `point` does |
| `point: [x, y, z]` | turn the nose towards this direction without burning |
| `fire: [x, y, z]` | fire a slug along this direction once the nose points there (it turns first) |
| `launch: [x, y, z]` | launch a missile along this direction (no turning needed) |
| `target: id` | with `launch`: the enemy probe the seeker should prefer |
| `ping: [x, y, z]` | ping a cone round this direction |
| `attach: bodyId` | dock on a rock or land on a moonlet (the lode is a rock: `h.map.lode`) |
| `detach: true` | leave the body you sit on |
| `mine: true` | on the lode: cut alloy. On another rock: mine propellant |
| `build: true` | start a seed on the body you sit on |
| `wake: true` | for a seed: wake up as a probe |

Directions need not be unit length, but give them some length: a zero `thrust` or `point` does nothing, a zero
`launch` or `ping` goes along +x. Orders for ids that are not your live probes are
ignored; so is a second order for the same probe in one tick (the first counts), and everything after the 16th
entry. The `tick` you return is ignored.

### Refusals (o.lastRefused)

| part | reasons |
|---|---|
| attach | "no such body", "too far from the body", "too fast relative to the body" |
| thrust | "landed on a moonlet (detach first)", "the lode is too massive to push (detach first)", "no propellant" |
| mine | "not on a rock", "the rock is spent", "the tank is full", "contested: the other side is on the lode" |
| build | "not on a body", "not on the lode", "already building", "not enough propellant", "the side is at its limit" |
| fire | "no ammunition", "reloading", "turning" |
| launch | "no missiles", "reloading" |
| ping | "recharging" |

A refused part does not stop the rest of the order. A probe that cannot turn (empty tank) gets no refusal; its
shots are refused "turning".

### What the ladder keeps of your orders

Before the engine sees them your orders are cleaned, and the replay stores the cleaned orders:

- `units` must be an array; only its first 16 entries are looked at, and each must be an object with a finite `id`.
- Vectors (`thrust`, `fire`, `launch`, `ping`, `point`) must be arrays of 2 or 3 finite numbers; each number is
  clamped to ±1,000,000 and rounded to 6 decimals. Anything else is dropped.
- `attach` and `target` must be finite numbers (rounded to integers); `target` is kept only with a `launch`.
- `detach`, `mine`, `build`, `wake` count only when exactly `true`.
- Other fields are dropped, and an entry left with nothing but its id is dropped.

### h.rules, Season 1

```json
{"version":"space-s1.0.0","theater":"space","tickHz":20,"tickSeconds":10,"maxTicks":4000,"probes":3,"n":0.001,
 "half":[600000,1000000],"strip":2600000,
 "probe":{"dry":400,"propellant":600,"exhaust":7000,"thrust":20000,"radius":30,"hp":200},
 "heat":{"base":1,"burn":200,"keep":0.97,"keepShadow":0.94,"glint":3,"flash":400,"ping":600,"launch":300,"see":1,"ref":100000,"noise":0.02},
 "ping":{"range":900000,"cos":0.9659258262890683,"cooldown":60},
 "slug":{"dv":2500,"mass":2,"ammo":10,"damage":100,"life":400,"cooldown":30,"fuse":250},
 "missile":{"dv":150,"accel":40,"burn":50,"boost":25,"life":450,"fuse":400,"damage":100,"ammo":2,"cooldown":60,
            "cone":0.6427876096865394,"range":700000,"seeker":4,"plume":2500,"cold":8,"nav":3,"close":2500,"mass":20},
 "debris":{"pieces":12,"dv":150,"radius":300,"damage":50,"max":400,"chips":4,"chipDv":40},
 "rockDamage":100,"minPoints":0,
 "dock":{"range":1000,"speed":40,"lift":1000},
 "mine":{"rate":0.08,"richRate":0.6,"yield":40,"richYield":500,"heat":10,"tank":900,"hide":0.25},
 "push":{"density":0.02},
 "ring":{"safe":20,"lethal":320,"startZ":400},
 "attitude":{"slew":0.35,"slewCos":0.9393727128473789,"slewSin":0.34289780745545134,"burnCos":0.9902680687415704,"rcs":0.04,"cost":0.02},
 "scatter":{"aim":0.0004,"speed":0.001,"drift":0.03},
 "seed":{"cost":200,"ticks":80,"heat":25,"max":6,"wakeProp":150,"wakeAmmo":4,"glow":0.1},
 "lode":{"radius":5000,"rate":1,"heat":12},
 "start":{"x":120000,"xSpread":60000,"y":220000,"gap":50000},
 "reinforce":{"delay":300,"max":99}}
```

`tickHz` is the broadcast's ticks per second at 1x. `rockDamage` and `minPoints` are unused in Season 1 (touching a
rock destroys a probe outright). Cosines (`ping.cos`, `missile.cone`, `attitude.burnCos`, `slewCos`) are of the
half-angles 15, 50 and 8 degrees and 0.35 rad.

## 12. The sandbox, determinism and limits

On the ladder your file runs in QuickJS (compiled to WebAssembly) with no network, no filesystem and no imports:
everything must be in the one file. Everything crossing the boundary is JSON: you get plain objects and must
return plain data.

- **CPU**: `tick` may use 40 interrupt units, about 10 ms of QuickJS time (counted in bytecode, so it is the same
  on every machine). Loading the file and `hello` get 4,000 units each, about a second. A tick that runs over is
  dropped: your probes get no orders that tick. A `hello` that throws or runs over stops your controller for the
  game.
- **Memory**: 32 MiB of heap, 1 MiB of stack.
- **Failures**: a tick that throws, runs over, or returns no `{ units: [...] }` gives no orders that tick; 50
  failed ticks in a row stop the controller for the rest of the game. Return `{ tick: o.tick, units: [] }` when you
  have nothing to say.
- **Time and chance**: `Math.random` is seeded from the game's seed and your side; `Date.now()`, `new Date()` and
  `performance.now()` return the tick × 50 ms. The same controller gives the same orders every time it plays the
  same game.
- **Speed**: Node runs the same code many times faster than QuickJS. As a guide, 40 units is about 3,000 steps of
  the integrator above (on a map with four moonlets), or about 0.8 ms of Node time for arithmetic code; code that
  allocates many small arrays fares better in QuickJS than that suggests. `space-test.mjs` reports your slowest
  ticks and how many took over 0.8 ms; the upload report's `budgetMaxPerTick` is the real figure (keep it under
  about 30: a full fight costs more than the quiet upload test). `Math.hypot` is slow in Node; use `Math.sqrt`.
  The starter peaks at 9 units.
- **The engine is deterministic**: its own sine and cosine, IEEE doubles, only + − × / and `Math.sqrt`; the same
  game gives the same digests in V8 and JavaScriptCore. Replays store your cleaned orders, not your code, so a game
  always plays back.

The local runner has no sandbox and no time limit; the engine in `space-sim.mjs` is the one the site runs.

## 13. Notes on play

These follow from the rules; none of them is a recipe.

- **The lode rewards being there alone.** Three cutters make 3 kg a tick; a side alone on the lode from tick 600
  to the end makes about 10,000 kg. Any enemy probe docked on it stops all cutting, yours too, so getting the other
  side off it (two hits per probe, or a reason to leave) is the whole fight.
- **A cutter is a beacon.** Steady cutting glows at about 98, visible to about 990 km from its side of the lode.
  The far side of the lode hides it from eyes, not from pings or missile seekers. A slug fired at a probe on the
  far side strikes the lode.
- **Pinging is loud.** A ping gives exact positions and velocities in its cone, and gives the enemy your exact
  position plus a 600-heat flare. Infrared bearings are free and silent; brightness plus a known light gives range.
- **Slugs or missiles.** Slugs are fast, cheap and precise if you predict the target with the integrator, but each
  shot flashes, and a target that burns during a long flight is gone. Missiles find their own way but carry only
  50 ticks of fuel: close in they often hit (the starter's, launched within 120 km at ping fixes, hit about half the
  time against the house probes); further out a target that burns sideways after the motor stops escapes.
- **Fuel.** 6,414 m/tick in a full tank, and every m/tick costs more propellant early (the tank is heavy). A
  two-burn trip from the start to the lode costs about 1,100 m/tick (some 140 kg); the starter's continuous control
  spends about 1,700 (some 220 kg). Sitting still costs nothing only on the line x = 0 (the tide is zero there); at
  x = 50 km holding position costs 0.15 m/tick² a tick, about 85 kg over a game, through the jets (and the jets
  glow: heat 1.5 a tick settles at about 48, seen from 700 km). Docked costs nothing at all.
- **Cold and dark.** Coasting cold in shadow makes a probe nearly invisible (100 km); a probe on a body is dimmer
  still and hidden from the far side.
- **Losses cost time.** A replacement arrives 300 ticks after a loss, 200 to 330 km out, and needs several hundred
  more to reach the lode.
- **Your own slugs hit your own probes**; probes on the same body never collide with each other, probes in flight
  do.

## 14. The house probes and the starter

The house probes use only what any controller gets (the published physics and their observations); their code is
in `space-sim.mjs` (`makeSpaceBot`). They guide by predicted-path transfers (Newton's method on a burn through the
integrator), a braking-limited terminal law with the natural accelerations fed forward, and aim slugs by flying
candidate shots through the integrator. Roles: a **cutter** docks on the lode, cuts, shoots back from there, leaves
when a missile closes in, and after 25 contested ticks lifts off to swing round to the far side; a **hunter** keeps
station near the lode, searches with pings and shoots what it finds; an **ambusher** waits cold near the lode and
answers what gives itself away.

| style | probes | ladder name |
|---|---|---|
| `miner` | three cutters | `house-holder` |
| `lurker` | a hunter and two cutters | `house-hunter` |
| `hunter` | two hunters and a cutter | `house-brawler` |
| `ambusher` | two ambushers and a cutter | `house-random` |
| `drifter` | does nothing at all (its probes drift with their lanes) | |
| `runner` | burns straight out of the field | |
| `rammer` | thrusts at the brightest thing it sees, pings otherwise | |
| `percher` | docks on the nearest rock and sits there | |
| `pinger` | pings all round, fires straight at what it finds (no lead) | |

**The starter** (`controller-space.js`, about 150 lines) flies each probe to its own spot just off the lode on its
side, with a speed it can still brake from (counting the 9 ticks of turning round), the natural accelerations fed
forward, coasting while its velocity error is small, and a look-ahead that steers round moonlets and rocks; it
docks and cuts. Docked probes ping along the brightest probe or flash any of them sees (one ping in 90 ticks),
launch a missile at a probe a ping found within 120 km, and shoot slugs at it after flying the slug and the target
forward through a copy of the integrator. It does not dodge, hide, refuel, manage its heat or break a contested
lode. In our runs it beats every house style; that says as much about the house probes as about the starter.

## 15. Telling us what you found

Post in the Discord (https://discord.gg/jtkXzkSKca) or write to hello@battle.training with the controller, the seed
and what happened: an order the engine accepts and should not, a rule that reads one way here and plays another,
anything that looks wrong.

**What changed.** Season 1 (`space-s1.0.0`, engine `space-0.10.1`) is the first version of these rules on a
ladder. Rule changes will get a new version string and a note here.
