Back to The Bathyal Post
SOURCE / PINNED RELEASE

Made of little things.

The Bathyal Post

Release
fa6ce530b9f3…
Author-recorded commit
b255b3c9fd49…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-55c50b9a042

Archive hash verified: 03cf62191e7476c5…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/voyage.ts
/** The postal route advances by one watch on each crossing. All forecasts are exact. */
export type StopId = 'buoy' | 'medusa' | 'vent' | 'wreck' | 'whale' | 'garden' | 'trench';
export type Recipient = Extract<StopId, 'medusa' | 'whale' | 'garden' | 'trench'>;
export type Mode = 'drift' | 'drive';
export type Rig = 'standard' | 'baffles' | 'tanks' | 'keel';
export type Phase = 'sailing' | 'docked' | 'retired' | 'lost' | 'won';

export interface Stop {
  id: StopId;
  name: string;
  kind: 'home' | 'recipient' | 'service';
  x: number;
  y: number;
  depth: number;
  description: string;
}

export const STOPS: Record<StopId, Stop> = {
  buoy: { id: 'buoy', name: 'Post Buoy', kind: 'home', x: .15, y: .20, depth: 0,
    description: 'The sorting office rings a little brass bell whenever the line comes taut. Return here to close your bag.' },
  medusa: { id: 'medusa', name: 'Bell Medusa', kind: 'recipient', x: .44, y: .26, depth: 180,
    description: 'She takes her letters folded into eighths. Her lace muffles your next two drives.' },
  vent: { id: 'vent', name: 'Breathing Vent', kind: 'service', x: .20, y: .59, depth: 640,
    description: 'A lung in the basalt. Its first exhalation each bag adds six air, up to capacity.' },
  wreck: { id: 'wreck', name: 'Postal Wreck', kind: 'service', x: .55, y: .60, depth: 670,
    description: 'The previous mail boat. Salvage two hull here once per bag. Something rattles in its sorting drawer.' },
  whale: { id: 'whale', name: 'Choir Whale', kind: 'recipient', x: .78, y: .28, depth: 340,
    description: 'Six voices share one enormous set of lungs. A delivery earns four air.' },
  garden: { id: 'garden', name: 'Lamp Garden', kind: 'recipient', x: .78, y: .76, depth: 920,
    description: 'A field of lamps with one name on the electoral roll. A delivery grows two hull plates.' },
  trench: { id: 'trench', name: 'Trench Mouth', kind: 'recipient', x: .42, y: .85, depth: 1180,
    description: 'Speak into the slot in the seafloor. A delivery makes the whole sea forget your wake.' },
};

export const EDGES: [StopId, StopId][] = [
  ['buoy', 'medusa'], ['buoy', 'vent'], ['medusa', 'whale'], ['medusa', 'wreck'],
  ['vent', 'wreck'], ['vent', 'trench'], ['wreck', 'whale'], ['wreck', 'garden'],
  ['wreck', 'trench'], ['whale', 'garden'], ['garden', 'trench'],
];

export const RIGS: Record<Rig, {name: string; description: string}> = {
  standard: {name: 'Postal issue', description: 'The ordinary brass bell of the night service.'},
  tanks: {name: 'Twin tanks', description: 'Carry three extra air on the next dive.'},
  baffles: {name: 'Felt baffles', description: 'Each drive makes one less wake.'},
  keel: {name: 'Iron keel', description: 'Cancel hull strain when driving into the deep.'},
};

export interface Letter {
  id: string;
  to: Recipient;
  title: string;
  body: string;
  reward: number;
  postClass: 'quiet' | 'express' | 'fragile' | 'forwarded';
  condition: string;
  delivered: boolean;
}

