Long Range Scan: the 1971 galaxy, on the terminal it was written for

An independent rebuild of the 1971 starship patrol game. Eight by eight
quadrants of eight by eight sectors, three digits a quadrant on the chart,
courses round a nine-point compass, and a stardate clock that is the real
opponent.

The name and the nouns are ours and NOTICE.md says why: the mechanics are
free to rebuild, the trademarks are not. Raiders rather than the enemy from
the television programme, beams rather than the energy weapon, and every
sentence the machine prints written for this project rather than borrowed
from a listing.

This is the 1971 skin only -- paper, ink and a print head. The remaster and
the synth come next, and the tokens and the structured transcript are already
shaped for them.
This commit is contained in:
2026-09-08 23:26:22 -07:00
commit 593bbd888f
31 changed files with 7262 additions and 0 deletions
+133
View File
@@ -0,0 +1,133 @@
/**
* The numbers, all of them, in one place.
*
* The 1971 game is arithmetic where Hunt the Wumpus is arrangement: almost
* everything here is a constant somebody typed into a BASIC listing, and the
* feel of the game is those constants rather than any one rule. They are
* reconstructed from the published behaviour of the 1978 type-in -- how much
* a warp costs, how hard a raider hits at range, how long a repair takes --
* and the places where a judgement call was needed are marked.
*/
/** Quadrants across the galaxy, and sectors across a quadrant. Both 8. */
export const GALAXY = 8
export const SECTORS = 8
export const START_ENERGY = 3000
export const START_TORPEDOES = 10
/** A patrol is short. That is the whole tension: the clock, not the shooting. */
export const MIN_DAYS = 25
export const MAX_EXTRA_DAYS = 10
/**
* How thickly raiders are scattered, quadrant by quadrant. A roll over 0.98
* puts three in one quadrant, which is very nearly a death sentence to warp
* into and is meant to be.
*/
export const RAIDER_ODDS: readonly (readonly [number, number])[] = [
[0.98, 3],
[0.95, 2],
[0.8, 1],
]
/** A starbase is rare. Most quadrants have nowhere to refit. */
export const BASE_ODDS = 0.96
/** Stars per quadrant: one to eight, and they block everything. */
export const MAX_STARS = 8
export const RAIDER_ENERGY = 200
/** Spread, so two raiders are never quite the same fight. */
export const RAIDER_ENERGY_SPREAD = 200
/**
* What a warp costs: one unit per sector crossed, plus ten to light the
* engines. That looks far too cheap until you notice where energy actually
* goes -- into the beams and into the shields. Crossing the galaxy is not the
* expensive thing. Arriving somewhere with raiders in it is.
*/
export const WARP_COST_PER_SECTOR = 1
export const WARP_COST_FIXED = 10
/** Warp engines out means you crawl: two-tenths, and no further. */
export const CRIPPLED_WARP = 0.2
export const MAX_WARP = 8
/** Below this, a beam does not get through the raider's own shields. */
export const BEAM_FLOOR = 0.15
/** Days of repair a hit costs a device, before the roll that softens it. */
export const DAMAGE_DAYS = 6
export const DAMAGE_CHANCE = 0.2
/** Docking repairs everything, in a hurry rather than instantly. */
export const DOCK_REPAIR_DAYS = 1
/** A yellow board: running out of power a long way from anywhere. */
export const LOW_ENERGY = 0.1
export const MAX_CAPTAINS = 4
export const MAX_NAME = 12
/*
* Everything the machine says, and none of it is anybody else's.
*
* The 1971 game and the 1978 type-in that carried it have famous lines in
* them, and those sentences belong to the people who wrote them. A project
* released under a copyleft licence cannot go around licensing words it did
* not write, so every line below was written for this project. See NOTICE.md,
* which is the same argument the two sibling games make.
*
* They are shouted because the machine had no lower case, not because we are
* shouting.
*/
export const HAIL_TEXT = [
'FLEET COMMAND TO PATROL VESSEL',
'RAIDERS ARE LOOSE IN ALL EIGHT BY EIGHT QUADRANTS.',
'FIND THEM AND END THEM BEFORE YOUR TIME RUNS OUT.',
]
export const CONDITION_TEXT: Record<string, string> = {
DOCKED: 'DOCKED',
RED: 'RED',
YELLOW: 'YELLOW',
GREEN: 'GREEN',
}
export const OUTCOME_TEXT: Record<string, string> = {
'mission-complete': 'THE LAST RAIDER IS GONE. THE QUADRANTS ARE QUIET.',
'out-of-time': 'THE CLOCK RUNS OUT. WHAT IS LEFT OUT THERE STAYS OUT THERE.',
destroyed: 'THE HULL OPENS. NOTHING FURTHER IS RECEIVED FROM YOU.',
stranded: 'NO POWER, NO SHIELDS, NO WAY HOME. YOU DRIFT.',
resigned: 'YOU BREAK OFF AND TURN FOR HOME.',
'base-destroyed': 'YOUR OWN TORPEDO TAKES THE STARBASE. FLEET COMMAND RELIEVES YOU.',
}
/** The eight things that can be broken, in the order the report lists them. */
export const DEVICE_NAMES: Record<string, string> = {
warp: 'WARP ENGINES',
srs: 'SHORT RANGE SENSORS',
lrs: 'LONG RANGE SENSORS',
beams: 'BEAM CONTROL',
tubes: 'TORPEDO TUBES',
repair: 'DAMAGE CONTROL',
shields: 'SHIELD CONTROL',
computer: 'COMPUTER',
}
/** What a sector looks like on paper. Three columns each, so the grid squares up. */
export const GLYPH = {
ship: '<O>',
raider: '+R+',
base: '>!<',
star: ' * ',
empty: ' ',
} as const
export const NO_SUCH_COURSE = 'COURSE MUST BE 1 THROUGH 9'
export const BLOCKED_TEXT = 'SOMETHING IS IN THE WAY. ALL STOP.'
export const EDGE_TEXT = 'THE GALAXY ENDS HERE. ALL STOP AT THE RIM.'
export const DOCKED_TEXT = 'MOORED TO THE STARBASE. TANKS FULL, TUBES FULL, SHIELDS DOWN.'
export const SHIELDS_DOWN_TEXT = 'SHIELD CONTROL IS OUT. NOTHING TO PUT IT IN.'
+224
View File
@@ -0,0 +1,224 @@
import { describe, expect, it } from 'vitest'
import { GALAXY, GLYPH, SECTORS, START_ENERGY, START_TORPEDOES } from './constants'
import { makePatrol, shortRangeScan, step } from './engine'
import { makeRng } from './rng'
import { DEVICES, type Census, type DeviceId, type Patrol } from './types'
const rng = () => makeRng(4242)
const emptyGalaxy = (): Census[][] =>
Array.from({ length: GALAXY }, () =>
Array.from({ length: GALAXY }, () => ({ raiders: 0, base: false, stars: 0 })),
)
/**
* A patrol with nothing in it, to be furnished a piece at a time. Building
* one by hand rather than dealing one is the only way to test a rule instead
* of testing the dice.
*/
function bare(over: Partial<Patrol> = {}): Patrol {
const galaxy = emptyGalaxy()
return {
day: 2000,
deadline: 2030,
galaxy,
chart: Array.from({ length: GALAXY }, () => Array.from({ length: GALAXY }, () => null)),
quadrant: { row: 0, col: 0 },
sector: { row: 0, col: 0 },
energy: START_ENERGY,
shields: 500,
torpedoes: START_TORPEDOES,
damage: Object.fromEntries(DEVICES.map((d) => [d, 0])) as Record<DeviceId, number>,
raiders: [],
stars: [],
base: null,
docked: false,
raidersLeft: 5,
raidersKilled: 0,
basesLeft: 1,
outcome: null,
...over,
}
}
describe('a dealt patrol', () => {
it('agrees with its own galaxy about how many raiders there are', () => {
for (const seed of [1, 2, 3, 99, 12345]) {
const p = makePatrol(makeRng(seed))
const actual = p.galaxy.flat().reduce((n, q) => n + q.raiders, 0)
expect(p.raidersLeft).toBe(actual)
expect(p.raidersKilled).toBe(0)
expect(p.outcome).toBeNull()
}
})
it('charts the quadrant it starts in, and nothing else', () => {
const p = makePatrol(makeRng(5))
const charted = p.chart.flat().filter((c) => c !== null)
expect(charted).toHaveLength(1)
expect(p.chart[p.quadrant.row]![p.quadrant.col]).not.toBeNull()
})
})
describe('the short range scan', () => {
it('prints eight rows between two rules, with the ship on one of them', () => {
const p = bare({ sector: { row: 2, col: 3 } })
const lines = shortRangeScan(p)
expect(lines).toHaveLength(SECTORS + 2)
expect(lines[3]!.text).toContain(GLYPH.ship)
})
it('refuses when the sensors are out, rather than guessing', () => {
const damage = { ...bare().damage, srs: 3 }
const lines = shortRangeScan(bare({ damage }))
expect(lines).toHaveLength(1)
expect(lines[0]!.text).toContain('SENSORS ARE OUT')
})
})
describe('warp', () => {
it('crosses eight sectors for every whole warp factor', () => {
const { patrol } = step(bare(), { type: 'nav', course: 1, warp: 1 }, rng())
// Eight sectors east from 1,1 is the first sector of the next quadrant.
expect(patrol.quadrant).toEqual({ row: 0, col: 1 })
expect(patrol.sector).toEqual({ row: 0, col: 0 })
})
it('stops at the rim rather than falling off it', () => {
const { patrol, lines } = step(bare(), { type: 'nav', course: 5, warp: 2 }, rng())
expect(patrol.quadrant).toEqual({ row: 0, col: 0 })
expect(patrol.sector).toEqual({ row: 0, col: 0 })
expect(lines.some((l) => l.text.includes('GALAXY ENDS'))).toBe(true)
})
it('stops short of anything in the way', () => {
const p = bare({ stars: [{ row: 0, col: 2 }] })
const { patrol, lines } = step(p, { type: 'nav', course: 1, warp: 0.25 }, rng())
expect(patrol.sector).toEqual({ row: 0, col: 1 })
expect(lines.some((l) => l.text.includes('IN THE WAY'))).toBe(true)
})
it('refuses more than a crawl when the engines are out', () => {
const damage = { ...bare().damage, warp: 4 }
const p = bare({ damage })
const { patrol, lines } = step(p, { type: 'nav', course: 1, warp: 3 }, rng())
expect(patrol.sector).toEqual(p.sector)
expect(lines[0]!.text).toContain('WARP ENGINES ARE OUT')
})
it('spends a day, and a day is what repairs things', () => {
const damage = { ...bare().damage, lrs: 0.5 }
const { patrol } = step(bare({ damage }), { type: 'nav', course: 7, warp: 1 }, rng())
expect(patrol.day).toBe(2001)
expect(patrol.damage.lrs).toBe(0)
})
})
describe('mooring', () => {
it('fills the tanks and the racks when you pull up beside a starbase', () => {
const p = bare({ base: { row: 0, col: 3 }, energy: 40, torpedoes: 1, shields: 300 })
const { patrol } = step(p, { type: 'nav', course: 1, warp: 0.25 }, rng())
expect(patrol.docked).toBe(true)
expect(patrol.energy).toBe(START_ENERGY)
expect(patrol.torpedoes).toBe(START_TORPEDOES)
expect(patrol.shields).toBe(0)
})
})
describe('torpedoes', () => {
it('take a raider off the board and off the count', () => {
const p = bare({
raidersLeft: 1,
raiders: [{ at: { row: 0, col: 4 }, energy: 300 }],
galaxy: (() => {
const g = emptyGalaxy()
g[0]![0] = { raiders: 1, base: false, stars: 0 }
return g
})(),
})
const { patrol } = step(p, { type: 'torpedo', course: 1 }, rng())
expect(patrol.raiders).toHaveLength(0)
expect(patrol.raidersKilled).toBe(1)
expect(patrol.raidersLeft).toBe(0)
expect(patrol.torpedoes).toBe(START_TORPEDOES - 1)
// Nothing left anywhere is the end of it.
expect(patrol.outcome).toBe('mission-complete')
})
it('are swallowed by a star, and the star is still there', () => {
const p = bare({ stars: [{ row: 0, col: 3 }] })
const { patrol, lines } = step(p, { type: 'torpedo', course: 1 }, rng())
expect(lines.some((l) => l.text.includes('SWALLOWS'))).toBe(true)
expect(patrol.stars).toHaveLength(1)
expect(patrol.outcome).toBeNull()
})
it('end the patrol if they take the starbase', () => {
const p = bare({ base: { row: 0, col: 5 } })
const { patrol } = step(p, { type: 'torpedo', course: 1 }, rng())
expect(patrol.outcome).toBe('base-destroyed')
})
it('are refused when the racks are empty, at no cost', () => {
const p = bare({ torpedoes: 0 })
const { patrol, lines } = step(p, { type: 'torpedo', course: 1 }, rng())
expect(patrol.torpedoes).toBe(0)
expect(lines[0]!.text).toContain('RACKS ARE EMPTY')
})
})
describe('being shot at', () => {
it('ends the patrol when the shields are gone', () => {
const p = bare({
shields: 1,
raiders: [{ at: { row: 0, col: 1 }, energy: 400 }],
})
const { patrol } = step(p, { type: 'beams', energy: 1 }, rng())
expect(patrol.outcome).toBe('destroyed')
})
it('does not happen at all while moored', () => {
const p = bare({
base: { row: 0, col: 1 },
docked: true,
shields: 1,
raiders: [{ at: { row: 0, col: 2 }, energy: 400 }],
})
const { patrol, lines } = step(p, { type: 'beams', energy: 1 }, rng())
expect(patrol.outcome).toBeNull()
expect(lines.some((l) => l.text.includes('STARBASE TAKES THE FIRE'))).toBe(true)
})
})
describe('the clock', () => {
it('ends the patrol when the orders expire', () => {
const p = bare({ day: 2029.5, deadline: 2030 })
const { patrol } = step(p, { type: 'nav', course: 7, warp: 1 }, rng())
expect(patrol.outcome).toBe('out-of-time')
})
})
describe('running dry', () => {
it('takes the last of it out of the shields before giving up', () => {
const p = bare({ energy: 5, shields: 400 })
const { patrol } = step(p, { type: 'nav', course: 7, warp: 1 }, rng())
expect(patrol.energy).toBe(0)
expect(patrol.shields).toBeLessThan(400)
expect(patrol.outcome).toBeNull()
})
it('strands you when there is nothing left in either', () => {
const p = bare({ energy: 5, shields: 2 })
const { patrol } = step(p, { type: 'nav', course: 7, warp: 1 }, rng())
expect(patrol.outcome).toBe('stranded')
})
})
describe('a finished patrol', () => {
it('takes no further commands', () => {
const p = bare({ outcome: 'resigned' })
const { patrol, lines } = step(p, { type: 'nav', course: 1, warp: 4 }, rng())
expect(patrol).toBe(p)
expect(lines).toHaveLength(0)
})
})
+634
View File
@@ -0,0 +1,634 @@
import {
BEAM_FLOOR,
BLOCKED_TEXT,
CRIPPLED_WARP,
DAMAGE_CHANCE,
DAMAGE_DAYS,
DEVICE_NAMES,
DOCKED_TEXT,
DOCK_REPAIR_DAYS,
EDGE_TEXT,
GALAXY,
GLYPH,
LOW_ENERGY,
MAX_WARP,
MIN_DAYS,
MAX_EXTRA_DAYS,
NO_SUCH_COURSE,
OUTCOME_TEXT,
SECTORS,
SHIELDS_DOWN_TEXT,
START_ENERGY,
START_TORPEDOES,
WARP_COST_FIXED,
WARP_COST_PER_SECTOR,
} from './constants'
import {
adjacent,
censusCode,
distance,
heading,
inGalaxy,
layQuadrant,
makeGalaxy,
occupant,
randomCoord,
same,
} from './galaxy'
import type { Rng } from './rng'
import {
DEVICES,
type Captain,
type Command,
type Condition,
type Coord,
type DeviceId,
type Line,
type Outcome,
type Patrol,
} from './types'
export const randomSeed = () => Math.floor(Math.random() * 0x7fffffff)
const line = (kind: Line['kind'], text: string): Line => ({ kind, text })
/** One-based, and printed the way the machine prints it: row then column. */
const say = (c: Coord) => `${c.row + 1},${c.col + 1}`
const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n))
/** Sectors are whole; a course is not. Round on arrival, never on the way. */
const round = (c: Coord): Coord => ({ row: Math.round(c.row), col: Math.round(c.col) })
// ---------------------------------------------------------------- setting up
export function makePatrol(rng: Rng): Patrol {
const { galaxy, raiders, bases } = makeGalaxy(rng)
const day = (20 + Math.floor(rng() * 20)) * 100
const damage = Object.fromEntries(DEVICES.map((d) => [d, 0])) as Record<DeviceId, number>
const patrol: Patrol = {
day,
deadline: day + MIN_DAYS + Math.floor(rng() * MAX_EXTRA_DAYS),
galaxy,
chart: Array.from({ length: GALAXY }, () => Array.from({ length: GALAXY }, () => null)),
quadrant: randomCoord(rng, GALAXY),
sector: randomCoord(rng),
energy: START_ENERGY,
shields: 0,
torpedoes: START_TORPEDOES,
damage,
raiders: [],
stars: [],
base: null,
docked: false,
raidersLeft: raiders,
raidersKilled: 0,
basesLeft: bases,
outcome: null,
}
return arrive(patrol, rng).patrol
}
/**
* Come out of warp: lay the quadrant out, write it on the chart, and find out
* whether anything here has noticed. Being in a quadrant is what charts it --
* the long range scan is for the eight you are *not* in.
*/
export function arrive(patrol: Patrol, rng: Rng): { patrol: Patrol; lines: Line[] } {
let next = layQuadrant(patrol, rng)
const { row, col } = next.quadrant
const chart = next.chart.map((r) => r.slice())
chart[row]![col] = { ...next.galaxy[row]![col]! }
next = { ...next, chart }
const lines: Line[] = []
next = redock(next, lines)
if (next.raiders.length > 0 && !next.docked) {
lines.push(
line(
'hit',
`CONDITION RED. ${next.raiders.length} RAIDER${next.raiders.length > 1 ? 'S' : ''} IN THIS QUADRANT.`,
),
)
}
return { patrol: next, lines }
}
/** Moored, if there is a starbase in the next sector over. */
function redock(patrol: Patrol, lines: Line[]): Patrol {
const docked = patrol.base !== null && adjacent(patrol.sector, patrol.base)
if (!docked) return { ...patrol, docked: false }
if (patrol.docked) return patrol
lines.push(line('system', DOCKED_TEXT))
const damage = { ...patrol.damage }
for (const d of DEVICES) damage[d] = Math.max(0, damage[d] - DOCK_REPAIR_DAYS)
return {
...patrol,
docked: true,
energy: START_ENERGY,
torpedoes: START_TORPEDOES,
shields: 0,
damage,
}
}
export function condition(patrol: Patrol): Condition {
if (patrol.docked) return 'DOCKED'
if (patrol.raiders.length > 0) return 'RED'
if (patrol.energy < START_ENERGY * LOW_ENERGY) return 'YELLOW'
return 'GREEN'
}
// ------------------------------------------------------------------- scanning
/**
* The short range scan, and the status board printed down its right-hand side.
*
* Eight rows of sectors and eight facts about the ship, one to a row, because
* that is what fits on a line of paper and because a printing terminal has no
* second place to put anything. This is the screen of the game: everything a
* captain decides is decided off these eleven lines.
*/
export function shortRangeScan(patrol: Patrol): Line[] {
if (patrol.damage.srs > 0) {
return [line('system', 'SHORT RANGE SENSORS ARE OUT. NOTHING TO SEE BY.')]
}
const status = [
`STARDATE ${patrol.day.toFixed(1)}`,
`CONDITION ${condition(patrol)}`,
`QUADRANT ${say(patrol.quadrant)}`,
`SECTOR ${say(patrol.sector)}`,
`ENERGY ${Math.round(patrol.energy)}`,
`SHIELDS ${Math.round(patrol.shields)}`,
`TORPEDOES ${patrol.torpedoes}`,
`RAIDERS ${patrol.raidersLeft}`,
]
const rule = '-'.repeat(SECTORS * 4 + 1)
const lines = [line('scan', rule)]
for (let row = 0; row < SECTORS; row++) {
let text = ''
for (let col = 0; col < SECTORS; col++) {
const who = occupant(patrol, { row, col })
text +=
who === 'ship'
? GLYPH.ship
: who === 'raider'
? GLYPH.raider
: who === 'base'
? GLYPH.base
: who === 'star'
? GLYPH.star
: GLYPH.empty
text += ' '
}
lines.push(line('scan', `${text} ${status[row]}`))
}
lines.push(line('scan', rule))
return lines
}
/**
* The long range scan: three digits a quadrant, for the nine quadrants
* centred on this one. Raiders, starbases, stars, in that order and no
* spaces -- 205 is two raiders, no base, five stars, and reading those three
* digits at a glance is the skill the whole game is built on.
*/
export function longRangeScan(patrol: Patrol): { patrol: Patrol; lines: Line[] } {
if (patrol.damage.lrs > 0) {
return { patrol, lines: [line('system', 'LONG RANGE SENSORS ARE OUT.')] }
}
const chart = patrol.chart.map((r) => r.slice())
const lines: Line[] = [line('scan', `LONG RANGE SCAN FOR QUADRANT ${say(patrol.quadrant)}`)]
const rule = '-------------------'
lines.push(line('scan', rule))
for (let dr = -1; dr <= 1; dr++) {
let text = ':'
for (let dc = -1; dc <= 1; dc++) {
const q = { row: patrol.quadrant.row + dr, col: patrol.quadrant.col + dc }
if (!inGalaxy(q)) {
text += ' *** :'
continue
}
const census = patrol.galaxy[q.row]![q.col]!
chart[q.row]![q.col] = { ...census }
text += ` ${censusCode(census)} :`
}
lines.push(line('scan', text))
lines.push(line('scan', rule))
}
return { patrol: { ...patrol, chart }, lines }
}
/** What the computer has been told, all sixty-four quadrants of it. */
export function galaxyChart(patrol: Patrol): Line[] {
if (patrol.damage.computer > 0) {
return [line('system', 'THE COMPUTER IS DOWN. THE CHART IS IN IT.')]
}
const lines = [
line('scan', 'CHART OF THE GALAXY AS RECORDED'),
line('scan', ' 1 2 3 4 5 6 7 8'),
]
for (let row = 0; row < GALAXY; row++) {
let text = `${row + 1} `
for (let col = 0; col < GALAXY; col++) text += ` ${censusCode(patrol.chart[row]![col]!)} `
lines.push(line('scan', text))
}
lines.push(
line('scan', `RAIDERS LEFT ${patrol.raidersLeft} DAYS LEFT ${daysLeft(patrol).toFixed(1)}`),
)
return lines
}
export function damageReport(patrol: Patrol): Line[] {
const broken = DEVICES.filter((d) => patrol.damage[d] > 0)
if (broken.length === 0) return [line('damage', 'ALL SYSTEMS ANSWER.')]
return [
line('damage', 'DEVICE DAYS TO REPAIR'),
...broken.map((d) =>
line('damage', `${DEVICE_NAMES[d]!.padEnd(20)}${patrol.damage[d]!.toFixed(1)}`),
),
]
}
export const daysLeft = (patrol: Patrol) => Math.max(0, patrol.deadline - patrol.day)
// -------------------------------------------------------------------- fighting
/**
* Everything still alive in this quadrant shoots back.
*
* A raider hits harder the closer it is and spends itself doing it, which is
* the only reason a long fight is ever winnable: sit at range and you take
* less and give less, close in and it is settled either way in two exchanges.
*/
function raidersFire(patrol: Patrol, rng: Rng, lines: Line[]): Patrol {
if (patrol.raiders.length === 0) return patrol
if (patrol.docked) {
lines.push(line('hit', 'THE STARBASE TAKES THE FIRE FOR YOU.'))
return patrol
}
let shields = patrol.shields
const damage = { ...patrol.damage }
const raiders = patrol.raiders.map((k) => ({ ...k }))
for (const k of raiders) {
const range = Math.max(1, distance(k.at, patrol.sector))
const hit = Math.floor((k.energy / range) * (2 + rng()))
shields -= hit
k.energy /= 3 + rng()
lines.push(
line(
'hit',
`${hit} UNIT HIT FROM THE RAIDER AT ${say(k.at)}. SHIELDS AT ${Math.max(0, Math.round(shields))}.`,
),
)
if (shields <= 0) break
if (rng() < DAMAGE_CHANCE) {
const d = DEVICES[Math.floor(rng() * DEVICES.length)]!
damage[d] += DAMAGE_DAYS * rng() + 1
lines.push(line('damage', `${DEVICE_NAMES[d]} DAMAGED.`))
}
}
const next = { ...patrol, shields: Math.max(0, shields), damage, raiders }
if (shields <= 0) {
lines.push(line('end', 'SHIELDS ARE GONE.'))
return { ...next, outcome: 'destroyed' }
}
return next
}
/** Take a raider off the board, here and in the galaxy's own count. */
function killRaider(patrol: Patrol, at: Coord): Patrol {
const galaxy = patrol.galaxy.map((r) => r.map((c) => ({ ...c })))
const q = galaxy[patrol.quadrant.row]![patrol.quadrant.col]!
q.raiders = Math.max(0, q.raiders - 1)
const chart = patrol.chart.map((r) => r.slice())
chart[patrol.quadrant.row]![patrol.quadrant.col] = { ...q }
return {
...patrol,
galaxy,
chart,
raiders: patrol.raiders.filter((k) => !same(k.at, at)),
raidersLeft: Math.max(0, patrol.raidersLeft - 1),
raidersKilled: patrol.raidersKilled + 1,
}
}
function fireBeams(patrol: Patrol, amount: number, rng: Rng): { patrol: Patrol; lines: Line[] } {
const lines: Line[] = []
if (patrol.damage.beams > 0) return { patrol, lines: [line('system', 'BEAM CONTROL IS OUT.')] }
if (patrol.raiders.length === 0) {
return { patrol, lines: [line('system', 'NOTHING IN THIS QUADRANT TO SHOOT AT.')] }
}
const spend = clamp(Math.floor(amount), 0, Math.floor(patrol.energy))
if (spend <= 0) return { patrol, lines: [line('system', 'NO ENERGY RELEASED.')] }
let next: Patrol = { ...patrol, energy: patrol.energy - spend }
lines.push(line('fire', `BEAMS FIRED. ${spend} UNITS RELEASED.`))
// A blind shot is a worse shot. The computer is what spreads the energy
// across the targets; without it you are pointing the ship and hoping.
let effective = spend
if (next.damage.computer > 0) {
effective = spend * 0.6
lines.push(line('system', 'WITHOUT THE COMPUTER THE SPREAD IS WIDE.'))
}
const share = effective / next.raiders.length
// A snapshot: killRaider rewrites next.raiders underneath this loop.
const targets = next.raiders.slice()
for (const k of targets) {
const range = Math.max(1, distance(k.at, next.sector))
const hit = Math.floor((share * (2 + rng())) / range)
if (hit <= k.energy * BEAM_FLOOR) {
lines.push(line('fire', `THE RAIDER AT ${say(k.at)} SHRUGS IT OFF.`))
continue
}
const left = k.energy - hit
if (left <= 0) {
lines.push(line('fire', `THE RAIDER AT ${say(k.at)} COMES APART.`))
next = killRaider(next, k.at)
} else {
next = {
...next,
raiders: next.raiders.map((r) => (same(r.at, k.at) ? { ...r, energy: left } : r)),
}
lines.push(line('fire', `${hit} UNITS ONTO THE RAIDER AT ${say(k.at)}.`))
}
}
return { patrol: raidersFire(next, rng, lines), lines }
}
/**
* One torpedo, one course, and no guidance at all: it goes where it is
* pointed until it meets something. Meeting a star means the star wins, and
* meeting the starbase means the patrol is over in the worst way there is.
*/
function fireTorpedo(patrol: Patrol, course: number, rng: Rng): { patrol: Patrol; lines: Line[] } {
if (patrol.damage.tubes > 0) return { patrol, lines: [line('system', 'THE TUBES ARE OUT.')] }
if (patrol.torpedoes <= 0) return { patrol, lines: [line('system', 'THE RACKS ARE EMPTY.')] }
if (!(course >= 1 && course <= 9)) return { patrol, lines: [line('system', NO_SUCH_COURSE)] }
const lines: Line[] = [line('fire', 'TORPEDO AWAY.')]
let next: Patrol = { ...patrol, torpedoes: patrol.torpedoes - 1 }
const step = heading(course)
let at = { row: next.sector.row, col: next.sector.col }
for (;;) {
at = { row: at.row + step.row, col: at.col + step.col }
const cell = round(at)
if (cell.row < 0 || cell.row >= SECTORS || cell.col < 0 || cell.col >= SECTORS) {
lines.push(line('fire', 'THE TORPEDO LEAVES THE QUADRANT AND KEEPS GOING.'))
break
}
const who = occupant(next, cell)
if (who === 'raider') {
lines.push(line('fire', `DIRECT HIT. THE RAIDER AT ${say(cell)} IS GONE.`))
next = killRaider(next, cell)
break
}
if (who === 'star') {
lines.push(line('fire', `THE STAR AT ${say(cell)} SWALLOWS IT.`))
break
}
if (who === 'base') {
lines.push(line('end', `THE STARBASE AT ${say(cell)} IS GONE.`))
return { patrol: { ...next, outcome: 'base-destroyed' }, lines }
}
}
return { patrol: raidersFire(next, rng, lines), lines }
}
// -------------------------------------------------------------------- moving
/**
* Warp.
*
* The whole move happens in galaxy coordinates -- sixty-four sectors on a
* side -- because a course does not stop at a quadrant boundary and neither
* should the arithmetic. Blocking only applies inside the quadrant you can
* actually see: the ship has no idea what is in the next one until it gets
* there, which is exactly the bargain the game is offering.
*/
function navigate(
patrol: Patrol,
course: number,
warp: number,
rng: Rng,
): { patrol: Patrol; lines: Line[] } {
if (!(course >= 1 && course <= 9)) return { patrol, lines: [line('system', NO_SUCH_COURSE)] }
if (patrol.damage.warp > 0 && warp > CRIPPLED_WARP) {
return {
patrol,
lines: [line('system', `WARP ENGINES ARE OUT. ${CRIPPLED_WARP} IS ALL THERE IS.`)],
}
}
const w = clamp(warp, 0, MAX_WARP)
const sectors = Math.round(w * SECTORS)
if (sectors <= 0) return { patrol, lines: [line('system', 'ALL STOP.')] }
const lines: Line[] = []
const step = heading(course)
const startQuadrant = patrol.quadrant
let pos = {
row: patrol.quadrant.row * SECTORS + patrol.sector.row,
col: patrol.quadrant.col * SECTORS + patrol.sector.col,
}
for (let i = 0; i < sectors; i++) {
const next = { row: pos.row + step.row, col: pos.col + step.col }
const cell = round(next)
if (cell.row < 0 || cell.row >= GALAXY * SECTORS || cell.col < 0 || cell.col >= GALAXY * SECTORS) {
lines.push(line('move', EDGE_TEXT))
break
}
const q = { row: Math.floor(cell.row / SECTORS), col: Math.floor(cell.col / SECTORS) }
if (same(q, startQuadrant)) {
const local = { row: cell.row % SECTORS, col: cell.col % SECTORS }
if (occupant(patrol, local) !== null && !same(local, patrol.sector)) {
lines.push(line('move', BLOCKED_TEXT))
break
}
}
pos = next
}
const cell = round(pos)
const quadrant = { row: Math.floor(cell.row / SECTORS), col: Math.floor(cell.col / SECTORS) }
const sector = { row: cell.row % SECTORS, col: cell.col % SECTORS }
const moved = !same(quadrant, startQuadrant)
const cost = sectors * WARP_COST_PER_SECTOR + WARP_COST_FIXED
const days = w >= 1 ? 1 : Math.round(w * 10) / 10
let next: Patrol = { ...patrol, quadrant, sector, energy: patrol.energy - cost }
// Out of power is not out of options while there is anything in the
// shields; the original let you cannibalise them and so does this.
if (next.energy < 0) {
const short = -next.energy
next = { ...next, energy: 0, shields: next.shields - short }
if (next.shields <= 0) {
lines.push(line('end', 'THE LAST OF THE POWER GOES INTO THE ENGINES.'))
return { patrol: { ...next, shields: 0, outcome: 'stranded' }, lines }
}
lines.push(line('system', 'SHIELD POWER DIVERTED TO THE ENGINES.'))
}
next = passDays(next, days, rng, lines)
if (moved) {
lines.push(line('move', `WARP ${w} TO QUADRANT ${say(quadrant)}, SECTOR ${say(sector)}.`))
const arrived = arrive(next, rng)
next = arrived.patrol
lines.push(...arrived.lines)
} else {
lines.push(line('move', `SECTOR ${say(sector)}.`))
next = redock(next, lines)
}
if (next.outcome) return { patrol: next, lines }
return { patrol: raidersFire(next, rng, lines), lines }
}
/**
* Time passing, which is the only thing that repairs anything.
*
* Damage control works while the ship flies; it does not work while you sit
* still thinking, because sitting still costs no days. That is why a badly
* hurt ship has to keep moving, and why the temptation to limp to a starbase
* at warp 0.2 is a real decision rather than a formality.
*/
function passDays(patrol: Patrol, days: number, rng: Rng, lines: Line[]): Patrol {
const damage = { ...patrol.damage }
for (const d of DEVICES) {
if (damage[d] <= 0) continue
damage[d] = Math.max(0, damage[d] - days)
if (damage[d] === 0) lines.push(line('damage', `${DEVICE_NAMES[d]} BACK ON LINE.`))
}
// Damage control occasionally finds something, or breaks something.
if (patrol.damage.repair === 0 && rng() < 0.1) {
const d = DEVICES[Math.floor(rng() * DEVICES.length)]!
if (damage[d] > 0) {
damage[d] = 0
lines.push(line('damage', `DAMAGE CONTROL HAS ${DEVICE_NAMES[d]} WORKING AGAIN.`))
}
}
return { ...patrol, day: patrol.day + days, damage }
}
function setShields(patrol: Patrol, amount: number): { patrol: Patrol; lines: Line[] } {
if (patrol.damage.shields > 0) return { patrol, lines: [line('system', SHIELDS_DOWN_TEXT)] }
const pool = patrol.energy + patrol.shields
const shields = clamp(Math.floor(amount), 0, Math.floor(pool))
return {
patrol: { ...patrol, shields, energy: pool - shields },
lines: [line('system', `SHIELDS AT ${shields}. ENERGY AT ${Math.round(pool - shields)}.`)],
}
}
// ---------------------------------------------------------------------- turn
/** Whatever the patrol has run out of, said once and only once. */
function settle(patrol: Patrol, lines: Line[]): Patrol {
if (patrol.outcome) return patrol
if (patrol.raidersLeft <= 0) {
lines.push(line('win', 'THE LAST OF THEM IS OFF THE BOARD.'))
return { ...patrol, outcome: 'mission-complete' }
}
if (patrol.day >= patrol.deadline) {
lines.push(line('end', 'THE ORDERS EXPIRE.'))
return { ...patrol, outcome: 'out-of-time' }
}
if (patrol.energy <= 0 && patrol.shields <= 0) {
lines.push(line('end', 'EVERY LAST UNIT IS SPENT.'))
return { ...patrol, outcome: 'stranded' }
}
return patrol
}
/** One command, and everything it sets off. The only way the patrol changes. */
export function step(patrol: Patrol, cmd: Command, rng: Rng): { patrol: Patrol; lines: Line[] } {
if (patrol.outcome) return { patrol, lines: [] }
let out: { patrol: Patrol; lines: Line[] }
switch (cmd.type) {
case 'nav':
out = navigate(patrol, cmd.course, cmd.warp, rng)
break
case 'srs':
out = { patrol, lines: shortRangeScan(patrol) }
break
case 'lrs':
out = longRangeScan(patrol)
break
case 'beams':
out = fireBeams(patrol, cmd.energy, rng)
break
case 'torpedo':
out = fireTorpedo(patrol, cmd.course, rng)
break
case 'shields':
out = setShields(patrol, cmd.energy)
break
case 'damage':
out = { patrol, lines: damageReport(patrol) }
break
case 'chart':
out = { patrol, lines: galaxyChart(patrol) }
break
case 'resign':
out = { patrol: { ...patrol, outcome: 'resigned' }, lines: [] }
break
}
const lines = [...out.lines]
return { patrol: settle(out.patrol, lines), lines }
}
/** What to print when a patrol ends. The words are in constants.ts. */
export const outcomeText = (o: Outcome): string => OUTCOME_TEXT[o] ?? ''
/**
* The standings, and the same order the shared board ranks in: raiders
* destroyed first, then days you did not need, then torpedoes you did not
* fire. Two captains who cleared the galaxy are separated by how fast, and
* then by how tidily.
*/
export const comparePatrols = (a: Captain, b: Captain): number =>
b.killed - a.killed || b.daysLeft - a.daysLeft || b.torpedoes - a.torpedoes
+106
View File
@@ -0,0 +1,106 @@
import { describe, expect, it } from 'vitest'
import { GALAXY, RAIDER_ODDS, SECTORS } from './constants'
import { adjacent, censusCode, heading, layQuadrant, makeGalaxy, same } from './galaxy'
import { makeRng } from './rng'
import type { Census, Patrol } from './types'
/**
* The galaxy is arithmetic, so it can be checked rather than trusted. These
* are the facts the rest of the game leans on without ever re-testing them.
*/
describe('the compass', () => {
it('puts the four cardinals where the printed grid wants them', () => {
expect(heading(1)).toEqual({ row: 0, col: 1 }) // east, along the row
expect(heading(3)).toEqual({ row: -1, col: 0 }) // north, up the page
expect(heading(5)).toEqual({ row: 0, col: -1 })
expect(heading(7)).toEqual({ row: 1, col: 0 })
})
it('closes the circle, so 9 is 1 again', () => {
expect(heading(9)).toEqual(heading(1))
})
it('interpolates between the spokes', () => {
// Halfway from east to north-east is half a row up and a whole column on.
expect(heading(1.5)).toEqual({ row: -0.5, col: 1 })
})
})
describe('a scattered galaxy', () => {
it('is always worth flying: at least one raider and one base', () => {
// The scatter is thin enough that an empty galaxy is not a freak event,
// which is exactly why the fix-ups exist.
for (let seed = 1; seed <= 200; seed++) {
const { galaxy, raiders, bases } = makeGalaxy(makeRng(seed))
expect(raiders).toBeGreaterThan(0)
expect(bases).toBeGreaterThan(0)
expect(galaxy.flat().reduce((n, q) => n + q.raiders, 0)).toBe(raiders)
expect(galaxy.flat().filter((q) => q.base).length).toBe(bases)
}
})
it('is eight by eight, and every quadrant has at least one star', () => {
const { galaxy } = makeGalaxy(makeRng(7))
expect(galaxy).toHaveLength(GALAXY)
for (const row of galaxy) {
expect(row).toHaveLength(GALAXY)
for (const q of row) {
expect(q.stars).toBeGreaterThan(0)
expect(q.raiders).toBeLessThanOrEqual(RAIDER_ODDS[0]![1])
}
}
})
})
describe('the three-digit code', () => {
it('reads raiders, starbases, stars, in that order', () => {
expect(censusCode({ raiders: 2, base: false, stars: 5 })).toBe('205')
expect(censusCode({ raiders: 0, base: true, stars: 1 })).toBe('011')
})
it('says nothing at all about a quadrant nobody has scanned', () => {
expect(censusCode(null)).toBe('***')
})
})
const emptyGalaxy = (): Census[][] =>
Array.from({ length: GALAXY }, () =>
Array.from({ length: GALAXY }, () => ({ raiders: 0, base: false, stars: 0 })),
)
describe('laying out a quadrant', () => {
it('puts down exactly what the census says, and never on top of anything', () => {
const galaxy = emptyGalaxy()
galaxy[0]![0] = { raiders: 3, base: true, stars: 8 }
const patrol = {
galaxy,
quadrant: { row: 0, col: 0 },
sector: { row: 4, col: 4 },
raiders: [],
stars: [],
base: null,
} as unknown as Patrol
const laid = layQuadrant(patrol, makeRng(11))
expect(laid.raiders).toHaveLength(3)
expect(laid.stars).toHaveLength(8)
expect(laid.base).not.toBeNull()
const all = [...laid.raiders.map((r) => r.at), ...laid.stars, laid.base!, laid.sector]
for (const a of all) {
expect(a.row).toBeGreaterThanOrEqual(0)
expect(a.row).toBeLessThan(SECTORS)
expect(all.filter((b) => same(a, b))).toHaveLength(1)
}
})
})
describe('mooring', () => {
it('counts the corners, and does not count standing on it', () => {
expect(adjacent({ row: 3, col: 3 }, { row: 2, col: 2 })).toBe(true)
expect(adjacent({ row: 3, col: 3 }, { row: 3, col: 5 })).toBe(false)
expect(adjacent({ row: 3, col: 3 }, { row: 3, col: 3 })).toBe(false)
})
})
+159
View File
@@ -0,0 +1,159 @@
import {
BASE_ODDS,
GALAXY,
MAX_STARS,
RAIDER_ENERGY,
RAIDER_ENERGY_SPREAD,
RAIDER_ODDS,
SECTORS,
} from './constants'
import type { Rng } from './rng'
import type { Census, Coord, Patrol, Raider } from './types'
/**
* The compass, and the one piece of this game most people misremember.
*
* Courses run 1 to 9 anticlockwise with 1 pointing along the row -- east, if
* you are looking at the printed grid -- and 9 is 1 again, so that a course of
* 8.5 has somewhere to go. A course is not an angle in degrees and never was:
* the whole point is that you can hold the nine of them in your head while
* reading a scan, and steer by counting round.
*
* Rows increase downward, because the grid is printed rather than plotted.
*/
const COMPASS: readonly Coord[] = [
{ row: 0, col: 1 }, // 1 east
{ row: -1, col: 1 }, // 2
{ row: -1, col: 0 }, // 3 north
{ row: -1, col: -1 }, // 4
{ row: 0, col: -1 }, // 5 west
{ row: 1, col: -1 }, // 6
{ row: 1, col: 0 }, // 7 south
{ row: 1, col: 1 }, // 8
{ row: 0, col: 1 }, // 9 east again
]
/** The unit step for a course, interpolating between the nine spokes. */
export function heading(course: number): Coord {
const i = Math.min(Math.floor(course), 8)
const f = course - i
const a = COMPASS[i - 1]!
const b = COMPASS[i]!
return { row: a.row + (b.row - a.row) * f, col: a.col + (b.col - a.col) * f }
}
export const inGalaxy = (c: Coord) =>
c.row >= 0 && c.row < GALAXY && c.col >= 0 && c.col < GALAXY
export const inQuadrant = (c: Coord) =>
c.row >= 0 && c.row < SECTORS && c.col >= 0 && c.col < SECTORS
export const same = (a: Coord, b: Coord) => a.row === b.row && a.col === b.col
export const distance = (a: Coord, b: Coord) =>
Math.sqrt((a.row - b.row) ** 2 + (a.col - b.col) ** 2)
/** Two sectors touching, corners included. What docking means. */
export const adjacent = (a: Coord, b: Coord) =>
!same(a, b) && Math.abs(a.row - b.row) <= 1 && Math.abs(a.col - b.col) <= 1
const pick = (rng: Rng, n: number) => Math.floor(rng() * n)
export const randomCoord = (rng: Rng, n = SECTORS): Coord => ({
row: pick(rng, n),
col: pick(rng, n),
})
function censusFor(rng: Rng): Census {
const roll = rng()
let raiders = 0
for (const [over, n] of RAIDER_ODDS) {
if (roll > over) {
raiders = n
break
}
}
return { raiders, base: rng() > BASE_ODDS, stars: 1 + pick(rng, MAX_STARS) }
}
/**
* Scatter the galaxy.
*
* Two fix-ups afterwards, both of which the original also needed: a galaxy
* with no raiders in it is not a patrol, and a galaxy with no starbase in it
* is not survivable. Rolling until the scatter happens to be playable would
* bias every other quadrant; placing the missing one is honest about what it
* is.
*/
export function makeGalaxy(rng: Rng): { galaxy: Census[][]; raiders: number; bases: number } {
const galaxy: Census[][] = []
for (let row = 0; row < GALAXY; row++) {
const line: Census[] = []
for (let col = 0; col < GALAXY; col++) line.push(censusFor(rng))
galaxy.push(line)
}
let raiders = galaxy.flat().reduce((n, q) => n + q.raiders, 0)
let bases = galaxy.flat().filter((q) => q.base).length
if (raiders === 0) {
const c = randomCoord(rng, GALAXY)
galaxy[c.row]![c.col]!.raiders = 1
raiders = 1
}
if (bases === 0) {
const c = randomCoord(rng, GALAXY)
galaxy[c.row]![c.col]!.base = true
bases = 1
}
return { galaxy, raiders, bases }
}
/** A three-digit quadrant code: raiders, starbases, stars. Unscanned is stars. */
export const censusCode = (c: Census | null): string =>
c === null ? '***' : `${Math.min(c.raiders, 9)}${c.base ? 1 : 0}${Math.min(c.stars, 9)}`
/**
* Lay out the quadrant the ship has just arrived in.
*
* The census says how many of each; where they go is decided now and
* forgotten on the way out. That is the original's behaviour and it is worth
* keeping rather than tidying: a quadrant is a fight, not a place, and the
* only thing that persists about it is the count on the chart.
*/
export function layQuadrant(patrol: Patrol, rng: Rng): Patrol {
const census = patrol.galaxy[patrol.quadrant.row]![patrol.quadrant.col]!
const taken: Coord[] = [patrol.sector]
const free = (): Coord => {
for (;;) {
const c = randomCoord(rng)
if (!taken.some((t) => same(t, c))) {
taken.push(c)
return c
}
}
}
const raiders: Raider[] = []
for (let i = 0; i < census.raiders; i++) {
raiders.push({ at: free(), energy: RAIDER_ENERGY + rng() * RAIDER_ENERGY_SPREAD })
}
const base = census.base ? free() : null
const stars: Coord[] = []
for (let i = 0; i < census.stars; i++) stars.push(free())
return { ...patrol, raiders, base, stars }
}
/** What is standing in a sector, if anything. */
export type Occupant = 'ship' | 'raider' | 'base' | 'star' | null
export function occupant(patrol: Patrol, at: Coord): Occupant {
if (same(at, patrol.sector)) return 'ship'
if (patrol.raiders.some((k) => same(k.at, at))) return 'raider'
if (patrol.base && same(patrol.base, at)) return 'base'
if (patrol.stars.some((s) => same(s, at))) return 'star'
return null
}
+92
View File
@@ -0,0 +1,92 @@
/**
* One board, shared by everybody, held by the scores service rather than the
* browser. Nothing about it is trusted on the way in: the server decides what
* is plausible, and the client re-checks the shape of whatever comes back
* before putting it on screen.
*
* The service is shared with the other games on the site rather than being one
* of ours -- see https://github.com/Coffey-Labs/games-scores. That is why
* every call names the game. Nothing else about it leaks in here: the rows
* come back in this game's own field names, so this file would be identical if
* the board were ours alone.
*/
/** Which board on the shared service is ours. */
export const GAME = 'scan'
const BASE = (import.meta.env.VITE_SCORES_API ?? '/api').replace(/\/+$/, '')
const TIMEOUT_MS = 8000
export const MAX_SCORES = 50
export interface Score {
id: string
name: string
/** Raiders destroyed. The rank, before any tie-break. */
killed: number
/** Days still on the orders when the patrol ended. */
daysLeft: number
/** Torpedoes still in the racks. */
torpedoes: number
/** How it ended, in the game's own words. */
ending: string | null
at: number
}
export type NewScore = Omit<Score, 'id' | 'at'>
function isScore(v: unknown): v is Score {
if (typeof v !== 'object' || v === null) return false
const s = v as Record<string, unknown>
return (
typeof s.id === 'string' &&
typeof s.name === 'string' &&
Number.isFinite(s.killed) &&
Number.isFinite(s.daysLeft) &&
Number.isFinite(s.torpedoes) &&
(s.ending === null || typeof s.ending === 'string') &&
Number.isFinite(s.at)
)
}
const parseBoard = (body: unknown): Score[] => {
const rows = (body as { scores?: unknown })?.scores
if (!Array.isArray(rows)) return []
return rows
.filter(isScore)
.map((s) => ({ ...s, name: s.name.slice(0, 12) }))
.slice(0, MAX_SCORES)
}
async function call(path: string, init?: RequestInit): Promise<unknown> {
const res = await fetch(`${BASE}${path}`, {
...init,
signal: AbortSignal.timeout(TIMEOUT_MS),
headers: { 'content-type': 'application/json', ...(init?.headers ?? {}) },
})
const body: unknown = await res.json().catch(() => null)
if (!res.ok) {
const why = (body as { error?: string })?.error
throw new Error(why ?? `scores service returned ${res.status}`)
}
return body
}
export async function fetchScores(): Promise<Score[]> {
return parseBoard(await call(`/scores?game=${GAME}`))
}
/** Posts every captain in the party at once and returns the new board. */
export async function submitScores(
entries: NewScore[],
): Promise<{ ids: string[]; scores: Score[] }> {
const body = await call('/scores', {
method: 'POST',
body: JSON.stringify({ game: GAME, entries }),
})
const ids = (body as { ids?: unknown })?.ids
return {
ids: Array.isArray(ids) ? ids.filter((i): i is string => typeof i === 'string') : [],
scores: parseBoard(body),
}
}
+153
View File
@@ -0,0 +1,153 @@
import { daysLeft } from './engine'
import type { Captain, Line, Patrol, Phase } from './types'
/**
* The phase machine, and the only place a turn changes hands.
*
* A turn is one whole patrol, not one command. A captain flies until the
* raiders are gone or something ends them, and only then does the printer go
* quiet and the next captain sit down. Splitting turns command by command
* would be fairer in some abstract sense and unplayable in practice: this is
* a game about a galaxy you are holding in your head, and four people cannot
* hold four of them at once. It is the same rule the cave game plays by, for
* the same reason.
*
* Each captain gets their own galaxy, dealt off the same seeded stream. They
* are not competing over one map -- they are being set the same kind of
* problem and judged on what they did with it.
*/
export interface GameState {
phase: Phase
seed: number
captains: Captain[]
/** Index into `captains`; the finished are skipped, never removed. */
turn: number
patrol: Patrol | null
/** Everything the machine has printed for the patrol now being flown. */
transcript: Line[]
/** Where the board was opened from, so BACK has somewhere to go. */
scoresReturn: Phase
}
export const initialState = (seed: number, phase: Phase = 'boot'): GameState => ({
phase,
seed,
captains: [],
turn: 0,
patrol: null,
transcript: [],
scoresReturn: 'title',
})
export type Action =
| { type: 'BOOTED' }
| { type: 'SHOW_INSTRUCTIONS' }
| { type: 'SHOW_SETUP' }
| { type: 'START'; names: string[] }
| { type: 'BEGIN_PATROL'; patrol: Patrol; lines: Line[] }
| { type: 'PRINT'; lines: Line[] }
| { type: 'ADVANCE'; patrol: Patrol; lines: Line[] }
| { type: 'SHOW_REPORT' }
| { type: 'NEXT_TURN' }
| { type: 'SHOW_SCORES' }
| { type: 'CLOSE_SCORES' }
| { type: 'RESTART'; seed: number }
/** Whose turn it is, or undefined once everybody has flown. */
export const currentCaptain = (s: GameState): Captain | undefined => s.captains[s.turn]
/** The next captain who has not flown yet, or -1 when they all have. */
export function nextWaiting(captains: Captain[], from: number): number {
for (let i = 1; i <= captains.length; i++) {
const at = (from + i) % captains.length
if (!captains[at]!.done) return at
}
return -1
}
export function reducer(state: GameState, action: Action): GameState {
switch (action.type) {
case 'BOOTED':
return { ...state, phase: 'title' }
case 'SHOW_INSTRUCTIONS':
return { ...state, phase: 'instructions' }
case 'SHOW_SETUP':
return { ...state, phase: 'setup' }
case 'START':
return {
...state,
phase: 'patrol',
captains: action.names.map((name, i) => ({
id: i,
name: name.trim().toUpperCase() || `CAPTAIN ${i + 1}`,
killed: 0,
daysLeft: 0,
torpedoes: 0,
done: false,
outcome: null,
})),
turn: 0,
patrol: null,
transcript: [],
}
case 'BEGIN_PATROL':
return { ...state, phase: 'patrol', patrol: action.patrol, transcript: action.lines }
case 'PRINT':
return { ...state, transcript: [...state.transcript, ...action.lines] }
case 'ADVANCE':
return {
...state,
patrol: action.patrol,
transcript: [...state.transcript, ...action.lines],
phase: action.patrol.outcome ? 'resolve' : 'patrol',
}
/** The patrol has ended; settle it against the captain and show the report. */
case 'SHOW_REPORT': {
const patrol = state.patrol
const who = currentCaptain(state)
if (!patrol?.outcome || !who) return { ...state, phase: 'report' }
const captains = state.captains.map((c) =>
c.id !== who.id
? c
: {
...c,
killed: patrol.raidersKilled,
daysLeft: Math.round(daysLeft(patrol) * 10) / 10,
torpedoes: patrol.torpedoes,
done: true,
outcome: patrol.outcome,
},
)
return { ...state, phase: 'report', captains }
}
case 'NEXT_TURN': {
const at = nextWaiting(state.captains, state.turn)
if (at === -1) return { ...state, phase: 'gameover', patrol: null }
return { ...state, phase: 'patrol', turn: at, patrol: null, transcript: [] }
}
case 'SHOW_SCORES':
return state.phase === 'scores'
? state
: { ...state, phase: 'scores', scoresReturn: state.phase }
case 'CLOSE_SCORES':
return { ...state, phase: state.scoresReturn }
case 'RESTART':
// The tape only loads once a session; a new patrol starts at the title.
return initialState(action.seed, 'title')
default:
return state
}
}
+19
View File
@@ -0,0 +1,19 @@
/**
* mulberry32 — small, fast, seedable PRNG.
* The 1971 listing ran on RND(1); we keep a seed so a galaxy can be replayed or
* shared, and so a test can lay out the same quadrant twice.
*/
export function makeRng(seed: number) {
let a = seed >>> 0
return function rng(): number {
a = (a + 0x6d2b79f5) >>> 0
let t = a
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
export type Rng = ReturnType<typeof makeRng>
export const chance = (rng: Rng, p: number) => rng() < p
+139
View File
@@ -0,0 +1,139 @@
/** A position, zero-based. Everything the machine prints adds one. */
export interface Coord {
row: number
col: number
}
export type DeviceId =
| 'warp'
| 'srs'
| 'lrs'
| 'beams'
| 'tubes'
| 'repair'
| 'shields'
| 'computer'
export const DEVICES: readonly DeviceId[] = [
'warp',
'srs',
'lrs',
'beams',
'tubes',
'repair',
'shields',
'computer',
]
/**
* What a quadrant holds, without saying where in it. This is the galaxy's
* whole memory: the sectors are laid out fresh each time you arrive, exactly
* as the original did, which is why leaving and coming back rearranges the
* furniture but never changes the count.
*/
export interface Census {
raiders: number
base: boolean
stars: number
}
export interface Raider {
at: Coord
/** Spent by taking hits and by shooting from a long way off. */
energy: number
}
export type Condition = 'DOCKED' | 'RED' | 'YELLOW' | 'GREEN'
export type Outcome =
| 'mission-complete'
| 'out-of-time'
| 'destroyed'
| 'stranded'
| 'resigned'
| 'base-destroyed'
/** True when the patrol ended in a way the captain walks away from. */
export const isWin = (o: Outcome | null): boolean => o === 'mission-complete'
/** One captain's whole patrol. The only mutable thing in the game. */
export interface Patrol {
/** Today, in the fleet's own numbering. Counts up. */
day: number
/** The day the orders expire. */
deadline: number
/** The truth, all sixty-four quadrants of it. */
galaxy: Census[][]
/** What has actually been scanned. A quadrant never seen is null. */
chart: (Census | null)[][]
quadrant: Coord
sector: Coord
energy: number
shields: number
torpedoes: number
/** Days of repair each device still needs. Zero is a working device. */
damage: Record<DeviceId, number>
/** Laid out on arrival, thrown away on leaving. */
raiders: Raider[]
stars: Coord[]
base: Coord | null
docked: boolean
raidersLeft: number
raidersKilled: number
basesLeft: number
outcome: Outcome | null
}
/**
* One line of the transcript. The teletype prints these and, when the
* remaster lands, the tactical view will read them for its log -- so both
* skins will say exactly the same things.
*/
export interface Line {
kind: 'system' | 'scan' | 'move' | 'fire' | 'hit' | 'damage' | 'end' | 'win'
text: string
}
export interface Captain {
id: number
name: string
/** Raiders destroyed. The score, before any tie-break. */
killed: number
/** Days left on the orders when it ended. First tie-break. */
daysLeft: number
/** Torpedoes still in the racks. Second tie-break. */
torpedoes: number
done: boolean
outcome: Outcome | null
}
export type Phase =
| 'boot'
| 'title'
| 'instructions'
| 'setup'
| 'patrol'
| 'resolve'
| 'report'
| 'gameover'
| 'scores'
/** A command, assembled from as many prompts as it takes to ask for it. */
export type Command =
| { type: 'nav'; course: number; warp: number }
| { type: 'srs' }
| { type: 'lrs' }
| { type: 'beams'; energy: number }
| { type: 'torpedo'; course: number }
| { type: 'shields'; energy: number }
| { type: 'damage' }
| { type: 'chart' }
| { type: 'resign' }