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:
+400
@@ -0,0 +1,400 @@
|
||||
/* =====================================================================
|
||||
One skin so far, and it is the machine as it was.
|
||||
|
||||
1971 is a printing terminal: black ink on fanfold paper, one weight, one
|
||||
family, no colour at all. Anything that wants to be emphatic has to do it
|
||||
with capitals or spacing, which is exactly the constraint the original was
|
||||
written under.
|
||||
|
||||
Everything the skin owns is a token, so that the remaster can swap the lot
|
||||
under `html[data-skin='modern']` without touching a rule below.
|
||||
===================================================================== */
|
||||
|
||||
:root {
|
||||
--ink: #241f1a;
|
||||
--ink-dim: #6b6157;
|
||||
--ink-bright: #0d0b09;
|
||||
--accent: #241f1a;
|
||||
--warn: #241f1a;
|
||||
--outline: #b6a992;
|
||||
--screen-bg: #e8e0cc;
|
||||
--screen-radius: 2px;
|
||||
--paper-edge: #d6cbb2;
|
||||
--glow: none;
|
||||
--btn-radius: 0;
|
||||
--btn-shadow: none;
|
||||
--btn-bg: #f3ecd9;
|
||||
--btn-fg: #241f1a;
|
||||
--field-bg: #f7f1e0;
|
||||
--field-fg: #241f1a;
|
||||
--body-font: ui-monospace, "DejaVu Sans Mono", "Cascadia Mono", "Courier New", monospace;
|
||||
--line-height: 1.42;
|
||||
--letter-spacing: 0.02em;
|
||||
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
/* =====================================================================
|
||||
Layout
|
||||
===================================================================== */
|
||||
|
||||
.app {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.cabinet {
|
||||
width: min(980px, 100%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.bezel {
|
||||
position: relative;
|
||||
padding: clamp(10px, 2vw, 20px);
|
||||
border-radius: calc(var(--screen-radius) + 10px);
|
||||
background: #cfc4ab;
|
||||
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
|
||||
/* The platen: the roller the paper comes over, with the feed knob at the end. */
|
||||
.platen {
|
||||
height: 16px;
|
||||
margin: -4px 0 10px;
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(180deg, #4a4038 0%, #2b241e 60%, #1a1512 100%);
|
||||
box-shadow: inset 0 -2px 3px rgba(0, 0, 0, 0.5);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.platen::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: -10px;
|
||||
top: -5px;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(circle at 35% 30%, #6b5c4d, #241f1a 70%);
|
||||
}
|
||||
|
||||
.screen {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: var(--screen-radius);
|
||||
background: var(--screen-bg);
|
||||
aspect-ratio: 4 / 3;
|
||||
box-shadow: var(--glow);
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
/* A phone is taller than it is wide; a fixed 4:3 wastes most of it. */
|
||||
.screen {
|
||||
aspect-ratio: 3 / 4;
|
||||
}
|
||||
}
|
||||
|
||||
.screen-inner {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: clamp(12px, 2.6vw, 26px) 34px;
|
||||
color: var(--ink);
|
||||
font-family: var(--body-font);
|
||||
font-size: clamp(10px, 1.45vw, 14px);
|
||||
line-height: var(--line-height);
|
||||
letter-spacing: var(--letter-spacing);
|
||||
}
|
||||
|
||||
.screen-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Fit shrinks rather than clipping; see Frame.tsx. */
|
||||
.screen-body > * {
|
||||
transform: scale(var(--fit, 1));
|
||||
transform-origin: top center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
width: 100%;
|
||||
max-width: 72ch;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.line {
|
||||
white-space: pre-wrap;
|
||||
min-height: 1.2em;
|
||||
}
|
||||
|
||||
.dim {
|
||||
color: var(--ink-dim);
|
||||
}
|
||||
|
||||
/* On paper there is no colour, so emphasis is weight and spacing only. */
|
||||
.accent,
|
||||
.warn {
|
||||
color: var(--accent);
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.14em;
|
||||
}
|
||||
|
||||
/* --- paper chrome ---------------------------------------------------- */
|
||||
|
||||
.sprockets {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 22px;
|
||||
background-image: radial-gradient(circle at 50% 10px, #b6a992 3.5px, transparent 4px);
|
||||
background-size: 22px 26px;
|
||||
background-color: var(--paper-edge);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sprockets-left {
|
||||
left: 0;
|
||||
border-right: 1px dashed #c3b79e;
|
||||
}
|
||||
|
||||
.sprockets-right {
|
||||
right: 0;
|
||||
border-left: 1px dashed #c3b79e;
|
||||
}
|
||||
|
||||
/* Paper is not flat and not one colour; a faint fibre keeps it from reading
|
||||
as a beige rectangle. */
|
||||
.paper-grain {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
opacity: 0.35;
|
||||
background-image:
|
||||
repeating-linear-gradient(0deg, rgba(0, 0, 0, 0.025) 0 1px, transparent 1px 3px),
|
||||
repeating-linear-gradient(90deg, rgba(0, 0, 0, 0.02) 0 1px, transparent 1px 4px);
|
||||
}
|
||||
|
||||
/* =====================================================================
|
||||
The transcript
|
||||
===================================================================== */
|
||||
|
||||
.console {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.paper {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
scrollbar-width: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.paper::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.printed {
|
||||
white-space: pre;
|
||||
min-height: 1.2em;
|
||||
}
|
||||
|
||||
/* The print head: a block where the next character is about to land. */
|
||||
.head {
|
||||
display: inline-block;
|
||||
width: 0.62em;
|
||||
height: 1em;
|
||||
margin-left: 1px;
|
||||
vertical-align: text-bottom;
|
||||
background: currentColor;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* =====================================================================
|
||||
The prompt
|
||||
===================================================================== */
|
||||
|
||||
.prompt {
|
||||
margin-top: 10px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.prompt-q {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.prompt-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.keys {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 2px 4px;
|
||||
}
|
||||
|
||||
.key {
|
||||
padding: 3px 8px;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.statusbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 16px;
|
||||
margin-top: 10px;
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--outline);
|
||||
color: var(--ink-dim);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
/* Condition red. On paper it can only be said louder, not redder. */
|
||||
.statusbar .senses {
|
||||
color: var(--ink-bright);
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.14em;
|
||||
}
|
||||
|
||||
.banner {
|
||||
margin: 0;
|
||||
font-family: var(--body-font);
|
||||
font-weight: 900;
|
||||
font-size: clamp(1.3rem, 4.4vw, 2.4rem);
|
||||
letter-spacing: 0.08em;
|
||||
line-height: 1.1;
|
||||
color: var(--ink-bright);
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: 3px 0;
|
||||
}
|
||||
|
||||
.field label {
|
||||
min-width: 11ch;
|
||||
color: var(--ink-dim);
|
||||
}
|
||||
|
||||
.field-input {
|
||||
flex: 1;
|
||||
max-width: 22ch;
|
||||
padding: 5px 8px;
|
||||
border: 2px solid var(--outline);
|
||||
border-radius: var(--btn-radius);
|
||||
background: var(--field-bg);
|
||||
color: var(--field-fg);
|
||||
font: inherit;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* =====================================================================
|
||||
Buttons
|
||||
===================================================================== */
|
||||
|
||||
.btn {
|
||||
padding: 6px 14px;
|
||||
border: 2px solid var(--outline);
|
||||
border-radius: var(--btn-radius);
|
||||
background: var(--btn-bg);
|
||||
color: var(--btn-fg);
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
cursor: pointer;
|
||||
box-shadow: var(--btn-shadow);
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: #241f1a;
|
||||
color: #f3ecd9;
|
||||
}
|
||||
|
||||
.btn-ghost {
|
||||
background: transparent;
|
||||
color: var(--ink-dim);
|
||||
border-color: transparent;
|
||||
box-shadow: none;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-ghost:hover:not(:disabled) {
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
/* The stack is a column, so a button in it stretches to the full width unless
|
||||
it is told not to. A button that wide reads as a banner rather than a
|
||||
control. */
|
||||
.stack > .btn {
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
/* =====================================================================
|
||||
The footer
|
||||
|
||||
It sits outside the frame, on the page rather than on the paper -- so it
|
||||
cannot use the ink tokens, which are chosen to be dark on a light sheet.
|
||||
===================================================================== */
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 8px;
|
||||
color: #9a9186;
|
||||
font-family: var(--body-font);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.controls .btn-ghost {
|
||||
color: #9a9186;
|
||||
}
|
||||
|
||||
.controls .btn-ghost:hover:not(:disabled) {
|
||||
color: #f0e8d4;
|
||||
}
|
||||
|
||||
/*
|
||||
* The way back. The arrow is a pseudo-element rather than part of the label so
|
||||
* that it can be the right arrow for the machine you are looking at: the two
|
||||
* ASCII characters a printing terminal could actually strike.
|
||||
*/
|
||||
.controls .back::before {
|
||||
content: '<-\00a0';
|
||||
}
|
||||
|
||||
.seed {
|
||||
margin-left: auto;
|
||||
opacity: 0.7;
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
import { useCallback, useEffect, useRef, useState, useReducer } from 'react'
|
||||
import { HAIL_TEXT } from './game/constants'
|
||||
import { makePatrol, randomSeed, shortRangeScan, step } from './game/engine'
|
||||
import { fetchScores, submitScores, type Score } from './game/highscores'
|
||||
import { makeRng, type Rng } from './game/rng'
|
||||
import { currentCaptain, initialState, reducer } from './game/reducer'
|
||||
import type { Command, Line } from './game/types'
|
||||
import { Btn, Fit, Frame } from './components/Frame'
|
||||
import { BridgeScreen } from './components/BridgeScreen'
|
||||
import {
|
||||
BootScreen,
|
||||
GameOverScreen,
|
||||
HighScoreScreen,
|
||||
InstructionsScreen,
|
||||
ReportScreen,
|
||||
SetupScreen,
|
||||
TitleScreen,
|
||||
type BoardState,
|
||||
} from './components/screens'
|
||||
import './App.css'
|
||||
|
||||
/**
|
||||
* AGPL section 13: anyone playing this over a network is entitled to the
|
||||
* source of the version they are playing, so the offer sits on every screen.
|
||||
*/
|
||||
const SOURCE_URL = 'https://github.com/Coffey-Labs/long-range-scan'
|
||||
|
||||
/**
|
||||
* The way back out.
|
||||
*
|
||||
* Absolute rather than `/`, because this game is served from a subdirectory in
|
||||
* production and from the root in development -- so the relative answer is
|
||||
* right in one of those and points at the game itself in the other. The
|
||||
* destination is a particular site, and naming it is the honest way to say so.
|
||||
* The source link next to it works the same way for the same reason.
|
||||
*/
|
||||
const GAMES_URL = 'https://games.jcoffey.dev/'
|
||||
|
||||
export default function App() {
|
||||
const [seed] = useState(randomSeed)
|
||||
const [state, dispatch] = useReducer(reducer, seed, initialState)
|
||||
const rng = useRef<Rng>(makeRng(seed))
|
||||
const [scores, setScores] = useState<Score[]>([])
|
||||
const [boardState, setBoardState] = useState<BoardState>('loading')
|
||||
const [freshScores, setFreshScores] = useState<string[]>([])
|
||||
/** True while the printer is mid-line, so no prompt appears over it. */
|
||||
const [printing, setPrinting] = useState(false)
|
||||
|
||||
const who = currentCaptain(state)
|
||||
|
||||
const loadBoard = useCallback(async () => {
|
||||
setBoardState('loading')
|
||||
try {
|
||||
setScores(await fetchScores())
|
||||
setBoardState('ready')
|
||||
} catch {
|
||||
setBoardState('error')
|
||||
}
|
||||
}, [])
|
||||
|
||||
// ---------------------------------------------------------------- turns
|
||||
|
||||
/**
|
||||
* Deal a galaxy for whoever is up, and open the way the machine opened: the
|
||||
* orders, then a scan, because the first thing anybody did was look.
|
||||
*
|
||||
* The galaxy is dealt off the same seeded stream as everything else, which
|
||||
* is what makes a whole session -- four captains, four patrols -- replayable
|
||||
* from the one number in the footer.
|
||||
*/
|
||||
const beginPatrol = useCallback(() => {
|
||||
const patrol = makePatrol(rng.current)
|
||||
const lines: Line[] = [
|
||||
...HAIL_TEXT.map((text): Line => ({ kind: 'system', text })),
|
||||
{
|
||||
kind: 'system',
|
||||
text: `${patrol.raidersLeft} RAIDERS. ${patrol.basesLeft} STARBASE${patrol.basesLeft === 1 ? '' : 'S'}. ${patrol.deadline - patrol.day} DAYS.`,
|
||||
},
|
||||
...shortRangeScan(patrol),
|
||||
]
|
||||
dispatch({ type: 'BEGIN_PATROL', patrol, lines })
|
||||
}, [])
|
||||
|
||||
// Whenever it is somebody's turn and there is no galaxy, deal them one.
|
||||
useEffect(() => {
|
||||
if (state.phase !== 'patrol' || state.patrol || !who) return
|
||||
beginPatrol()
|
||||
}, [state.phase, state.patrol, who, beginPatrol])
|
||||
|
||||
const command = (cmd: Command, echo: Line[]) => {
|
||||
if (!state.patrol) return
|
||||
const { patrol, lines } = step(state.patrol, cmd, rng.current)
|
||||
dispatch({ type: 'ADVANCE', patrol, lines: [...echo, ...lines] })
|
||||
}
|
||||
|
||||
// The report waits for the printer to finish saying how it ended.
|
||||
useEffect(() => {
|
||||
if (state.phase !== 'resolve' || printing) return
|
||||
const t = window.setTimeout(() => dispatch({ type: 'SHOW_REPORT' }), 500)
|
||||
return () => window.clearTimeout(t)
|
||||
}, [state.phase, printing])
|
||||
|
||||
/**
|
||||
* Close the books. The standings show straight away; posting to the board
|
||||
* happens behind them, so a slow or missing line out never holds up the end
|
||||
* of a session.
|
||||
*/
|
||||
const post = useCallback((captains: typeof state.captains) => {
|
||||
setBoardState('loading')
|
||||
submitScores(
|
||||
captains.map((c) => ({
|
||||
name: c.name,
|
||||
killed: c.killed,
|
||||
daysLeft: c.daysLeft,
|
||||
torpedoes: c.torpedoes,
|
||||
ending: c.outcome,
|
||||
})),
|
||||
)
|
||||
.then(({ ids, scores: table }) => {
|
||||
setScores(table)
|
||||
setFreshScores(ids)
|
||||
setBoardState('ready')
|
||||
})
|
||||
.catch(() => setBoardState('error'))
|
||||
}, [])
|
||||
|
||||
const posted = useRef(false)
|
||||
useEffect(() => {
|
||||
if (state.phase !== 'gameover' || posted.current) return
|
||||
posted.current = true
|
||||
post(state.captains)
|
||||
}, [state.phase, state.captains, post])
|
||||
|
||||
const restart = () => {
|
||||
const s = randomSeed()
|
||||
rng.current = makeRng(s)
|
||||
posted.current = false
|
||||
setFreshScores([])
|
||||
dispatch({ type: 'RESTART', seed: s })
|
||||
}
|
||||
|
||||
const showScores = () => {
|
||||
dispatch({ type: 'SHOW_SCORES' })
|
||||
if (boardState !== 'ready') void loadBoard()
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- render
|
||||
|
||||
const moreToCome = state.captains.some((c) => !c.done && c.id !== who?.id)
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<Frame
|
||||
footer={
|
||||
<div className="controls">
|
||||
{/* Leftmost, because that is where a way back belongs. */}
|
||||
<a className="btn btn-ghost back" href={GAMES_URL} title="The rest of the games">
|
||||
GAMES
|
||||
</a>
|
||||
<Btn kind="ghost" onClick={restart} title="Abandon this session">
|
||||
NEW PATROL
|
||||
</Btn>
|
||||
<a
|
||||
className="btn btn-ghost"
|
||||
href={SOURCE_URL}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
title="Free software, AGPL-3.0-or-later"
|
||||
>
|
||||
SOURCE
|
||||
</a>
|
||||
<span className="seed">SEED {state.seed}</span>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{state.phase === 'boot' && <BootScreen onLoaded={() => dispatch({ type: 'BOOTED' })} />}
|
||||
|
||||
<Fit>
|
||||
{state.phase === 'title' && (
|
||||
<TitleGate
|
||||
onStart={() => dispatch({ type: 'SHOW_SETUP' })}
|
||||
onInstructions={() => dispatch({ type: 'SHOW_INSTRUCTIONS' })}
|
||||
onScores={showScores}
|
||||
/>
|
||||
)}
|
||||
|
||||
{state.phase === 'instructions' && (
|
||||
<InstructionsScreen onDone={() => dispatch({ type: 'SHOW_SETUP' })} />
|
||||
)}
|
||||
|
||||
{state.phase === 'setup' && (
|
||||
<SetupScreen onStart={(names) => dispatch({ type: 'START', names })} />
|
||||
)}
|
||||
|
||||
{(state.phase === 'patrol' || state.phase === 'resolve') && state.patrol && who && (
|
||||
<BridgeScreen
|
||||
key={who.id}
|
||||
patrol={state.patrol}
|
||||
transcript={state.transcript}
|
||||
captainName={who.name}
|
||||
over={state.phase === 'resolve'}
|
||||
onCommand={command}
|
||||
onPrint={(lines) => dispatch({ type: 'PRINT', lines })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{state.phase === 'report' && state.patrol && who && (
|
||||
<ReportScreen
|
||||
patrol={state.patrol}
|
||||
captain={state.captains[who.id]!}
|
||||
moreToCome={moreToCome}
|
||||
onNext={() => dispatch({ type: 'NEXT_TURN' })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{state.phase === 'gameover' && (
|
||||
<GameOverScreen
|
||||
captains={state.captains}
|
||||
onRestart={restart}
|
||||
onScores={showScores}
|
||||
/>
|
||||
)}
|
||||
|
||||
{state.phase === 'scores' && (
|
||||
<HighScoreScreen
|
||||
scores={scores}
|
||||
state={boardState}
|
||||
highlight={freshScores}
|
||||
onBack={() => dispatch({ type: 'CLOSE_SCORES' })}
|
||||
onRetry={() => void loadBoard()}
|
||||
/>
|
||||
)}
|
||||
</Fit>
|
||||
</Frame>
|
||||
{/* Kept out of the tree above so a re-render of the game cannot reset it. */}
|
||||
<PrintingWatcher lines={state.transcript} onChange={setPrinting} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the machine is still typing.
|
||||
*
|
||||
* The prompt must not appear while a line is half printed -- the whole point
|
||||
* of the printing terminal is that you read what arrived before you answer
|
||||
* it.
|
||||
*
|
||||
* It times the characters that have just *arrived*, not the whole transcript.
|
||||
* Timing the whole thing is the obvious way to write this and it is wrong in
|
||||
* a way that takes a few turns to notice: `Teletype` only prints lines it has
|
||||
* not printed yet, so the wait keeps growing while the actual printing stays
|
||||
* the same length. A scan is not timed at all, because it lands whole.
|
||||
*/
|
||||
function PrintingWatcher({
|
||||
lines,
|
||||
onChange,
|
||||
}: {
|
||||
lines: Line[]
|
||||
onChange: (busy: boolean) => void
|
||||
}) {
|
||||
const chars = lines.reduce((n, l) => n + (l.kind === 'scan' ? 0 : l.text.length), 0)
|
||||
const printed = useRef(0)
|
||||
|
||||
useEffect(() => {
|
||||
// A new patrol throws the transcript away; nothing is owed from the old one.
|
||||
if (chars < printed.current) printed.current = 0
|
||||
|
||||
const fresh = chars - printed.current
|
||||
printed.current = chars
|
||||
if (fresh <= 0) {
|
||||
onChange(false)
|
||||
return
|
||||
}
|
||||
|
||||
onChange(true)
|
||||
// 60 characters a second, plus a beat to read the last line.
|
||||
const t = window.setTimeout(() => onChange(false), (fresh / 60) * 1000 + 120)
|
||||
return () => window.clearTimeout(t)
|
||||
}, [chars, onChange])
|
||||
return null
|
||||
}
|
||||
|
||||
/** Enter or Space takes the patrol, the way a terminal would take it. */
|
||||
function TitleGate(props: {
|
||||
onStart: () => void
|
||||
onInstructions: () => void
|
||||
onScores: () => void
|
||||
}) {
|
||||
const { onStart } = props
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') onStart()
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [onStart])
|
||||
return <TitleScreen {...props} />
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { condition, daysLeft } from '../game/engine'
|
||||
import type { Command, Line, Patrol } from '../game/types'
|
||||
import { Teletype } from './Teletype'
|
||||
|
||||
/**
|
||||
* The console: the paper, and the one line you are allowed to type on.
|
||||
*
|
||||
* The original asks for a command and then asks for whatever that command
|
||||
* needs, one question at a time -- COMMAND, then COURSE, then WARP FACTOR --
|
||||
* because a printing terminal has no form to fill in and no way back to a
|
||||
* field you have already left. That is kept exactly, and it is why this
|
||||
* component is a tiny state machine rather than a set of inputs.
|
||||
*/
|
||||
type Ask = 'command' | 'nav-course' | 'nav-warp' | 'tor-course' | 'beams' | 'shields'
|
||||
|
||||
const QUESTION: Record<Ask, string> = {
|
||||
command: 'COMMAND',
|
||||
'nav-course': 'COURSE (1-9)',
|
||||
'nav-warp': 'WARP FACTOR (0-8)',
|
||||
'tor-course': 'TORPEDO COURSE (1-9)',
|
||||
beams: 'UNITS TO FIRE',
|
||||
shields: 'UNITS TO SHIELDS',
|
||||
}
|
||||
|
||||
/** The nine, in the order the machine lists them when asked. */
|
||||
export const COMMANDS: readonly (readonly [string, string])[] = [
|
||||
['NAV', 'WARP SOMEWHERE ELSE'],
|
||||
['SRS', 'SHORT RANGE SCAN'],
|
||||
['LRS', 'LONG RANGE SCAN'],
|
||||
['BEA', 'FIRE THE BEAMS'],
|
||||
['TOR', 'FIRE A TORPEDO'],
|
||||
['SHE', 'PUT ENERGY IN THE SHIELDS'],
|
||||
['DAM', 'DAMAGE REPORT'],
|
||||
['COM', 'THE CHART, AND WHERE YOU ARE ON IT'],
|
||||
['XXX', 'BREAK OFF AND GO HOME'],
|
||||
]
|
||||
|
||||
export function BridgeScreen({
|
||||
patrol,
|
||||
transcript,
|
||||
captainName,
|
||||
over,
|
||||
onCommand,
|
||||
onPrint,
|
||||
}: {
|
||||
patrol: Patrol
|
||||
transcript: Line[]
|
||||
captainName: string
|
||||
/** The patrol has ended. There is nothing left to ask. */
|
||||
over: boolean
|
||||
onCommand: (cmd: Command, echo: Line[]) => void
|
||||
onPrint: (lines: Line[]) => void
|
||||
}) {
|
||||
const [ask, setAsk] = useState<Ask>('command')
|
||||
const [course, setCourse] = useState(0)
|
||||
const [text, setText] = useState('')
|
||||
const input = useRef<HTMLInputElement>(null)
|
||||
|
||||
// The question moves on; the cursor should be waiting under it.
|
||||
useEffect(() => {
|
||||
input.current?.focus()
|
||||
}, [ask])
|
||||
|
||||
const echo = (answer: string): Line => ({
|
||||
kind: 'system',
|
||||
text: `${QUESTION[ask]} ? ${answer}`,
|
||||
})
|
||||
|
||||
/** `raw` is how the command buttons answer: a click is a whole answer. */
|
||||
const submit = (raw?: string) => {
|
||||
const answer = (raw ?? text).trim().toUpperCase()
|
||||
if (answer === '') return
|
||||
setText('')
|
||||
|
||||
if (ask === 'command') {
|
||||
const cmd = answer.slice(0, 3)
|
||||
const known = COMMANDS.some(([id]) => id === cmd)
|
||||
if (!known) {
|
||||
onPrint([echo(answer), { kind: 'system', text: 'THAT IS NOT ONE OF THE NINE.' }])
|
||||
return
|
||||
}
|
||||
|
||||
// Two of them need more asking before anything happens.
|
||||
if (cmd === 'NAV') {
|
||||
onPrint([echo(answer)])
|
||||
setAsk('nav-course')
|
||||
return
|
||||
}
|
||||
if (cmd === 'TOR') {
|
||||
onPrint([echo(answer)])
|
||||
setAsk('tor-course')
|
||||
return
|
||||
}
|
||||
if (cmd === 'BEA') {
|
||||
onPrint([echo(answer)])
|
||||
setAsk('beams')
|
||||
return
|
||||
}
|
||||
if (cmd === 'SHE') {
|
||||
onPrint([echo(answer)])
|
||||
setAsk('shields')
|
||||
return
|
||||
}
|
||||
|
||||
const simple: Record<string, Command> = {
|
||||
SRS: { type: 'srs' },
|
||||
LRS: { type: 'lrs' },
|
||||
DAM: { type: 'damage' },
|
||||
COM: { type: 'chart' },
|
||||
XXX: { type: 'resign' },
|
||||
}
|
||||
onCommand(simple[cmd]!, [echo(answer)])
|
||||
return
|
||||
}
|
||||
|
||||
const value = Number(answer)
|
||||
if (!Number.isFinite(value)) {
|
||||
onPrint([echo(answer), { kind: 'system', text: 'A NUMBER, PLEASE.' }])
|
||||
return
|
||||
}
|
||||
|
||||
switch (ask) {
|
||||
case 'nav-course':
|
||||
onPrint([echo(answer)])
|
||||
setCourse(value)
|
||||
setAsk('nav-warp')
|
||||
break
|
||||
case 'nav-warp':
|
||||
onCommand({ type: 'nav', course, warp: value }, [echo(answer)])
|
||||
setAsk('command')
|
||||
break
|
||||
case 'tor-course':
|
||||
onCommand({ type: 'torpedo', course: value }, [echo(answer)])
|
||||
setAsk('command')
|
||||
break
|
||||
case 'beams':
|
||||
onCommand({ type: 'beams', energy: value }, [echo(answer)])
|
||||
setAsk('command')
|
||||
break
|
||||
case 'shields':
|
||||
onCommand({ type: 'shields', energy: value }, [echo(answer)])
|
||||
setAsk('command')
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="console">
|
||||
<Teletype lines={transcript} />
|
||||
|
||||
{/*
|
||||
A concession, and the only one: the machine printed the ship's numbers
|
||||
beside a short range scan and nowhere else, so the 1971 way to know
|
||||
your energy was to remember it or spend a command asking. That is fine
|
||||
on paper you can hold and unkind on a phone, where the answer has
|
||||
already scrolled. The scan is still the only place the *galaxy*
|
||||
appears; this strip only ever says what is true of the ship.
|
||||
*/}
|
||||
<div className="statusbar">
|
||||
<span>{captainName}</span>
|
||||
<span>STARDATE {patrol.day.toFixed(1)}</span>
|
||||
<span>DAYS {daysLeft(patrol).toFixed(1)}</span>
|
||||
<span>ENERGY {Math.round(patrol.energy)}</span>
|
||||
<span>SHIELDS {Math.round(patrol.shields)}</span>
|
||||
<span>TORP {patrol.torpedoes}</span>
|
||||
<span>RAIDERS {patrol.raidersLeft}</span>
|
||||
<span className={condition(patrol) === 'RED' ? 'senses' : ''}>{condition(patrol)}</span>
|
||||
</div>
|
||||
|
||||
{/*
|
||||
The prompt never goes away while the patrol is running, even mid-print.
|
||||
Hiding it until the printer catches up is the obvious thing and it is
|
||||
wrong: a terminal took type-ahead, and somebody who already knows they
|
||||
want SRS should not have their keystrokes eaten because the machine is
|
||||
still hammering out the last line. It cost two commands to find that
|
||||
out by playing it.
|
||||
*/}
|
||||
{!over && (
|
||||
<div className="prompt">
|
||||
<div className="prompt-row">
|
||||
<span className="prompt-q">{QUESTION[ask]} ?</span>
|
||||
<input
|
||||
ref={input}
|
||||
className="field-input"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') submit()
|
||||
}}
|
||||
aria-label={QUESTION[ask]}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/*
|
||||
The nine, as buttons. A terminal had a keyboard and a phone does
|
||||
not, and making somebody thumb-type NAV forty times is not
|
||||
faithfulness, it is an obstacle the original never had. Typing
|
||||
still works and is still the way it is meant to be played.
|
||||
*/}
|
||||
{ask === 'command' && (
|
||||
<div className="keys">
|
||||
{COMMANDS.map(([id, what]) => (
|
||||
<button
|
||||
key={id}
|
||||
className="btn btn-ghost key"
|
||||
title={what}
|
||||
onClick={() => submit(id)}
|
||||
>
|
||||
{id}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react'
|
||||
|
||||
/**
|
||||
* The thing the game is happening inside.
|
||||
*
|
||||
* 1971 is a printing terminal on the end of a telephone line, so the frame is
|
||||
* a sheet of fanfold paper coming out of a machine: sprocket holes down both
|
||||
* edges, a platen at the top, and no screen anywhere. When the remaster
|
||||
* arrives it will bring its own frame and everything inside will be laid out
|
||||
* identically -- only the box will change.
|
||||
*/
|
||||
export function Frame({ children, footer }: { children: ReactNode; footer?: ReactNode }) {
|
||||
return (
|
||||
<div className="cabinet">
|
||||
<div className="bezel">
|
||||
<div className="platen" aria-hidden />
|
||||
<div className="screen">
|
||||
<div className="screen-inner">{children}</div>
|
||||
<div className="sprockets sprockets-left" aria-hidden />
|
||||
<div className="sprockets sprockets-right" aria-hidden />
|
||||
<div className="paper-grain" aria-hidden />
|
||||
</div>
|
||||
</div>
|
||||
{footer}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A sheet of paper does not scroll. If the page comes out taller than the
|
||||
* frame, shrink it rather than clipping it. Lifted from the sibling games,
|
||||
* where the argument was about televisions and cave mouths.
|
||||
*/
|
||||
export function Fit({ children }: { children: ReactNode }) {
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
const [scale, setScale] = useState(1)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const measure = () => {
|
||||
const el = box.current
|
||||
const page = el?.firstElementChild as HTMLElement | null
|
||||
if (!el || !page) return
|
||||
// offsetHeight is the laid-out size and ignores the transform, so
|
||||
// measuring here cannot feed back into itself.
|
||||
const h = page.offsetHeight
|
||||
const avail = el.clientHeight
|
||||
setScale(h > 0 && avail > 0 ? Math.min(1, avail / h) : 1)
|
||||
}
|
||||
|
||||
measure()
|
||||
const ro = new ResizeObserver(measure)
|
||||
if (box.current) ro.observe(box.current)
|
||||
if (box.current?.firstElementChild) ro.observe(box.current.firstElementChild)
|
||||
return () => ro.disconnect()
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="screen-body" ref={box} style={{ '--fit': scale } as React.CSSProperties}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Line({ children, className = '' }: { children?: ReactNode; className?: string }) {
|
||||
return <div className={`line ${className}`}>{children ?? ' '}</div>
|
||||
}
|
||||
|
||||
export function Btn({
|
||||
children,
|
||||
onClick,
|
||||
kind = 'normal',
|
||||
disabled,
|
||||
title,
|
||||
}: {
|
||||
children: ReactNode
|
||||
onClick: () => void
|
||||
kind?: 'normal' | 'primary' | 'ghost'
|
||||
disabled?: boolean
|
||||
title?: string
|
||||
}) {
|
||||
return (
|
||||
<button className={`btn btn-${kind}`} onClick={onClick} disabled={disabled} title={title}>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { Line } from '../game/types'
|
||||
|
||||
/**
|
||||
* The 1971 skin: everything the machine has said, printed.
|
||||
*
|
||||
* A printing terminal runs at ten characters a second and cannot take any of
|
||||
* it back, so this types rather than appears, and nothing already printed
|
||||
* ever changes. That is not decoration -- it is the reason the game feels the
|
||||
* way it does. A short range scan arriving row by row is a different
|
||||
* experience from finding the whole grid already on the page, and this game
|
||||
* is eleven lines of grid arriving while something shoots at you.
|
||||
*
|
||||
* A scan is exempt. Eight rows of it at reading speed is most of a minute,
|
||||
* and the original's printer was hammering all eight out while the captain
|
||||
* was already deciding -- so the grid lands whole and the sentences type.
|
||||
*/
|
||||
const CPS = 60 // Faster than a real ASR-33. A real one is 10, and it is a lot.
|
||||
|
||||
export function Teletype({ lines }: { lines: Line[] }) {
|
||||
const [printed, setPrinted] = useState<string[]>([])
|
||||
const [partial, setPartial] = useState('')
|
||||
const done = useRef(0)
|
||||
const paper = useRef<HTMLDivElement>(null)
|
||||
|
||||
// A new patrol throws the old transcript away rather than scrolling it.
|
||||
useEffect(() => {
|
||||
if (lines.length < done.current) {
|
||||
done.current = 0
|
||||
setPrinted([])
|
||||
setPartial('')
|
||||
}
|
||||
}, [lines.length])
|
||||
|
||||
useEffect(() => {
|
||||
if (done.current >= lines.length) return
|
||||
const next = lines[done.current]!
|
||||
|
||||
if (next.kind === 'scan') {
|
||||
done.current += 1
|
||||
setPrinted((p) => [...p, next.text])
|
||||
return
|
||||
}
|
||||
|
||||
const text = next.text
|
||||
let at = 0
|
||||
setPartial('')
|
||||
|
||||
const timer = window.setInterval(() => {
|
||||
at += 1
|
||||
setPartial(text.slice(0, at))
|
||||
if (at >= text.length) {
|
||||
window.clearInterval(timer)
|
||||
done.current += 1
|
||||
setPartial('')
|
||||
setPrinted((p) => [...p, text])
|
||||
}
|
||||
}, 1000 / CPS)
|
||||
|
||||
return () => window.clearInterval(timer)
|
||||
// `printed` is the trigger: finishing one line starts the next.
|
||||
}, [lines, printed.length])
|
||||
|
||||
// The paper feeds up; you always read at the bottom.
|
||||
useEffect(() => {
|
||||
paper.current?.scrollTo({ top: paper.current.scrollHeight })
|
||||
}, [printed.length, partial])
|
||||
|
||||
return (
|
||||
<div className="paper" ref={paper}>
|
||||
{printed.map((text, i) => (
|
||||
<div className="printed" key={i}>
|
||||
{text}
|
||||
</div>
|
||||
))}
|
||||
{partial && (
|
||||
<div className="printed">
|
||||
{partial}
|
||||
<span className="head" aria-hidden />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { MAX_CAPTAINS, MAX_NAME, START_ENERGY, START_TORPEDOES } from '../game/constants'
|
||||
import { comparePatrols, outcomeText } from '../game/engine'
|
||||
import type { Score } from '../game/highscores'
|
||||
import type { Captain, Patrol } from '../game/types'
|
||||
import { isWin } from '../game/types'
|
||||
import { COMMANDS } from './BridgeScreen'
|
||||
import { Btn, Line } from './Frame'
|
||||
|
||||
/**
|
||||
* Everything that is not the patrol itself. These are small enough that
|
||||
* keeping them in one file makes the shape of the game easier to see than
|
||||
* eight files would, and none of them holds a rule.
|
||||
*/
|
||||
|
||||
// ------------------------------------------------------------------- boot
|
||||
|
||||
/**
|
||||
* Dialling in.
|
||||
*
|
||||
* The lemonade stand loads from cassette because that is how an Atari got its
|
||||
* programs. This game is eight years older than that machine and did not live
|
||||
* on a machine you owned at all -- it lived on a mainframe at the end of a
|
||||
* telephone line, which you called. So the boot is a call, and it is the same
|
||||
* gesture the cave game opens with for the same reason.
|
||||
*
|
||||
* There is no sound yet. When the remaster lands it brings the synth with it,
|
||||
* and this schedule is already shaped to be played rather than only printed.
|
||||
*/
|
||||
const STAGES: [number, string][] = [
|
||||
[0, 'DIAL TONE'],
|
||||
[1.1, 'DIALLING'],
|
||||
[2.6, 'RINGING'],
|
||||
[4.2, 'ANSWER TONE'],
|
||||
[5.2, 'CARRIER -- 110 BAUD, FULL DUPLEX'],
|
||||
[6.0, 'LOGIN ACCEPTED'],
|
||||
]
|
||||
|
||||
const BOOT_TOTAL = 6.8
|
||||
|
||||
export function BootScreen({ onLoaded }: { onLoaded: () => void }) {
|
||||
const [dialling, setDialling] = useState(false)
|
||||
const [stage, setStage] = useState(-1)
|
||||
|
||||
useEffect(() => {
|
||||
if (!dialling) return
|
||||
|
||||
const timers = STAGES.map(([at], i) => window.setTimeout(() => setStage(i), at * 1000))
|
||||
const done = window.setTimeout(onLoaded, BOOT_TOTAL * 1000)
|
||||
|
||||
return () => {
|
||||
for (const t of timers) window.clearTimeout(t)
|
||||
window.clearTimeout(done)
|
||||
}
|
||||
}, [dialling, onLoaded])
|
||||
|
||||
if (!dialling) {
|
||||
return (
|
||||
<div className="stack boot">
|
||||
<Line className="accent">LONG RANGE SCAN</Line>
|
||||
<Line> </Line>
|
||||
<Line>THE PROGRAM IS NOT ON THIS MACHINE. IT IS ON SOMEBODY ELSE'S.</Line>
|
||||
<Line className="dim">PUT THE HANDSET IN THE COUPLER AND CALL IT.</Line>
|
||||
<Line> </Line>
|
||||
<Btn kind="primary" onClick={() => setDialling(true)}>
|
||||
DIAL
|
||||
</Btn>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="stack boot">
|
||||
{STAGES.slice(0, stage + 1).map(([, what], i) => (
|
||||
<Line key={i} className={i === stage ? '' : 'dim'}>
|
||||
{what}
|
||||
</Line>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ title
|
||||
|
||||
export function TitleScreen({
|
||||
onStart,
|
||||
onInstructions,
|
||||
onScores,
|
||||
}: {
|
||||
onStart: () => void
|
||||
onInstructions: () => void
|
||||
onScores: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="stack title">
|
||||
<h1 className="banner">LONG RANGE SCAN</h1>
|
||||
<Line className="dim">A PATROL, A CLOCK, AND SIXTY-FOUR QUADRANTS TO SEARCH.</Line>
|
||||
<Line> </Line>
|
||||
<Line>RAIDERS ARE SCATTERED THROUGH THE GALAXY. YOU HAVE ONE SHIP AND NOT LONG.</Line>
|
||||
<Line> </Line>
|
||||
<div className="prompt-row">
|
||||
<Btn kind="primary" onClick={onStart}>
|
||||
TAKE THE PATROL
|
||||
</Btn>
|
||||
<Btn onClick={onInstructions}>ORDERS</Btn>
|
||||
<Btn onClick={onScores}>BOARD</Btn>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------- instructions
|
||||
|
||||
export function InstructionsScreen({ onDone }: { onDone: () => void }) {
|
||||
return (
|
||||
<div className="stack orders">
|
||||
<Line className="accent">YOUR ORDERS</Line>
|
||||
<Line>FIND EVERY RAIDER IN THE GALAXY AND DESTROY IT BEFORE YOUR TIME RUNS OUT.</Line>
|
||||
<Line> </Line>
|
||||
<Line className="accent">THE GALAXY</Line>
|
||||
<Line>EIGHT BY EIGHT QUADRANTS. EACH QUADRANT IS EIGHT BY EIGHT SECTORS.</Line>
|
||||
<Line>A LONG RANGE SCAN READS THREE DIGITS PER QUADRANT: RAIDERS, STARBASES, STARS.</Line>
|
||||
<Line>SO 205 IS TWO RAIDERS, NO BASE AND FIVE STARS. READING THOSE IS THE GAME.</Line>
|
||||
<Line> </Line>
|
||||
<Line className="accent">THE SHIP</Line>
|
||||
<Line>
|
||||
{START_ENERGY} UNITS OF ENERGY AND {START_TORPEDOES} TORPEDOES. ENERGY MOVES YOU, FIRES
|
||||
THE BEAMS AND FILLS THE SHIELDS -- IT IS ALL THE SAME POOL.
|
||||
</Line>
|
||||
<Line>EIGHT DEVICES CAN BE BROKEN BY A HIT. DAMAGE CONTROL WORKS ONLY WHILE YOU FLY.</Line>
|
||||
<Line>MOOR NEXT TO A STARBASE AND YOU ARE FULL AGAIN. THERE ARE NOT MANY OF THEM.</Line>
|
||||
<Line> </Line>
|
||||
<Line className="accent">STEERING</Line>
|
||||
<Line>COURSES RUN 1 TO 9 ANTICLOCKWISE. 1 IS ALONG THE ROW, 3 IS UP, 5 IS BACK, 7 IS
|
||||
DOWN, AND 9 IS 1 AGAIN. WARP 1 IS EIGHT SECTORS.</Line>
|
||||
<Line> </Line>
|
||||
<Line className="accent">THE COMMANDS</Line>
|
||||
{COMMANDS.map(([id, what]) => (
|
||||
<Line key={id}>
|
||||
{id} {' '} {what}
|
||||
</Line>
|
||||
))}
|
||||
<Line> </Line>
|
||||
<Btn kind="primary" onClick={onDone}>
|
||||
UNDERSTOOD
|
||||
</Btn>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ setup
|
||||
|
||||
export function SetupScreen({ onStart }: { onStart: (names: string[]) => void }) {
|
||||
const [names, setNames] = useState<string[]>([''])
|
||||
|
||||
const set = (i: number, v: string) =>
|
||||
setNames((n) => n.map((old, j) => (j === i ? v.slice(0, MAX_NAME) : old)))
|
||||
|
||||
return (
|
||||
<div className="stack setup">
|
||||
<Line className="accent">WHO IS FLYING?</Line>
|
||||
<Line className="dim">EACH CAPTAIN GETS THEIR OWN GALAXY. YOU TAKE IT IN TURNS.</Line>
|
||||
<Line> </Line>
|
||||
{names.map((name, i) => (
|
||||
<div className="field" key={i}>
|
||||
<label htmlFor={`captain-${i}`}>CAPTAIN {i + 1}</label>
|
||||
<input
|
||||
id={`captain-${i}`}
|
||||
className="field-input"
|
||||
value={name}
|
||||
maxLength={MAX_NAME}
|
||||
placeholder={`CAPTAIN ${i + 1}`}
|
||||
onChange={(e) => set(i, e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<Line> </Line>
|
||||
<div className="prompt-row">
|
||||
{names.length < MAX_CAPTAINS && (
|
||||
<Btn onClick={() => setNames((n) => [...n, ''])}>ONE MORE</Btn>
|
||||
)}
|
||||
<Btn kind="primary" onClick={() => onStart(names)}>
|
||||
CAST OFF
|
||||
</Btn>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- report
|
||||
|
||||
/** The end of one captain's patrol, before the next one sits down. */
|
||||
export function ReportScreen({
|
||||
patrol,
|
||||
captain,
|
||||
moreToCome,
|
||||
onNext,
|
||||
}: {
|
||||
patrol: Patrol
|
||||
captain: Captain
|
||||
moreToCome: boolean
|
||||
onNext: () => void
|
||||
}) {
|
||||
const won = isWin(patrol.outcome)
|
||||
return (
|
||||
<div className="stack report">
|
||||
<Line className={won ? 'accent' : 'warn'}>
|
||||
{patrol.outcome ? outcomeText(patrol.outcome) : ''}
|
||||
</Line>
|
||||
<Line> </Line>
|
||||
<Line>
|
||||
{captain.name} — {captain.killed} DESTROYED, {captain.daysLeft.toFixed(1)} DAYS LEFT,{' '}
|
||||
{captain.torpedoes} TORPEDO{captain.torpedoes === 1 ? '' : 'ES'}
|
||||
</Line>
|
||||
<Line className="dim">
|
||||
{patrol.raidersLeft} RAIDER{patrol.raidersLeft === 1 ? '' : 'S'} STILL OUT THERE.
|
||||
</Line>
|
||||
<Line> </Line>
|
||||
<Btn kind="primary" onClick={onNext}>
|
||||
{moreToCome ? 'NEXT CAPTAIN' : 'THAT IS THAT'}
|
||||
</Btn>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- standings
|
||||
|
||||
export function GameOverScreen({
|
||||
captains,
|
||||
onRestart,
|
||||
onScores,
|
||||
}: {
|
||||
captains: Captain[]
|
||||
onRestart: () => void
|
||||
onScores: () => void
|
||||
}) {
|
||||
const ranked = [...captains].sort(comparePatrols)
|
||||
const anyWon = captains.some((c) => isWin(c.outcome))
|
||||
return (
|
||||
<div className="stack over">
|
||||
<Line className="accent">
|
||||
{anyWon ? 'THE FLEET IS SATISFIED.' : 'THE RAIDERS ARE STILL OUT THERE.'}
|
||||
</Line>
|
||||
<Line> </Line>
|
||||
{ranked.map((c, i) => (
|
||||
<Line key={c.id}>
|
||||
{String(i + 1).padStart(2)}. {c.name.padEnd(MAX_NAME)}{' '}
|
||||
{String(c.killed).padStart(2)} KILLED {c.daysLeft.toFixed(1).padStart(5)} DAYS{' '}
|
||||
{String(c.torpedoes).padStart(2)} TORP
|
||||
</Line>
|
||||
))}
|
||||
<Line> </Line>
|
||||
<div className="prompt-row">
|
||||
<Btn kind="primary" onClick={onRestart}>
|
||||
AGAIN
|
||||
</Btn>
|
||||
<Btn onClick={onScores}>BOARD</Btn>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- board
|
||||
|
||||
export type BoardState = 'loading' | 'ready' | 'error'
|
||||
|
||||
export function HighScoreScreen({
|
||||
scores,
|
||||
state,
|
||||
highlight,
|
||||
onBack,
|
||||
onRetry,
|
||||
}: {
|
||||
scores: Score[]
|
||||
state: BoardState
|
||||
highlight: string[]
|
||||
onBack: () => void
|
||||
onRetry: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="stack board">
|
||||
<Line className="accent">THE BOARD</Line>
|
||||
<Line className="dim">RANKED ON RAIDERS DESTROYED, THEN DAYS LEFT, THEN TORPEDOES.</Line>
|
||||
<Line> </Line>
|
||||
{state === 'loading' && <Line>ASKING THE MACHINE...</Line>}
|
||||
{state === 'error' && (
|
||||
<>
|
||||
{/* The game is entirely playable without the board, and says so
|
||||
rather than pretending the patrol did not happen. */}
|
||||
<Line className="warn">THE BOARD IS NOT ANSWERING. YOUR PATROL STILL COUNTED.</Line>
|
||||
<Line> </Line>
|
||||
<Btn onClick={onRetry}>TRY AGAIN</Btn>
|
||||
</>
|
||||
)}
|
||||
{state === 'ready' && scores.length === 0 && <Line>NOBODY HAS REPORTED IN YET.</Line>}
|
||||
{state === 'ready' &&
|
||||
scores.map((s, i) => (
|
||||
<Line key={s.id} className={highlight.includes(s.id) ? 'accent' : ''}>
|
||||
{String(i + 1).padStart(2)}. {s.name.padEnd(MAX_NAME)}{' '}
|
||||
{String(s.killed).padStart(2)} {s.daysLeft.toFixed(1).padStart(5)}{' '}
|
||||
{String(s.torpedoes).padStart(2)}
|
||||
</Line>
|
||||
))}
|
||||
<Line> </Line>
|
||||
<Btn kind="primary" onClick={onBack}>
|
||||
BACK
|
||||
</Btn>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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.'
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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' }
|
||||
@@ -0,0 +1,46 @@
|
||||
:root {
|
||||
font-synthesis: none;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* The root is a flex item of body; without this the cabinet shrinks to fit. */
|
||||
#root {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* The room the machine is standing in: a terminal room in a university
|
||||
basement, lit by the ceiling and nothing else. */
|
||||
body {
|
||||
background: radial-gradient(120% 80% at 50% 0%, #5a5a5a 0%, #3a3a3a 55%, #232323 100%);
|
||||
color: #241f1a;
|
||||
font-family: ui-monospace, "DejaVu Sans Mono", "Cascadia Mono", "Courier New", monospace;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: clamp(8px, 2vw, 28px);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.001ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.001ms !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
/**
|
||||
* There is one skin so far, and it is the machine as it was. The remaster
|
||||
* will bring a provider and a toggle with it; until then the attribute is set
|
||||
* once here so the stylesheet has something to key off and nothing has to
|
||||
* pretend there is a choice.
|
||||
*/
|
||||
document.documentElement.dataset.skin = 'teletype'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
Reference in New Issue
Block a user