type LetterText = [title: string, body: string];
const POST: Record<Recipient, LetterText[]> = {
  medusa: [
    ['A thimble of rain', 'Auntie, I held a cup out when the storm came. Is this how the sky tasted when you were small?'],
    ['Darning instructions', 'Dear sister, pull the torn edges of your bell together. Start at the bite mark. I have enclosed my longest thread.'],
    ['The low ceiling', 'I have hung nine paper moons over the cot. The little one opens and closes her hands to keep them afloat.'],
    ['An invitation in salt', 'Mother, we are gathering at the old tide mark. Wear the pink that only the shrimp can see.'],
    ['Pressed violets', 'They lose their colour when you take them down. I drew round each one so you would know where to smell.'],
  ],
  whale: [
    ['The missing sixth', 'Father, I found the note that fell out of your song. You were humming it against my pillow the night you left.'],
    ['A season ticket', 'Two stalls, one evening, no ceiling. The plankton will put on their green lights if you start us in the right key.'],
    ['Breathing lessons', 'There is a boy on the pier who thinks the whole sea rises because you breathe in. Would you write back and say he is close?'],
    ['A name in longhand', 'Here is the name you asked for, written from end to end of this roll. Allow the full afternoon to say it.'],
    ['An unsigned score', 'Bar twelve is a rest. It is where I hope to hear the child singing back.'],
  ],
  garden: [
    ['Seeds from the dark', 'Dear Keeper, the lamps you sent have taken in the cellar. Yesterday a moth came all the way down the stairs.'],
    ['An empty matchbook', 'For the lights that never see a window. Strike the little strip with a tooth and remember us in winter.'],
    ['A census of bulbs', 'Three hundred lit, two asleep, and one that blinks when called by her maiden name. Please amend last year’s ledger.'],
    ['The night gardener', 'Keep one furrow dark. Some of the children are carrying stars and would like to see them on the way home.'],
    ['A parcel of roots', 'I send the bottom halves. We will know they have met when the trees up here begin to shine.'],
  ],
  trench: [
    ['Return my echo', 'I dropped my brother’s name down there on Tuesday. If it has reached you, please send it home before supper.'],
    ['A small confession', 'Keeper of Lost Depths, I drew the bottom on the first chart. I was tired and the paper had run out.'],
    ['Receipt for a shadow', 'I have received the dark you sent and put it under the bed. The baby sleeps past dawn now.'],
    ['Care of nobody', 'Whoever opens this, hold the paper up to your ear. I have put the sound of a kettle on it.'],
    ['The last collection', 'We are taking down the box at the end of our road. I thought you should have its last small clatter.'],
  ],
};

export function archivedLetters(postmarks: readonly string[]) {
  const letters = [];
  for (const [to, texts] of Object.entries(POST)) {
    for (const [serial, [title, body]] of texts.entries()) {
      if (postmarks.includes(to + '-' + serial)) letters.push({to: to as Recipient, title, body});
    }
  }
  return letters;
}

export type NoticeKind = 'launch' | 'travel' | 'delivery' | 'service' | 'attack' | 'dock' | 'loss' | 'secret';
export interface Notice { kind: NoticeKind; title: string; text: string }
export interface Voyage {
  version: 1;
  seed: number;
  bag: number;
  quota: number;
  at: StopId;
  air: number;
  maxAir: number;
  hull: number;
  maxHull: number;
  wake: number;
  turn: number;
  score: number;
  phase: Phase;
  letters: Letter[];
  rig: Rig;
  reserve: number;
  lace: number;
  ventUsed: boolean;
  wreckUsed: boolean;
  strained: boolean;
  deadLetter: 'hidden' | 'carried' | 'posted';
  totalDelivered: number;
  last: Notice;
  log: string[];
}

export interface Forecast {
  airCost: number;
  hullCost: number;
  wakeAfter: number;
  attack: boolean;
  pressure: boolean;
  hunted: boolean;
  quiet: boolean;
  fatal: boolean;
  current: 'with' | 'slack' | 'against';
  summary: string;
}

const recipients: Recipient[] = ['medusa', 'whale', 'garden', 'trench'];
const MAX_WAKE = 6;
const premiumPostage = 6;

// Stateless mixing makes letter draws independent of any path taken by the player.
function hash(seed: number, salt: number): number {
  let value = Math.imul(seed ^ salt, 0x45d9f3b);
  value = Math.imul(value ^ (value >>> 16), 0x45d9f3b);
  return (value ^ (value >>> 16)) >>> 0;
}

function makeLetters(seed: number, bag: number): Letter[] {
  const shuffled = [...recipients].sort((a, b) => {
    if (a === b) return 0;
    if (bag === 1 && (a === 'medusa' || b === 'medusa')) return a === 'medusa' ? -1 : 1;
    return hash(seed, bag * 31 + recipients.indexOf(a)) - hash(seed, bag * 31 + recipients.indexOf(b));
  });
  return shuffled.slice(0, bag + 1).map((to, i) => {
    const pool = POST[to];
    const serial = (hash(seed, recipients.indexOf(to) + 9) % pool.length + bag - 1) % pool.length;
    const [title, body] = pool[serial];
    const classes = ['quiet', 'express', 'fragile', 'forwarded'] as const;
    const postClass = bag === 1 && i === 0 ? 'quiet' : classes[(serial + i + bag) % classes.length];
    const conditions = {
      quiet: 'Quiet post · arrive at wake 0–1',
      express: 'Express · by watch ' + (bag + 2),
      fragile: 'Glass post · avoid hull damage',
      forwarded: 'Forwarded · deliver another first',
    };
    return {id: to + '-' + serial, to, title, body, postClass, condition: conditions[postClass],
      reward: 8 + 2 * recipients.indexOf(to) + bag, delivered: false};
  });
}

export function newVoyage(seed: number): Voyage {
  const number = seed >>> 0;
  const last: Notice = {kind: 'launch', title: 'First collection', text: 'Take a letter to the Bell Medusa. Bring at least one postmark back to the buoy.'};
  return {
    version: 1, seed: number, bag: 1, quota: 1, at: 'buoy', maxAir: 13, air: 13,
    maxHull: 5, hull: 5, wake: 0, turn: 0, score: 0, phase: 'sailing', rig: 'standard', reserve: 0,
    lace: 0, ventUsed: false, wreckUsed: false, strained: false, deadLetter: 'hidden', totalDelivered: 0,
    letters: makeLetters(number, 1), last, log: [last.text],
  };
}

export function nextBag(state: Voyage, rig: Rig = 'tanks'): Voyage {
  if (state.phase !== 'docked' || state.bag >= 3 || !Object.hasOwn(RIGS, rig)) return state;
  const bag = state.bag + 1;
  const reserve = state.reserve + Number(state.letters.every(letter => letter.delivered));
  const maxAir = (bag === 2 ? 9 : 7) + reserve + (rig === 'tanks' ? 3 : 0);
  const last: Notice = {kind: 'launch', title: 'Collection ' + bag,
    text: RIGS[rig].name + ' fitted. Bring back ' + bag + ' postmarks. ' +
      (state.hull === state.maxHull ? 'Hull inspection passed.' : 'The sorting office mended ' + Math.min(2, state.maxHull - state.hull) + ' hull.')};
  return {...state, bag, quota: bag, turn: 0, at: 'buoy', air: maxAir, maxAir,
    hull: Math.min(state.maxHull, state.hull + 2), wake: 0, rig, reserve,
    phase: 'sailing', letters: makeLetters(state.seed, bag), lace: 0, ventUsed: false, wreckUsed: false, strained: false,
    deadLetter: state.deadLetter === 'posted' ? 'posted' : 'hidden', last, log: appendEntry(state, last)};
}

function appendEntry(state: Voyage, notice: Notice): string[] {
  return [...state.log.slice(-31), notice.title + ' — ' + notice.text];
}

export function neighbours(at: StopId): StopId[] {
  return EDGES.flatMap(([a,b]) => at === a ? [b] : at === b ? [a] : []);
}

export function deliveredCount(state: Voyage): number {
  return state.letters.filter(letter => letter.delivered).length;
}

const TIDES = ['Flood', 'High water', 'Ebb', 'Low water'] as const;
function tidePhase(state: Voyage): number {
  return (state.turn + (state.bag === 1 ? 0 : hash(state.seed, state.bag) % 4)) % 4;
}
export function tideName(state: Voyage): string { return TIDES[tidePhase(state)]; }

function currentOn(state: Voyage, to: StopId): Forecast['current'] {
  const tide = tidePhase(state);
  if (tide === 1 || tide === 3) return 'slack';
  const descending = STOPS[to].depth > STOPS[state.at].depth;
  return (tide === 0) === descending ? 'with' : 'against';
}

/** After the first bag the Listener hunts one mooring per watch. */
export function huntingGround(state: Voyage): StopId | null {
  if (state.bag === 1 || state.phase !== 'sailing') return null;
  const trail: StopId[] = ['medusa', 'whale', 'garden', 'trench', 'vent', 'wreck'];
  return trail[(hash(state.seed, state.bag + 7) + state.turn) % trail.length];
}

function arrivalAir(state: Voyage, to: StopId): number {
  if (to === 'vent' && !state.ventUsed) return 6;
  return to === 'whale' && state.letters.some(letter => letter.to === to && !letter.delivered) ? 4 : 0;
}

export function forecast(state: Voyage, to: StopId, mode: Mode): Forecast | null {
  if (state.phase !== 'sailing' || !neighbours(state.at).includes(to) || (mode !== 'drive' && mode !== 'drift')) return null;
  const current = currentOn(state, to);
  const powered = mode === 'drive';
  const driftCost = {with: 1, slack: state.bag === 1 ? 2 : 3, against: state.bag + 2};
  const airCost = powered ? 1 : driftCost[current];
  const hunted = powered && state.lace === 0 && to === huntingGround(state);
  const springWake = Number(state.bag > 1 && (current !== 'with' || state.bag === 3));
  const driveWake = state.lace > 0 ? 0 : 2 + Number(current === 'against') + springWake + 2 * Number(hunted) - Number(state.rig === 'baffles');
  const rawWake = powered ? state.wake + driveWake : Math.max(0, state.wake - 2);
  const attack = rawWake >= MAX_WAKE;
  const pressure = powered && state.rig !== 'keel' && STOPS[to].depth >= 900 && STOPS[to].depth > STOPS[state.at].depth;
  const bite = attack ? state.bag + 1 : 0;
  const hullCost = Number(pressure) + bite;
  const trenchLetter = to === 'trench' && state.letters.some(letter => letter.to === to && !letter.delivered);
  const wakeAfter = trenchLetter ? 0 : attack ? 1 : rawWake;
  const ranDry = airCost > state.air || (airCost === state.air && to !== 'buoy' && !arrivalAir(state, to));
  const fatal = ranDry || hullCost >= state.hull;
  const notes = [airCost + ' air'];
  if (hunted) notes.push('hunting ground +2 drive wake');
  if (pressure) notes.push('deep strain −1 hull');
  if (attack) notes.push('Listener strike −' + bite + ' hull');
  if (fatal) notes.push(ranDry ? 'air runs out on this leg' : 'hull fails on this leg');
  else if (to === 'buoy') notes.push(deliveredCount(state) < state.quota ? 'return below quota ends the shift' : 'close bag at the buoy');
  else if (to === 'vent' && !state.ventUsed) notes.push('vent +' + Math.min(6, state.maxAir - state.air + airCost) + ' air');
  else if (to === 'wreck' && !state.wreckUsed) notes.push('salvage +' + Math.min(2, state.maxHull - state.hull + hullCost) + ' hull');
  else if (state.letters.some(letter => letter.to === to && !letter.delivered)) notes.push('letter delivered');
  return {current, airCost, hullCost, wakeAfter, attack, pressure, hunted, quiet: rawWake <= 1, fatal, summary: notes.join(' · ')};
}

function deliver(state: Voyage, letter: Letter, quietArrival: boolean): Notice {
  let favor: string;
  switch (letter.to) {
    case 'medusa':
      state.lace = 2;
      favor = 'She ties lace round the screw. Your next two drives make no wake.';
      break;
    case 'whale': {
      const breath = Math.min(4, state.maxAir - state.air);
      state.air += breath;
      favor = 'Six mouths sing into the reserve tank. +' + breath + ' air.';
      break;
    }
    case 'garden': {
      const plates = Math.min(2, state.maxHull - state.hull);
      state.hull += plates;
      favor = plates ? 'New brass sprouts over the rivets. +' + plates + ' hull.' : 'The lamps inspect your rivets and find every one sound.';
      break;
    }
    case 'trench':
      state.wake = 0;
      favor = 'The trench swallows even the sound of your passing. Wake cleared.';
      break;
  }
  const qualifies = {
    quiet: quietArrival,
    express: state.turn <= state.bag + 2,
    fragile: !state.strained,
    forwarded: deliveredCount(state) > 0,
  };
  const bonus = qualifies[letter.postClass] ? premiumPostage : 0;
  state.letters = state.letters.map(item => item.id === letter.id ? {...letter, delivered: true} : item);
  state.score += letter.reward + bonus;
  state.totalDelivered++;
  return {kind: 'delivery', title: letter.title, text: favor + ' +' + (letter.reward + bonus) + ' postage' + (bonus ? ' with the class premium.' : '.')};
}

export function travel(state: Voyage, to: StopId, mode: Mode): Voyage {
  const leg = forecast(state, to, mode);
  if (!leg) return state;
  const next: Voyage = {...state, at: to, turn: state.turn + 1,
    air: Math.max(0, state.air - leg.airCost), hull: Math.max(0, state.hull - leg.hullCost),
    wake: leg.wakeAfter, strained: state.strained || leg.hullCost > 0, lace: Math.max(0, state.lace - Number(mode === 'drive'))};
  const arrival = STOPS[to];
  let notice: Notice = {kind: 'travel', title: arrival.name, text: 'Crossing logged. ' + (mode === 'drift' ? 'The screw is still.' : 'The screw winds down.')};
  if (leg.fatal) {
    next.phase = 'lost';
    notice = {kind: 'loss', title: next.hull === 0 ? 'The rivets gave' : 'The last breath',
      text: next.hull === 0 ? 'The emergency mail float breaks free of the bell. The office receives your log at dawn.' : 'The air gauge touches its brass stop. Above you, an empty line rings the sorting bell.'};
  } else if (to === 'buoy') {
    const posted = deliveredCount(next);
    next.phase = posted < next.quota ? 'retired' : next.bag === 3 ? 'won' : 'docked';
    const bonus = posted >= next.quota ? next.air + 2 * next.hull + (posted === next.letters.length ? 10 : 0) : 0;
    next.score += bonus;
    notice = {kind: 'dock', title: next.phase === 'won' ? 'The dawn collection' : next.phase === 'retired' ? 'Early recall' : 'Bag signed in',
      text: next.phase === 'retired' ? 'The crew is safe. The next courier takes the unfinished rounds.' :
        posted + ' postmarks received. +' + bonus + ' return postage.' + (posted === next.letters.length && next.bag < 3 ? ' A full bag earns one extra air capacity.' : '')};
  } else {
    if (to === 'vent' && !state.ventUsed) {
      next.air = Math.min(next.maxAir, next.air + 6);
      next.ventUsed = true;
      notice = {kind: 'service', title: 'A borrowed breath', text: 'The vent sighs air into your tanks. It needs the rest of this round to refill.'};
    }
    if (to === 'wreck' && !state.wreckUsed) {
      const recovered = Math.min(2, next.maxHull - next.hull);
      next.hull += recovered;
      next.wreckUsed = true;
      if (next.deadLetter === 'hidden') next.deadLetter = 'carried';
      notice = {kind: 'service', title: 'The sorting drawer', text: (recovered ? 'Spare plates restore ' + recovered + ' hull.' : 'The hull is sound.') + (next.deadLetter === 'carried' ? ' An old envelope reads “Where the sea opens its mouth.”' : ' The empty drawer slides shut.')};
    }
    const letter = next.letters.find(item => item.to === to && !item.delivered);
    if (letter) notice = deliver(next, letter, leg.quiet);
    if (to === 'trench' && next.deadLetter === 'carried') {
      next.deadLetter = 'posted';
      next.score += 18;
      const first = letter ? notice.text + ' ' : '';
      notice = {kind: 'secret', title: 'The black postmark', text: first + 'The wreck’s envelope slips between two stones. A voice says, “About time.” +18 postage.'};
    }
    if (leg.hullCost) {
      const cost = leg.attack ? 'The Listener catches your wake.' : 'Deep pressure bites.';
      notice = {kind: notice.kind === 'travel' && leg.attack ? 'attack' : notice.kind, title: notice.title,
        text: cost + ' −' + leg.hullCost + ' hull. ' + notice.text};
    }
  }
  next.last = notice;
  next.log = appendEntry(state, notice);
  return next;
}

function integer(value: unknown, min: number, max: number): value is number {
  return typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max;
}
function record(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function member<T extends string>(value: unknown, choices: readonly T[]): value is T {
  return typeof value === 'string' && (choices as readonly string[]).includes(value);
}
function smallText(value: unknown): value is string { return typeof value === 'string' && value.length <= 700; }

/** Treat saved games as untrusted and reject incompatible or partial checkpoints. */
export function isVoyage(value: unknown): value is Voyage {
  if (!record(value) || value.version !== 1 || !integer(value.bag, 1, 3) || !integer(value.seed, 0, 0xffffffff)) return false;
  const v = value;
  const bag = value.bag;
  if (v.quota !== bag || !member(v.at, Object.keys(STOPS)) || !member(v.phase, ['sailing','docked','retired','lost','won']) ||
    !member(v.rig, Object.keys(RIGS)) || !integer(v.maxAir, 7, 16) || !integer(v.air, 0, v.maxAir) || v.maxHull !== 5 ||
    !integer(v.hull, 0, 5) || !integer(v.wake, 0, 5) || !integer(v.turn, 0, 512) ||
    !integer(v.score, 0, 10000) || !integer(v.reserve, 0, 2) || !integer(v.lace, 0, 2) ||
    typeof v.ventUsed !== 'boolean' || typeof v.wreckUsed !== 'boolean' || typeof v.strained !== 'boolean' || !member(v.deadLetter, ['hidden','carried','posted']) ||
    !integer(v.totalDelivered, 0, 9) || !Array.isArray(v.letters) || v.letters.length !== bag + 1 ||
    !Array.isArray(v.log) || !v.log.length || v.log.length > 32 || !v.log.every(smallText) || !record(v.last) ||
    !member(v.last.kind, ['launch','travel','delivery','service','attack','dock','loss','secret']) ||
    !smallText(v.last.title) || !smallText(v.last.text)) return false;
  const expected = makeLetters(value.seed, bag);
  return v.letters.every((item, i) => record(item) && item.id === expected[i].id && item.to === expected[i].to &&
    item.postClass === expected[i].postClass && item.condition === expected[i].condition &&
    item.title === expected[i].title && item.body === expected[i].body && item.reward === expected[i].reward && typeof item.delivered === 'boolean');
}