From 0fe0f52a5307fc4b87420a3ac4da7fb48e603a5e Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Thu, 19 Nov 2026 21:03:23 -0700 Subject: [PATCH] Add STARLANE door game and door framework - Introduce a pluggable door system (src/doors/) with registry, menu, and DoorModule contract so games are self-contained and isolated from core BBS code - Add STARLANE: a frontier space-trading door with universe generation, lane pathfinding, commodity trading/haggling, combat, planet seeding/bastions, syndicates, Reaver NPCs, and a world ticker - Extend db.ts with transaction helper (withTx) and namespaced migrations so doors can ship their own SQL under src/doors//migrations - Add shared UI widgets (box, menus, number/list prompts) and Session notice/promptChoice support for live cross-node messages - Wire door init and migration into server startup, add copy-assets build step for SQL files, and update README/CLAUDE docs --- CLAUDE.md | 35 +++ Dockerfile | 1 + README.md | 24 +- package.json | 5 +- scripts/copy-assets.mjs | 16 ++ src/db.ts | 48 +++- src/doors/CLAUDE.md | 29 ++ src/doors/doorMenu.ts | 58 ++++ src/doors/registry.ts | 5 + src/doors/starlane/CLAUDE.md | 54 ++++ src/doors/starlane/actions/damage.ts | 10 + src/doors/starlane/actions/fate.ts | 54 ++++ src/doors/starlane/art/scenes.ts | 59 ++++ src/doors/starlane/art/title.ts | 58 ++++ src/doors/starlane/config.ts | 63 ++++ src/doors/starlane/data/names.ts | 40 +++ src/doors/starlane/data/planets.ts | 45 +++ src/doors/starlane/data/ranks.ts | 27 ++ src/doors/starlane/data/ships.ts | 34 +++ src/doors/starlane/engine/combat.test.ts | 35 +++ src/doors/starlane/engine/combat.ts | 90 ++++++ src/doors/starlane/engine/commodities.ts | 28 ++ src/doors/starlane/engine/haggle.test.ts | 43 +++ src/doors/starlane/engine/haggle.ts | 64 +++++ src/doors/starlane/engine/pathfind.test.ts | 31 ++ src/doors/starlane/engine/pathfind.ts | 97 +++++++ src/doors/starlane/engine/planets.test.ts | 36 +++ src/doors/starlane/engine/planets.ts | 51 ++++ src/doors/starlane/engine/pricing.test.ts | 30 ++ src/doors/starlane/engine/pricing.ts | 43 +++ src/doors/starlane/engine/rng.ts | 26 ++ src/doors/starlane/engine/universe.test.ts | 51 ++++ src/doors/starlane/engine/universe.ts | 203 +++++++++++++ src/doors/starlane/index.ts | 88 ++++++ src/doors/starlane/migrations/001_init.sql | 143 ++++++++++ src/doors/starlane/repo/defenses.ts | 47 +++ src/doors/starlane/repo/news.ts | 54 ++++ src/doors/starlane/repo/npcs.ts | 46 +++ src/doors/starlane/repo/planets.ts | 91 ++++++ src/doors/starlane/repo/players.ts | 132 +++++++++ src/doors/starlane/repo/q.ts | 10 + src/doors/starlane/repo/syndicates.ts | 38 +++ src/doors/starlane/repo/world.ts | 128 +++++++++ src/doors/starlane/screens/arrival.ts | 191 +++++++++++++ src/doors/starlane/screens/bazaar.ts | 291 +++++++++++++++++++ src/doors/starlane/screens/combat.ts | 249 ++++++++++++++++ src/doors/starlane/screens/computer.ts | 119 ++++++++ src/doors/starlane/screens/deploy.ts | 62 ++++ src/doors/starlane/screens/help.ts | 36 +++ src/doors/starlane/screens/info.ts | 90 ++++++ src/doors/starlane/screens/main.ts | 58 ++++ src/doors/starlane/screens/move.ts | 76 +++++ src/doors/starlane/screens/planet.ts | 317 +++++++++++++++++++++ src/doors/starlane/screens/port.ts | 195 +++++++++++++ src/doors/starlane/screens/scan.ts | 97 +++++++ src/doors/starlane/screens/sectorView.ts | 69 +++++ src/doors/starlane/screens/syndicate.ts | 158 ++++++++++ src/doors/starlane/screens/sysop.ts | 69 +++++ src/doors/starlane/screens/ui.ts | 38 +++ src/doors/starlane/ticker.ts | 149 ++++++++++ src/doors/types.ts | 22 ++ src/nodes.ts | 20 ++ src/screens/mainMenu.ts | 27 +- src/server.ts | 4 +- src/session/Session.ts | 56 ++++ src/ui/box.ts | 21 ++ src/ui/widgets.ts | 63 ++++ 67 files changed, 4715 insertions(+), 32 deletions(-) create mode 100644 CLAUDE.md create mode 100644 scripts/copy-assets.mjs create mode 100644 src/doors/CLAUDE.md create mode 100644 src/doors/doorMenu.ts create mode 100644 src/doors/registry.ts create mode 100644 src/doors/starlane/CLAUDE.md create mode 100644 src/doors/starlane/actions/damage.ts create mode 100644 src/doors/starlane/actions/fate.ts create mode 100644 src/doors/starlane/art/scenes.ts create mode 100644 src/doors/starlane/art/title.ts create mode 100644 src/doors/starlane/config.ts create mode 100644 src/doors/starlane/data/names.ts create mode 100644 src/doors/starlane/data/planets.ts create mode 100644 src/doors/starlane/data/ranks.ts create mode 100644 src/doors/starlane/data/ships.ts create mode 100644 src/doors/starlane/engine/combat.test.ts create mode 100644 src/doors/starlane/engine/combat.ts create mode 100644 src/doors/starlane/engine/commodities.ts create mode 100644 src/doors/starlane/engine/haggle.test.ts create mode 100644 src/doors/starlane/engine/haggle.ts create mode 100644 src/doors/starlane/engine/pathfind.test.ts create mode 100644 src/doors/starlane/engine/pathfind.ts create mode 100644 src/doors/starlane/engine/planets.test.ts create mode 100644 src/doors/starlane/engine/planets.ts create mode 100644 src/doors/starlane/engine/pricing.test.ts create mode 100644 src/doors/starlane/engine/pricing.ts create mode 100644 src/doors/starlane/engine/rng.ts create mode 100644 src/doors/starlane/engine/universe.test.ts create mode 100644 src/doors/starlane/engine/universe.ts create mode 100644 src/doors/starlane/index.ts create mode 100644 src/doors/starlane/migrations/001_init.sql create mode 100644 src/doors/starlane/repo/defenses.ts create mode 100644 src/doors/starlane/repo/news.ts create mode 100644 src/doors/starlane/repo/npcs.ts create mode 100644 src/doors/starlane/repo/planets.ts create mode 100644 src/doors/starlane/repo/players.ts create mode 100644 src/doors/starlane/repo/q.ts create mode 100644 src/doors/starlane/repo/syndicates.ts create mode 100644 src/doors/starlane/repo/world.ts create mode 100644 src/doors/starlane/screens/arrival.ts create mode 100644 src/doors/starlane/screens/bazaar.ts create mode 100644 src/doors/starlane/screens/combat.ts create mode 100644 src/doors/starlane/screens/computer.ts create mode 100644 src/doors/starlane/screens/deploy.ts create mode 100644 src/doors/starlane/screens/help.ts create mode 100644 src/doors/starlane/screens/info.ts create mode 100644 src/doors/starlane/screens/main.ts create mode 100644 src/doors/starlane/screens/move.ts create mode 100644 src/doors/starlane/screens/planet.ts create mode 100644 src/doors/starlane/screens/port.ts create mode 100644 src/doors/starlane/screens/scan.ts create mode 100644 src/doors/starlane/screens/sectorView.ts create mode 100644 src/doors/starlane/screens/syndicate.ts create mode 100644 src/doors/starlane/screens/sysop.ts create mode 100644 src/doors/starlane/screens/ui.ts create mode 100644 src/doors/starlane/ticker.ts create mode 100644 src/doors/types.ts create mode 100644 src/ui/box.ts create mode 100644 src/ui/widgets.ts diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..29e09a4 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,35 @@ +# WarezHou$e BBS + +Late-80s style BBS in the browser. Node 22 + TypeScript (strict, CommonJS), Postgres 16, xterm.js front end. +Callers connect over a WebSocket; all BBS logic runs server-side and writes ANSI to a dumb terminal. + +## Commands +- `npm run build`: tsc, then `scripts/copy-assets.mjs` copies `src/**/*.sql` into `dist/` +- `npm test`: build, then `node --test` on `dist/**/*.test.js` (pure engine code only, no DB) +- `docker compose up -d --build`: full stack at http://localhost:8080; `docker compose logs app` + +## Architecture (core) +| Path | Role | +|---|---| +| `src/server.ts` | HTTP/WS server, node slots, runs migrations then each door's `init()` | +| `src/session/Session.ts` | One caller: throttled output, `readKey/readChoice/readLine/yesNo/pause`, notices | +| `src/session/ansi.ts` | Pipe colour codes (`|00`-`|15` fg, `|16`-`|23` bg, `|CL`), `padRight`, `center`, `esc` | +| `src/ui/` | Shared widgets: `makeBox`, `menuItem`, `readNumber`, `pickFromList`, `commas`, `padLeft` | +| `src/nodes.ts` | Live sessions; `notifyUser(userId, text)`, `broadcast(text)` | +| `src/db.ts` | `pool`, `withTx(fn)`, `migrate()`; BIGINT comes back as JS number | +| `src/screens/` | Core BBS screens (logon, new user, main menu) | +| `src/doors/` | Door framework + one folder per door (see `src/doors/CLAUDE.md`) | +| `db/migrations/` | Core SQL migrations, applied in filename order on start | + +## Conventions +- **Screens fit 80x25.** Keep lines within 79 visible chars; use `vlen()` for padding text with pipe codes. +- All output goes through `Session` (`print`/`println` take pipe codes). Escape user text with `esc()` before embedding it. +- Hotkey prompts that should show live messages use `s.promptChoice(prompt, keys)` (single-line prompt). +- Multi-row state changes go in `withTx`, with `SELECT ... FOR UPDATE` on the rows you read then write. +- `Disconnected` is thrown from any I/O when the caller drops; let it propagate. + +## Modularity rule +Core code never imports from a door except via `src/doors/registry.ts`. A door imports only from +`src/session/*`, `src/ui/*`, `src/db.ts`, `src/nodes.ts` and `src/users/userRepo.ts` (types, `isSysop`). +Doors never import from each other or from `src/screens/`. Each area keeps its own `CLAUDE.md`; +when working inside a door, its folder plus this API is all the context needed. diff --git a/Dockerfile b/Dockerfile index 3240b3a..8538801 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,6 +3,7 @@ WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci COPY tsconfig.json ./ +COPY scripts ./scripts COPY src ./src RUN npm run build && npm prune --omit=dev diff --git a/README.md b/README.md index b04944c..ab45fbe 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,9 @@ Settings (`.env`): `PORT`, `BAUD` (simulated output speed, `0` = unthrottled), | `src/session/Session.ts` | Per-caller I/O: baud-throttled output, hotkeys, line input | | `src/session/ansi.ts` | Pipe colour codes (`|00`-`|15` fg, `|16`-`|23` bg, `|CL`) | | `src/screens/` | Welcome/logon, login, new user, main menu | +| `src/ui/` | Shared widgets (boxes, menus, number prompts) | +| `src/doors/` | Door framework (`registry.ts`, `doorMenu.ts`) and one folder per door | +| `src/doors/starlane/` | **STARLANE**, a frontier space-trading door game | | `src/art/welcome.ts` | Welcome ANSI art | | `src/users/userRepo.ts` | User accounts (bcrypt), call log | | `db/migrations/` | SQL migrations, applied automatically on start | @@ -39,9 +42,24 @@ Settings (`.env`): `PORT`, `BAUD` (simulated output speed, `0` = unthrottled), ## Adding things -- **New screen / door game:** add a module under `src/screens/` that takes a - `Session`, and wire a key to it in `src/screens/mainMenu.ts`. -- **New tables:** add `db/migrations/002_whatever.sql`; it runs on next start. +- **New screen:** add a module under `src/screens/` that takes a `Session`, and + wire a key to it in `src/screens/mainMenu.ts`. +- **New door game:** create `src/doors//index.ts` exporting a `DoorModule` + and add it to `src/doors/registry.ts`. See `src/doors/CLAUDE.md`. +- **New tables:** core tables go in `db/migrations/002_whatever.sql`. A door + keeps its own in `src/doors//migrations/`. Both run on next start. + +## Tests + +`npm test` builds and runs the unit tests (pure game-engine logic, no database). + +## STARLANE + +The first door. Trade between ports, haggle with brokers, fight Reavers and +other callers, seed planets and build Bastions, form Syndicates. Turns refill +daily. The universe is generated on first start. The Sysop (first account) can +press **Z** in-game to edit pilots or trigger a Big Bang (new universe). +Design notes live in `src/doors/starlane/CLAUDE.md`. ## Database access diff --git a/package.json b/package.json index e9be403..ed6a84f 100644 --- a/package.json +++ b/package.json @@ -5,9 +5,10 @@ "description": "WarezHou$e - a late 80s / early 90s style BBS for the browser", "main": "dist/server.js", "scripts": { - "build": "tsc -p tsconfig.json", + "build": "tsc -p tsconfig.json && node scripts/copy-assets.mjs", "start": "node dist/server.js", - "dev": "tsc -p tsconfig.json && node dist/server.js" + "dev": "npm run build && node dist/server.js", + "test": "npm run build && node --test \"dist/**/*.test.js\"" }, "engines": { "node": ">=20" diff --git a/scripts/copy-assets.mjs b/scripts/copy-assets.mjs new file mode 100644 index 0000000..1710c96 --- /dev/null +++ b/scripts/copy-assets.mjs @@ -0,0 +1,16 @@ +// Copies non-TS assets (door SQL migrations) from src/ to dist/ after tsc. +import fs from 'fs'; +import path from 'path'; + +function walk(dir) { + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) walk(p); + else if (e.name.endsWith('.sql')) { + const out = path.join('dist', path.relative('src', p)); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.copyFileSync(p, out); + } + } +} +walk('src'); diff --git a/src/db.ts b/src/db.ts index 7cf6bae..37f87ea 100644 --- a/src/db.ts +++ b/src/db.ts @@ -1,10 +1,30 @@ import fs from 'fs'; import path from 'path'; -import { Pool } from 'pg'; +import { Pool, types } from 'pg'; + +// BIGINT (int8) columns and COUNT(*) come back as JS numbers rather than +// strings. Safe for values below 2^53, which is all this BBS stores. +types.setTypeParser(20, (v) => Number(v)); // Connection settings come from the standard PG* environment variables. export const pool = new Pool({ max: 10 }); +/** Runs `fn` inside BEGIN/COMMIT on one client, rolling back on error. */ +export async function withTx(fn: (c: import('pg').PoolClient) => Promise): Promise { + const c = await pool.connect(); + try { + await c.query('BEGIN'); + const out = await fn(c); + await c.query('COMMIT'); + return out; + } catch (err) { + await c.query('ROLLBACK').catch(() => {}); + throw err; + } finally { + c.release(); + } +} + const MIGRATIONS_DIR = path.resolve(__dirname, '..', 'db', 'migrations'); const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); @@ -21,8 +41,17 @@ async function waitForDb(retries = 30): Promise { } } -/** Applies any db/migrations/*.sql files not yet recorded, in filename order. */ -export async function migrate(): Promise { +export interface MigrationSource { + /** Prefix recorded in schema_migrations ("" for core, "starlane/" for a door). */ + namespace: string; + dir: string; +} + +/** + * Applies any *.sql files not yet recorded, in filename order: core + * db/migrations first, then each extra source (door migrations). + */ +export async function migrate(extra: MigrationSource[] = []): Promise { await waitForDb(); const client = await pool.connect(); try { @@ -31,10 +60,17 @@ export async function migrate(): Promise { name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())`); const { rows } = await client.query<{ name: string }>('SELECT name FROM schema_migrations'); const applied = new Set(rows.map((r) => r.name)); - const files = fs.readdirSync(MIGRATIONS_DIR).filter((f) => f.endsWith('.sql')).sort(); - for (const file of files) { + const sources: MigrationSource[] = [{ namespace: '', dir: MIGRATIONS_DIR }, ...extra]; + const todo: { name: string; file: string }[] = []; + for (const src of sources) { + if (!fs.existsSync(src.dir)) continue; + for (const f of fs.readdirSync(src.dir).filter((x) => x.endsWith('.sql')).sort()) { + todo.push({ name: src.namespace + f, file: path.join(src.dir, f) }); + } + } + for (const { name: file, file: fullPath } of todo) { if (applied.has(file)) continue; - const sql = fs.readFileSync(path.join(MIGRATIONS_DIR, file), 'utf8'); + const sql = fs.readFileSync(fullPath, 'utf8'); await client.query('BEGIN'); try { await client.query(sql); diff --git a/src/doors/CLAUDE.md b/src/doors/CLAUDE.md new file mode 100644 index 0000000..d525721 --- /dev/null +++ b/src/doors/CLAUDE.md @@ -0,0 +1,29 @@ +# Door framework + +A door is a self-contained game/program launched from the **D**oor Games menu. + +## Contract (`types.ts`) +```ts +interface DoorModule { + id: string; // stable; also the migration namespace ("/001_init.sql") + name: string; // menu name + description: string; // menu blurb, keep under ~45 chars + minSecurity?: number; // users.security_level needed to see it + migrationsDir?: string;// path.join(__dirname, 'migrations') + init?(): Promise;// once at server start, after migrations (start timers here) + run(s: Session): Promise; // one caller's visit; return to go back to the BBS +} +``` +- `doorMenu.ts` lists `registry.ts` entries and runs one. A non-`Disconnected` error thrown from + `run` is caught and logged, and the caller goes back to the menu instead of being hung up on. +- While a caller is in a door, `s.activity` is the door name (shown in Who's Online). + +## Adding a door +1. `src/doors//index.ts` exporting a `DoorModule`. +2. Optional `src/doors//migrations/NNN_name.sql`. Prefix tables with a short door tag (e.g. `sl_`). +3. Add one import line to `registry.ts`. +4. Add `src/doors//CLAUDE.md` describing the door's design and file map. +5. Keep game rules in pure modules with `*.test.ts` next to them; `npm test` picks them up. + +Imports allowed from a door: `../../session/*`, `../../ui/*`, `../../db`, `../../nodes`, +`../../users/userRepo`. Nothing else from core, and nothing from other doors. diff --git a/src/doors/doorMenu.ts b/src/doors/doorMenu.ts new file mode 100644 index 0000000..38e3e4e --- /dev/null +++ b/src/doors/doorMenu.ts @@ -0,0 +1,58 @@ +import type { Session } from '../session/Session'; +import { Disconnected } from '../session/Session'; +import { padRight } from '../session/ansi'; +import { makeBox } from '../ui/box'; +import { doors } from './registry'; +import type { DoorModule } from './types'; + +const box = makeBox(78, '|05', '|07'); + +function available(s: Session): DoorModule[] { + const level = s.user?.security_level ?? 0; + return doors.filter((d) => level >= (d.minSecurity ?? 0)); +} + +/** The "D" menu: lists registered doors and runs the one picked. */ +export async function doorMenu(s: Session): Promise { + for (;;) { + s.activity = 'Door Games'; + const list = available(s); + s.clear(); + await s.println(box.top); + await s.println(box.row(padRight(' |13D O O R G A M E S', 56) + '|08Pick a door, any door')); + await s.println(box.mid); + await s.println(box.row('')); + if (!list.length) await s.println(box.row(' |08No doors are installed yet.')); + for (let i = 0; i < list.length; i++) { + const d = list[i]; + await s.println(box.row(` |08[|15${i + 1}|08] ${padRight(`|14${d.name}`, 22)}|07${d.description}`)); + } + await s.println(box.row('')); + await s.println(box.row(' |08[|15Q|08] |11Return to Main Menu')); + await s.println(box.bot); + await s.print(' |07Door |08(|15Q|08=|07Quit|08)|07: '); + + const keys = list.map((_, i) => String(i + 1)).join('').slice(0, 9) + 'Q'; + const k = await s.readChoice(keys); + await s.println(); + if (k === 'Q') return; + await launch(s, list[Number(k) - 1]); + } +} + +/** Runs a door, isolating the BBS from door crashes. */ +async function launch(s: Session, door: DoorModule): Promise { + const prev = s.activity; + s.activity = door.name; + try { + await door.run(s); + } catch (err) { + if (err instanceof Disconnected) throw err; + console.error(`[door ${door.id}] node ${s.node} crashed`, err); + s.takeNotices(); + await s.println(`\r\n|12 *** ${door.name} has crashed. |07Returning you to the BBS.`); + await s.pause(); + } finally { + s.activity = prev; + } +} diff --git a/src/doors/registry.ts b/src/doors/registry.ts new file mode 100644 index 0000000..9924d78 --- /dev/null +++ b/src/doors/registry.ts @@ -0,0 +1,5 @@ +import type { DoorModule } from './types'; +import { starlane } from './starlane'; + +/** Every installed door. To add one: create src/doors//index.ts and list it here. */ +export const doors: DoorModule[] = [starlane]; diff --git a/src/doors/starlane/CLAUDE.md b/src/doors/starlane/CLAUDE.md new file mode 100644 index 0000000..a0f09e8 --- /dev/null +++ b/src/doors/starlane/CLAUDE.md @@ -0,0 +1,54 @@ +# STARLANE + +An original frontier space-trading door in the TW2002 genre (warp lanes, daily turns, port haggling, +fighters/mines, planets, corporations). The names, text and art are all original. Don't borrow names +or terms from existing games. + +## Setting +- **Terminus** (sector 1): the **Bazaar** (Shipyard, Hardware, Colonists, Tavern). There's no commodity port. +- **Concord Space** (1..`SL.concordMax`): safe. No attacks, deployments or seeds there; Reavers stay out. +- **The Drift**: everything else, split into named regions. +- Commodities, by index everywhere: 0 **Ore**, 1 **Biomass**, 2 **Circuitry**. +- NPCs: **Reavers** (clans, roam via the ticker, grow 3% per tick, prey on weaker ships and planets). +- **Syndicates**: corps of up to 6. They share planets and defenses, have a treasury, and the leader sets the memo. +- **Planets** come from a **Terraform Seed** (seed-capable hulls only). **Bastion** levels: 1 Vault, + 2 Shield Grid, 3 Lance Battery (burns 10 Ore per shot), 4 Transporter, 5 Deep Core. + +## Rules and formulas (where to tune) +- All balance knobs: `config.ts` (`SL`, `PRICES`, `LIMITS`); ships `data/ships.ts`; planets/bastions `data/planets.ts`; ranks `data/ranks.ts`. +- Turns: `turns_per_day` (in `sl_universe`) refills when `turns_date` != today (server TZ), on entry. + Warp costs `ship.turnsPerWarp`. Docking, attacking and deep scans cost 1. Transporter costs 3. +- Prices (`engine/pricing.ts`): a selling port charges `base*(1.15-0.45r)`, a buying port pays + `base*(1.0+0.5r)`, where `r = stock/cap`. Stock regenerates `portRegenPerHour * cap` per hour, lazily on read. +- Haggle (`engine/haggle.ts`): the port has a hidden limit of ±(3%+7%·r±1.5%). Offers past the limit get + countered halfway, up to 4 rounds. An offer worse than 0.8x/1.25x the limit is an insult and ends it. + XP is 1, 2 or 4 by deal quality. +- Combat (`engine/combat.ts`): volleys are 8-16% of fighters per round. Each hit burns 3 shield points + first, then 1 fighter. Destroyed ship means an escape pod to Terminus in a Skiff, a 20% loot share, + and `deaths_today++`. At `maxDeathsPerDay` your turns drop to 0. +- Planet production (`engine/planets.ts`): per 100 colonists per hour by type, fractional (stored as + double precision), lazily advanced on read. Bastion upgrades finish at `bastion_done_at`. +- Arrival (`screens/arrival.ts`): mines, then offensive fighters, then Lances, then a Reaver ambush, + then the toll/blockade choice. Autopilot stops on any hazard. +- Logging off while landed (planet menu **E**) hides the ship from Reavers and pilots. + +## Files +| Path | What | +|---|---| +| `index.ts` | DoorModule: `init` (load or generate the universe, start the ticker), `run` (title, sign-on, daily reset, news, loop) | +| `ticker.ts` | Every `SL.tickMinutes`: respawn, move, grow and attack with Reavers; prune news | +| `engine/` | Pure logic plus tests: rng, universe gen (kNN + rift lanes + SCC patch), pathfind, pricing, haggle, combat, planets | +| `data/` | Ships, ranks, planet types/bastion, name generators | +| `repo/` | SQL per entity (`players`, `world` (lane graph cache, ports, Big Bang), `planets`, `defenses`, `npcs`, `syndicates`, `news`) | +| `actions/` | Shared state changes: `destroyPilot` (pod, loot, news), `applyDamage` | +| `screens/` | UI: `main` (command loop), `sectorView`, `move`, `arrival`, `port`, `bazaar`, `computer`, `scan`, `deploy`, `combat`, `planet`, `syndicate`, `info`, `help`, `sysop` | +| `art/` | Title logo and scene art (pipe-coded strings) | +| `migrations/001_init.sql` | All `sl_` tables | + +## Patterns +- Read with `getX(pool, ...)` for display. Mutate inside `withTx` with `getX(c, ..., true)` (row lock), + re-validate, then `saveX`. Lock several pilots with `lockPilots` (id order). +- Tell other pilots things with `tell(uid, text, c)` (live if they're in the door, otherwise stored for the + "while you were away" log) or `tellIfOnline` (live only, e.g. arrivals). +- News: `addNews(text, c)`. Escape every handle and name with `esc()`. +- The sysop menu (**Z**) edits pilots, runs a tick, posts news, and does the **Big Bang** (wipe plus regenerate). diff --git a/src/doors/starlane/actions/damage.ts b/src/doors/starlane/actions/damage.ts new file mode 100644 index 0000000..6180f74 --- /dev/null +++ b/src/doors/starlane/actions/damage.ts @@ -0,0 +1,10 @@ +/** Applies raw damage to a ship: shields soak first, then fighters (1 each). Returns true if destroyed. */ +export function applyDamage(target: { fighters: number; shields: number }, dmg: number): { shieldLoss: number; fighterLoss: number; destroyed: boolean } { + const shieldLoss = Math.min(target.shields, dmg); + target.shields -= shieldLoss; + dmg -= shieldLoss; + const fighterLoss = Math.min(target.fighters, dmg); + target.fighters -= fighterLoss; + dmg -= fighterLoss; + return { shieldLoss, fighterLoss, destroyed: dmg > 0 }; +} diff --git a/src/doors/starlane/actions/fate.ts b/src/doors/starlane/actions/fate.ts new file mode 100644 index 0000000..bd458a5 --- /dev/null +++ b/src/doors/starlane/actions/fate.ts @@ -0,0 +1,54 @@ +import type { Q } from '../repo/q'; +import { savePilot, podPilot, type Pilot } from '../repo/players'; +import { addNews, tell } from '../repo/news'; +import { esc } from '../../../session/ansi'; +import { ship } from '../data/ships'; +import { alignmentShift } from '../engine/combat'; +import { SL } from '../config'; +import type { Reaver } from '../repo/npcs'; + +export type Killer = + | { kind: 'pilot'; pilot: Pilot } + | { kind: 'reaver'; reaver: Reaver } + | { kind: 'hazard'; what: string; ownerId: number | null }; + +export function killerName(k: Killer): string { + if (k.kind === 'pilot') return `|11${esc(k.pilot.handle)}`; + if (k.kind === 'reaver') return `|12the Reaver "${esc(k.reaver.name)}"`; + return `|07${k.what}`; +} + +/** + * Destroys a pilot's ship: loot to the killer, escape pod to Terminus, + * tracers removed, news posted. Saves the victim; the caller saves the killer + * pilot/reaver. Set `victimIsHere` when the victim is the acting caller (they + * see it on screen, so no notice is needed). + */ +export async function destroyPilot(c: Q, victim: Pilot, killer: Killer, victimIsHere: boolean): Promise { + const lost = ship(victim.ship_type).name; + const sector = victim.sector; + let loot = 0; + if (killer.kind === 'pilot') { + loot = Math.floor(victim.credits * SL.lootShare); + killer.pilot.credits += loot; + killer.pilot.xp += 25 + Math.floor(ship(victim.ship_type).price / 2000); + killer.pilot.kills++; + killer.pilot.alignment += alignmentShift(victim.alignment); + } else if (killer.kind === 'reaver') { + loot = Math.floor(victim.credits * SL.lootShare); + killer.reaver.credits += loot; + } + victim.credits -= loot; + podPilot(victim); + await savePilot(c, victim); + await c.query('DELETE FROM sl_tracers WHERE target_id = $1', [victim.user_id]); + await addNews(`|12${esc(victim.handle)}|07 lost a ${lost} in sector |15${sector}|07 to ${killerName(killer)}|07.`, c); + if (!victimIsHere) { + await tell( + victim.user_id, + `|12Your ${lost} was destroyed in sector ${sector} by ${killerName(killer)}|12!|07 You escaped in a pod to Terminus${loot ? `, minus ${loot} cr` : ''}.`, + c, + ); + } + return loot; +} diff --git a/src/doors/starlane/art/scenes.ts b/src/doors/starlane/art/scenes.ts new file mode 100644 index 0000000..9e4690e --- /dev/null +++ b/src/doors/starlane/art/scenes.ts @@ -0,0 +1,59 @@ +import { center } from '../../../session/ansi'; + +/** Small scene art, all within 80 columns. Pipe codes for colour. */ + +export const DOCKING = [ + '|08 .-------------------------.', + '|08 /|07 ▄▄▄ |15DOCKING CLAMPS |07 ▄▄▄ |08 \\', + '|08 | |07 ███|08━━━━━━━━━━━━━━━━|07███ |08 |', + '|08 \\|07 ▀▀▀ |10 ENGAGED |07 ▀▀▀|08 /', + "|08 '-------------------------'", +]; + +export const BAZAAR = [ + '|14 ╔╦╗ |06▄▀▄ |14╦═╗ ▄▀▄ ▄▀▄ |06╔═╗ |14╦═╗', + '|14 ║║║ |06█▀█ |14║═╣ █▀█ █▀█ |06╔═╝ |14║═╣', + '|06 ╩ ╩ |14▀ ▀ |06╩═╝ ▀ ▀ ▀ ▀ |14╚═╝ |06╩ ╩', + '|08 the great orbital bazaar of |15Terminus', +]; + +export const EXPLOSION = [ + '|08 . |14*|08 . .', + '|04 . |12\\|08 . |12| |08 . |12/|08 .', + '|14 * |12--==|14≡≡|15▓▓█|15 K-BOOM |15█▓▓|14≡≡|12==-- |14*', + '|04 . |12/|08 . |12| |08 . |12\\|08 .', + '|08 . |14*|08 . .', +]; + +export const ESCAPE_POD = [ + '|07 _', + '|07 (|11o|07) |08~ ~ ~ |07your escape pod tumbles toward Terminus', + "|07 `", +]; + +const PLANET_ART = [ + // rocky / ore + ['|06 .-""""-.', '|06 .´|04 ▒░ ▒ |06`.', '|06 /|04 ▒▒ ░▒▒ |06\\', '|06 \\|04 ░▒▒ ▒ |06/', "|06 `.|04 ▒ ░▒ |06.´", "|06 `-....-´"], + // lush / water + ['|02 .-""""-.', '|02 .´|10 ░▒|09≈≈|10▒░ |02`.', '|02 /|09 ≈≈|10▒▒░|09≈≈≈ |02\\', '|02 \\|10 ░▒|09≈≈≈|10▒▒ |02/', "|02 `.|09 ≈≈|10░▒ |02.´", "|02 `-....-´"], + // ice / crystal + ['|11 .-""""-.', '|11 .´|15 ░ ◊ |07░░ |11`.', '|11 /|07 ░░|15◊|07░░ ░░ |11\\', '|11 \\|15 ◊ |07░░░ |15◊ |11/', "|11 `.|07 ░ |15◊|07░ |11.´", "|11 `-....-´"], +]; + +export function planetArt(kind: number): string[] { + return PLANET_ART[kind % PLANET_ART.length]; +} + +export const REAVER = [ + "|04 __/\\__", + "|04 >=|12[|15x_x|12]|04=< |12REAVERS!", + "|04 `´\\/`´", +]; + +export const BIG_BANG = [ + center('|08. . |15* |08. .'), + center('|07. |14\\ |15| |14/ |07.'), + center('|15-- |14( |15BANG |14) |15--'), + center('|07. |14/ |15| |14\\ |07.'), + center('|08. . |15* |08. .'), +]; diff --git a/src/doors/starlane/art/title.ts b/src/doors/starlane/art/title.ts new file mode 100644 index 0000000..9dd9756 --- /dev/null +++ b/src/doors/starlane/art/title.ts @@ -0,0 +1,58 @@ +import { center } from '../../../session/ansi'; +import { mulberry32 } from '../engine/rng'; + +/** 5-row block font, just the letters we need. */ +const FONT: Record = { + S: [' ████ ', '██ ', ' ████ ', ' ██', '█████ '], + T: ['██████', ' ██ ', ' ██ ', ' ██ ', ' ██ '], + A: [' ████ ', '██ ██', '██████', '██ ██', '██ ██'], + R: ['█████ ', '██ ██', '█████ ', '██ ██ ', '██ ██'], + L: ['██ ', '██ ', '██ ', '██ ', '██████'], + N: ['██ ██', '███ ██', '██████', '██ ███', '██ ██'], + E: ['██████', '██ ', '████ ', '██ ', '██████'], +}; + +const ROW_COLORS = ['|15', '|11', '|11', '|03', '|09']; + +function logo(word: string): string[] { + const rows: string[] = []; + for (let r = 0; r < 5; r++) { + const line = [...word].map((ch) => FONT[ch][r]).join(' '); + rows.push(ROW_COLORS[r] + line); + } + return rows; +} + +/** Deterministic starfield line of the given width. */ +function stars(seed: number, width = 78): string { + const rng = mulberry32(seed); + let out = ''; + for (let i = 0; i < width; i++) { + const r = rng(); + out += r < 0.03 ? '|15*' : r < 0.08 ? '|08.' : r < 0.1 ? '|07·' : ' '; + } + return out; +} + +const SHIP = [ + '|08 _____', + '|08 __.---|07" "|08---.__', + '|12 ≡≡≡|04>|07[|15▓▓|07]|08=====|07[|11 ◊ |07]|08=====|07[|15▓▓|07]|08>', + '|08 `--.___ ___.--´', + '|08 `"""´', +]; + +export function titleScreen(version: string): string[] { + return [ + stars(11), + stars(12), + ...logo('STARLANE').map((l) => center(l)), + stars(13), + center('|08─────────────── |07a frontier trading door for |13WarezHou$e |08───────────────'), + stars(14), + ...SHIP.map((l) => center(l)), + stars(15), + center('|07Haul cargo. Haggle hard. Fortify a world. |12Watch for Reavers.'), + center(`|08${version}`), + ]; +} diff --git a/src/doors/starlane/config.ts b/src/doors/starlane/config.ts new file mode 100644 index 0000000..5f00dac --- /dev/null +++ b/src/doors/starlane/config.ts @@ -0,0 +1,63 @@ +/** Balance knobs for STARLANE. Universe size / turns can be overridden by env or a Big Bang. */ +const num = (v: string | undefined, d: number) => { + const n = Number(v); + return v !== undefined && v !== '' && Number.isFinite(n) ? n : d; +}; + +export const SL = { + title: 'STARLANE', + defaultSectors: num(process.env.SL_SECTORS, 1000), + defaultTurnsPerDay: num(process.env.SL_TURNS, 250), + + /** Sectors 1..concordMax are Concord Space (no combat, no deployments). */ + concordMax: 10, + terminus: 1, + + startCredits: 2000, + startFighters: 20, + startShields: 50, + + /** Fraction of Drift sectors with a commodity port. */ + portDensity: 0.45, + oneWayChance: 0.08, + /** Port stock regenerates this fraction of capacity per hour. */ + portRegenPerHour: 0.04, + + maxDeathsPerDay: 2, + /** Share of a victim's on-hand credits an attacker loots. */ + lootShare: 0.2, + + tickMinutes: num(process.env.SL_TICK_MIN, 10), + reaverCount: 12, + maxPlanetsPerSector: 3, + maxSyndicateMembers: 6, + + /** Alignment at or below this counts as "wanted": Bazaar tariff applies. */ + wantedAlignment: -100, + bazaarTariff: 0.25, + + newsDays: 7, + messageDays: 14, +}; + +/** Bazaar hardware prices (credits). */ +export const PRICES = { + fighter: 60, + shield: 20, + mine: 250, + tracer: 400, + probe: 700, + massScanner: 9000, + deepScanner: 35000, + seed: 25000, + colonist: 25, + /** Extra holds cost base * (1 + holdsAlreadyBought / 10). */ + holdBase: 400, +}; + +export const LIMITS = { + mines: 100, + tracers: 10, + probes: 10, + seeds: 1, +}; diff --git a/src/doors/starlane/data/names.ts b/src/doors/starlane/data/names.ts new file mode 100644 index 0000000..9258f97 --- /dev/null +++ b/src/doors/starlane/data/names.ts @@ -0,0 +1,40 @@ +import { pick, type Rng } from '../engine/rng'; + +export const REGIONS = [ + 'The Ashen Reach', 'Cinder Expanse', 'Hollow Verge', 'Saltglass Nebula', 'Mourning Shoals', 'Iron Tide', + 'The Long Dark', 'Bramble Cluster', "Widow's Veil", 'The Rustbelt', 'Vesper Gulf', 'Glasswater', + 'Thornfield', 'The Shattered March', 'Lantern Deep', 'Cobalt Wastes', 'Pale Hollow', 'Ember Run', + 'Gallows Reach', 'The Quiet Sea', 'Halcyon Rift', 'The Splinters', 'Ghostlight Basin', 'Sable Verge', + 'Tinker\'s Folly', 'The Boneyard', 'Driftwood Shallows', 'Copperhead Run', 'Starveling Gap', 'The Furnace', +]; + +const PORT_A = [ + 'Kell', 'Dray', 'Orrin', 'Vask', 'Mire', 'Tobin', 'Hale', 'Rook', 'Sable', 'Corvan', 'Brisk', 'Lark', 'Ostra', + 'Nym', 'Quill', 'Tarrow', 'Fenn', 'Grist', 'Holloway', 'Jessup', 'Marrow', 'Pike', 'Ruse', 'Sorrel', 'Thane', + 'Umber', 'Vane', 'Wick', 'Yarrow', 'Zell', 'Cask', 'Dunmore', 'Esker', 'Flint', 'Garrow', 'Haskin', 'Ivo', +]; +const PORT_B = [ + 'Landing', 'Yard', 'Exchange', 'Depot', 'Station', 'Outpost', 'Hold', 'Market', 'Works', 'Haven', 'Post', + 'Freeport', 'Junction', 'Dock', 'Spire', 'Wharf', 'Crossing', 'Rest', 'Bourse', 'Roost', +]; + +export function portName(rng: Rng): string { + const a = pick(rng, PORT_A); + return rng() < 0.3 ? `${a}'s ${pick(rng, PORT_B)}` : `${a} ${pick(rng, PORT_B)}`; +} + +export const REAVER_CLANS = ['Vosk', 'Black Tithe', 'Gutterknife', 'Red Lantern', 'Harrow', 'Ninefingers', 'Hollow Crown']; +const REAVER_A = ['Grim', 'Bleeding', 'Rust', 'Hungry', 'Last', 'Broken', 'Pale', 'Howling', 'Crooked', 'Burnt', 'Silent', 'Wretched']; +const REAVER_B = ['Kestrel', 'Saint', 'Widow', 'Jackal', 'Mercy', 'Lantern', 'Hound', 'Psalm', 'Tooth', 'Orphan', 'Gallows', 'Vulture']; + +export function reaverName(rng: Rng): string { + return `${pick(rng, REAVER_A)} ${pick(rng, REAVER_B)}`; +} + +const PLANET_A = ['New', 'Far', 'Old', 'Little', 'High', 'Lost', '']; +const PLANET_B = ['Hope', 'Harbor', 'Ashfall', 'Prosper', 'Greystone', 'Emberly', 'Tallow', 'Solace', 'Brightwater', 'Kessin', 'Dunwich', 'Morrow']; + +export function planetName(rng: Rng): string { + const a = pick(rng, PLANET_A); + return a ? `${a} ${pick(rng, PLANET_B)}` : pick(rng, PLANET_B); +} diff --git a/src/doors/starlane/data/planets.ts b/src/doors/starlane/data/planets.ts new file mode 100644 index 0000000..0f9de56 --- /dev/null +++ b/src/doors/starlane/data/planets.ts @@ -0,0 +1,45 @@ +/** Planet types. Production is per 100 colonists per hour; fighters likewise. */ +export interface PlanetType { + id: number; + name: string; + prod: [number, number, number]; + fighters: number; + maxColonists: number; + art: number; +} + +export const PLANET_TYPES: PlanetType[] = [ + { id: 1, name: 'Ferric', prod: [12, 2, 3], fighters: 2, maxColonists: 3000, art: 0 }, + { id: 2, name: 'Verdant', prod: [3, 12, 2], fighters: 1, maxColonists: 5000, art: 1 }, + { id: 3, name: 'Silicate', prod: [4, 2, 8], fighters: 2, maxColonists: 2500, art: 2 }, + { id: 4, name: 'Oceanic', prod: [5, 9, 3], fighters: 1, maxColonists: 6000, art: 1 }, + { id: 5, name: 'Volcanic', prod: [16, 0, 4], fighters: 4, maxColonists: 1500, art: 0 }, + { id: 6, name: 'Glacial', prod: [6, 3, 6], fighters: 3, maxColonists: 2000, art: 2 }, +]; + +export function planetType(id: number): PlanetType { + return PLANET_TYPES.find((p) => p.id === id) ?? PLANET_TYPES[0]; +} + +/** Bastion fortress levels. Upgrading to `level` costs this and takes `hours`. */ +export interface BastionLevel { + level: number; + name: string; + credits: number; + cost: [number, number, number]; + hours: number; + perk: string; +} + +export const BASTION: BastionLevel[] = [ + { level: 1, name: 'Vault', credits: 15000, cost: [500, 300, 100], hours: 4, perk: 'Credit vault: Reavers cannot plunder stored credits.' }, + { level: 2, name: 'Shield Grid', credits: 40000, cost: [1000, 500, 600], hours: 8, perk: 'Planetary shields (1,000 per level above 1) recharge over time.' }, + { level: 3, name: 'Lance Battery', credits: 90000, cost: [2000, 800, 1500], hours: 12, perk: 'Fires on hostile ships entering the sector. Burns 10 Ore a shot.' }, + { level: 4, name: 'Transporter', credits: 160000, cost: [3000, 1500, 3000], hours: 18, perk: 'Beam between your planets anywhere in the Drift for 3 turns.' }, + { level: 5, name: 'Deep Core', credits: 300000, cost: [5000, 3000, 5000], hours: 24, perk: 'Production +50%, Lance damage doubled.' }, +]; + +/** Storage cap for each commodity on a planet. */ +export const planetStorage = (bastion: number) => 10000 + bastion * 10000; +export const planetShieldCap = (bastion: number) => (bastion >= 2 ? (bastion - 1) * 1000 : 0); +export const lanceDamage = (bastion: number) => (bastion >= 3 ? (bastion >= 5 ? 2 : 1) * 60 * bastion : 0); diff --git a/src/doors/starlane/data/ranks.ts b/src/doors/starlane/data/ranks.ts new file mode 100644 index 0000000..000a78e --- /dev/null +++ b/src/doors/starlane/data/ranks.ts @@ -0,0 +1,27 @@ +/** Rank titles by experience. Pilots with negative alignment walk the outlaw track. */ +const THRESHOLDS = [0, 50, 200, 500, 1000, 2500, 5000, 10000, 25000, 50000]; +const LAWFUL = ['Drifter', 'Deckhand', 'Spacer', 'Trader', 'Merchant', 'Captain', 'Commodore', 'Magnate', 'Baron of the Drift', 'Star Sovereign']; +const OUTLAW = ['Scav', 'Cutpurse', 'Smuggler', 'Brigand', 'Corsair', 'Marauder', 'Warlord', 'Dread Corsair', 'Reaver King', 'Void Tyrant']; + +export function rankIndex(xp: number): number { + let i = 0; + while (i + 1 < THRESHOLDS.length && xp >= THRESHOLDS[i + 1]) i++; + return i; +} + +export function rankTitle(xp: number, alignment: number): string { + return (alignment < 0 ? OUTLAW : LAWFUL)[rankIndex(xp)]; +} + +export function nextRankXp(xp: number): number | null { + const i = rankIndex(xp); + return i + 1 < THRESHOLDS.length ? THRESHOLDS[i + 1] : null; +} + +export function alignmentLabel(a: number): string { + if (a >= 500) return '|11Paragon'; + if (a >= 100) return '|10Upstanding'; + if (a > -100) return '|07Neutral'; + if (a > -500) return '|12Wanted'; + return '|04Infamous'; +} diff --git a/src/doors/starlane/data/ships.ts b/src/doors/starlane/data/ships.ts new file mode 100644 index 0000000..aabb307 --- /dev/null +++ b/src/doors/starlane/data/ships.ts @@ -0,0 +1,34 @@ +/** Ship classes. id is stored in sl_players.ship_type. */ +export interface ShipClass { + id: number; + name: string; + price: number; + holds: number; + maxHolds: number; + maxFighters: number; + maxShields: number; + turnsPerWarp: number; + /** Can carry a Terraform Seed. */ + seeds: boolean; + blurb: string; +} + +export const SHIPS: ShipClass[] = [ + { id: 1, name: 'Skiff', price: 5000, holds: 20, maxHolds: 40, maxFighters: 60, maxShields: 100, turnsPerWarp: 2, seeds: false, blurb: 'Patched hull, one good engine. Everyone starts somewhere.' }, + { id: 2, name: 'Courier', price: 18000, holds: 30, maxHolds: 50, maxFighters: 200, maxShields: 200, turnsPerWarp: 1, seeds: false, blurb: 'Fast scout. Burns half the turns per jump.' }, + { id: 3, name: 'Mule Hauler', price: 35000, holds: 75, maxHolds: 125, maxFighters: 150, maxShields: 250, turnsPerWarp: 3, seeds: false, blurb: 'Slow, ugly, and full of cargo space.' }, + { id: 4, name: 'Corvette', price: 60000, holds: 40, maxHolds: 80, maxFighters: 800, maxShields: 600, turnsPerWarp: 2, seeds: false, blurb: 'A real warship for a pilot on a budget.' }, + { id: 5, name: 'Bulk Freighter', price: 110000, holds: 120, maxHolds: 200, maxFighters: 400, maxShields: 500, turnsPerWarp: 3, seeds: true, blurb: 'Hauls colonists and seeds to the far Drift.' }, + { id: 6, name: 'Frontier Clipper', price: 175000, holds: 80, maxHolds: 150, maxFighters: 1200, maxShields: 1000, turnsPerWarp: 2, seeds: true, blurb: 'The settler\'s workhorse. Trades, fights, builds.' }, + { id: 7, name: 'Gunship', price: 260000, holds: 50, maxHolds: 90, maxFighters: 4000, maxShields: 2500, turnsPerWarp: 2, seeds: false, blurb: 'Nothing but guns and bad intentions.' }, + { id: 8, name: 'Dreadnought', price: 650000, holds: 150, maxHolds: 250, maxFighters: 10000, maxShields: 5000, turnsPerWarp: 3, seeds: true, blurb: 'A moving fortress. The Drift notices you.' }, +]; + +export function ship(id: number): ShipClass { + return SHIPS.find((s) => s.id === id) ?? SHIPS[0]; +} + +/** Credits the Bazaar gives for your current hull. */ +export function tradeInValue(id: number): number { + return Math.floor(ship(id).price * 0.5); +} diff --git a/src/doors/starlane/engine/combat.test.ts b/src/doors/starlane/engine/combat.test.ts new file mode 100644 index 0000000..f83d5bf --- /dev/null +++ b/src/doors/starlane/engine/combat.test.ts @@ -0,0 +1,35 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { battle, mineStrike } from './combat'; +import { mulberry32 } from './rng'; + +test('battle invariants', () => { + const rng = mulberry32(9); + for (let i = 0; i < 2000; i++) { + const att = { fighters: Math.floor(rng() * 2000), shields: 0 }; + const def = { fighters: Math.floor(rng() * 2000), shields: Math.floor(rng() * 1000) }; + const r = battle(att, def, rng); + assert.ok(r.attacker.fighters >= 0 && r.defender.fighters >= 0 && r.defender.shields >= 0); + assert.equal(r.attacker.fighters + r.attackerLost, att.fighters); + assert.equal(r.defender.fighters + r.defenderFightersLost, def.fighters); + assert.equal(r.defender.shields + r.defenderShieldsLost, def.shields); + assert.equal(r.defenderBroken, r.defender.fighters === 0 && r.defender.shields === 0); + assert.ok(r.attackerBroken || r.defenderBroken || r.rounds === 60); + } +}); + +test('overwhelming force wins', () => { + const rng = mulberry32(5); + let wins = 0; + for (let i = 0; i < 100; i++) if (battle({ fighters: 1000, shields: 0 }, { fighters: 100, shields: 50 }, rng).defenderBroken) wins++; + assert.ok(wins >= 95, `only ${wins} wins`); +}); + +test('mines', () => { + const rng = mulberry32(6); + assert.equal(mineStrike(0, { fighters: 10, shields: 10 }, rng).detonated, 0); + const m = mineStrike(50, { fighters: 0, shields: 0 }, rng); + assert.ok(m.detonated > 0 && m.destroyed); + const safe = mineStrike(5, { fighters: 1000, shields: 1000 }, rng); + assert.ok(!safe.destroyed && safe.shieldLoss > 0 && safe.fighterLoss === 0); +}); diff --git a/src/doors/starlane/engine/combat.ts b/src/doors/starlane/engine/combat.ts new file mode 100644 index 0000000..7d952d3 --- /dev/null +++ b/src/doors/starlane/engine/combat.ts @@ -0,0 +1,90 @@ +import { randRange, type Rng } from './rng'; + +/** Shield points burned by one fighter hit. Shields are cheap, so they're soft. */ +export const SHIELD_PER_HIT = 3; + +export interface Side { + fighters: number; + shields: number; +} + +export interface BattleResult { + attacker: Side; + defender: Side; + rounds: number; + attackerLost: number; + defenderFightersLost: number; + defenderShieldsLost: number; + /** Defender has no fighters and no shields left. */ + defenderBroken: boolean; + /** Attacker has no fighters left. */ + attackerBroken: boolean; +} + +/** + * Fighter exchange. Each round both sides fire volleys proportional to + * their fighters; shields soak hits before fighters die. Attacker shields + * only protect the attacker's ship, not its committed fighters, so attacker + * losses come straight off fighters. + * + * `attBonus`/`defBonus` scale volley strength (e.g. planet defences, lances). + */ +export function battle(att: Side, def: Side, rng: Rng, attBonus = 1, defBonus = 1, maxRounds = 60): BattleResult { + const a = { ...att }; + const d = { ...def }; + let rounds = 0; + const startA = a.fighters; + const startDF = d.fighters; + const startDS = d.shields; + + while (rounds < maxRounds && a.fighters > 0 && (d.fighters > 0 || d.shields > 0)) { + rounds++; + let aHits = Math.max(1, Math.round(a.fighters * randRange(rng, 0.08, 0.16) * attBonus)); + const dHits = d.fighters > 0 ? Math.max(1, Math.round(d.fighters * randRange(rng, 0.08, 0.16) * defBonus)) : 0; + + // Attacker hits: shields first (each hit burns SHIELD_PER_HIT points), then fighters. + const toShields = Math.min(Math.ceil(d.shields / SHIELD_PER_HIT), aHits); + d.shields = Math.max(0, d.shields - toShields * SHIELD_PER_HIT); + aHits -= toShields; + d.fighters = Math.max(0, d.fighters - aHits); + + a.fighters = Math.max(0, a.fighters - dHits); + } + + return { + attacker: a, + defender: d, + rounds, + attackerLost: startA - a.fighters, + defenderFightersLost: startDF - d.fighters, + defenderShieldsLost: startDS - d.shields, + defenderBroken: d.fighters <= 0 && d.shields <= 0, + attackerBroken: a.fighters <= 0, + }; +} + +/** + * Mines going off as a ship enters. Returns how many detonated and the + * damage taken (shields first, then fighters). `destroyed` if the hull is bare. + */ +export function mineStrike(mines: number, ship: Side, rng: Rng) { + const hits = mines > 0 ? Math.max(1, Math.round(mines * randRange(rng, 0.2, 0.4))) : 0; + let dmg = hits * 25; + const shieldLoss = Math.min(ship.shields, dmg); + dmg -= shieldLoss; + const fighterLoss = Math.min(ship.fighters, Math.ceil(dmg / 2)); + dmg -= fighterLoss * 2; + return { + detonated: hits, + shieldLoss, + fighterLoss, + destroyed: hits > 0 && dmg > 0, + }; +} + +/** Alignment change for destroying a target with the given alignment. */ +export function alignmentShift(targetAlignment: number): number { + if (targetAlignment <= -100) return 25; // bringing in an outlaw + if (targetAlignment >= 100) return -50; // gunning down a decent pilot + return -15; +} diff --git a/src/doors/starlane/engine/commodities.ts b/src/doors/starlane/engine/commodities.ts new file mode 100644 index 0000000..8a51e5d --- /dev/null +++ b/src/doors/starlane/engine/commodities.ts @@ -0,0 +1,28 @@ +/** The three trade goods. Index order is used everywhere (stock[], cargo[]). */ +export const COMMODITIES = [ + { key: 'ore', name: 'Ore', base: 20, color: '|07' }, + { key: 'bio', name: 'Biomass', base: 34, color: '|10' }, + { key: 'circ', name: 'Circuitry', base: 55, color: '|11' }, +] as const; + +export const NUM_COMMODITIES = COMMODITIES.length; + +/** A port's trade pattern: one char per commodity, 'B' = port buys, 'S' = port sells. */ +export type Pattern = string; + +export const PATTERNS: Pattern[] = ['BBS', 'BSB', 'SBB', 'SSB', 'SBS', 'BSS', 'SSS', 'BBB']; +/** Relative odds of each pattern when generating ports. */ +export const PATTERN_WEIGHTS = [16, 16, 16, 16, 16, 16, 2, 2]; + +export function portBuys(pattern: Pattern, c: number): boolean { + return pattern[c] === 'B'; +} + +export function describePattern(pattern: Pattern): string { + return COMMODITIES.map((c, i) => (portBuys(pattern, i) ? `|12buys |07${c.name}` : `|10sells |07${c.name}`)).join(' |08· '); +} + +/** Compact "B S S" style tag with colors. */ +export function patternTag(pattern: Pattern): string { + return [...pattern].map((ch) => (ch === 'B' ? '|12B' : '|10S')).join(''); +} diff --git a/src/doors/starlane/engine/haggle.test.ts b/src/doors/starlane/engine/haggle.test.ts new file mode 100644 index 0000000..0258f1d --- /dev/null +++ b/src/doors/starlane/engine/haggle.test.ts @@ -0,0 +1,43 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { startHaggle, makeOffer, haggleXp } from './haggle'; +import { mulberry32 } from './rng'; + +test('accepted prices never beat the port limit', () => { + const rng = mulberry32(1); + for (let i = 0; i < 2000; i++) { + const side = rng() < 0.5 ? 'buy' : 'sell'; + const quote = 100 + Math.floor(rng() * 10000); + const h = startHaggle(side, quote, rng(), rng); + if (side === 'buy') assert.ok(h.limit < quote && h.limit >= quote * 0.85); + else assert.ok(h.limit > quote && h.limit <= quote * 1.15); + for (let r = 0; r < 10; r++) { + const offer = Math.round(quote * (0.7 + rng() * 0.6)); + const res = makeOffer(h, offer); + if (res.kind === 'accept') { + if (side === 'buy') assert.ok(res.price >= h.limit); + else assert.ok(res.price <= h.limit); + assert.ok(res.quality >= 0 && res.quality <= 1); + break; + } + if (res.kind === 'refuse') break; + if (side === 'buy') assert.ok(res.quote >= h.limit && res.quote <= quote); + else assert.ok(res.quote <= h.limit && res.quote >= quote); + } + } +}); + +test('taking the quote is always accepted with zero quality', () => { + const h = startHaggle('buy', 1000, 0.5, mulberry32(2)); + const r = makeOffer(h, 1000); + assert.deepEqual(r, { kind: 'accept', price: 1000, quality: 0 }); +}); + +test('insulting offers end the haggle; patience runs out', () => { + const h = startHaggle('buy', 1000, 0.5, mulberry32(3)); + assert.equal(makeOffer(h, 500).kind, 'refuse'); + const h2 = startHaggle('sell', 1000, 0.5, mulberry32(4)); + const kinds = [1, 2, 3, 4].map(() => makeOffer(h2, h2.limit + 1).kind); + assert.equal(kinds[kinds.length - 1], 'refuse'); + assert.ok(haggleXp(1) > haggleXp(0.6) && haggleXp(0.6) > haggleXp(0)); +}); diff --git a/src/doors/starlane/engine/haggle.ts b/src/doors/starlane/engine/haggle.ts new file mode 100644 index 0000000..46ee2a8 --- /dev/null +++ b/src/doors/starlane/engine/haggle.ts @@ -0,0 +1,64 @@ +import type { Rng } from './rng'; + +/** + * Haggling. The port quotes a total; the player counters. The port has a + * hidden limit (lowest it will sell for / highest it will pay). Offers past + * the limit get a counter until patience runs out; insulting offers end it. + * + * side 'buy' = player buys from port (lower offer is better for player) + * side 'sell' = player sells to port (higher ask is better for player) + */ +export type Side = 'buy' | 'sell'; + +export interface Haggle { + side: Side; + originalQuote: number; + quote: number; + limit: number; + round: number; + maxRounds: number; +} + +export type OfferResult = + | { kind: 'accept'; price: number; quality: number } + | { kind: 'counter'; quote: number } + | { kind: 'refuse' }; + +/** `stockRatio` in 0..1: a well-stocked seller / hungry buyer is more flexible. */ +export function startHaggle(side: Side, quote: number, stockRatio: number, rng: Rng): Haggle { + const tol = Math.max(0.01, 0.03 + 0.07 * stockRatio + (rng() - 0.5) * 0.03); + const limit = side === 'buy' ? Math.floor(quote * (1 - tol)) : Math.ceil(quote * (1 + tol)); + return { side, originalQuote: quote, quote, limit, round: 0, maxRounds: 4 }; +} + +/** How good a deal is, 0 (paid the quote) .. 1 (hit the port's limit exactly). */ +function qualityOf(h: Haggle, price: number): number { + const span = Math.abs(h.originalQuote - h.limit); + if (span === 0) return 0; + return Math.max(0, Math.min(1, Math.abs(h.originalQuote - price) / span)); +} + +export function makeOffer(h: Haggle, offer: number): OfferResult { + const better = h.side === 'buy' ? (a: number, b: number) => a < b : (a: number, b: number) => a > b; + + // Offer no better for the player than the current quote: done at the offer. + if (!better(offer, h.quote)) return { kind: 'accept', price: offer, quality: qualityOf(h, offer) }; + // Within the port's limit: deal. + if (!better(offer, h.limit)) return { kind: 'accept', price: offer, quality: qualityOf(h, offer) }; + + h.round++; + const insulting = h.side === 'buy' ? offer < h.limit * 0.8 : offer > h.limit * 1.25; + if (insulting || h.round >= h.maxRounds) return { kind: 'refuse' }; + + // Counter: move halfway from the current quote toward the limit. + const next = h.limit + (h.quote - h.limit) * 0.5; + h.quote = h.side === 'buy' ? Math.ceil(next) : Math.floor(next); + return { kind: 'counter', quote: h.quote }; +} + +/** Experience earned for a completed trade. */ +export function haggleXp(quality: number): number { + if (quality >= 0.9) return 4; + if (quality >= 0.5) return 2; + return 1; +} diff --git a/src/doors/starlane/engine/pathfind.test.ts b/src/doors/starlane/engine/pathfind.test.ts new file mode 100644 index 0000000..836d92b --- /dev/null +++ b/src/doors/starlane/engine/pathfind.test.ts @@ -0,0 +1,31 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { shortestPath, distances, stronglyConnected, type LaneGraph } from './pathfind'; + +const g: LaneGraph = new Map([ + [1, [2, 3]], + [2, [4]], + [3, [4, 5]], + [4, [1]], + [5, []], +]); + +test('shortest path respects one-way lanes', () => { + assert.deepEqual(shortestPath(g, 1, 4)!.length, 3); + assert.deepEqual(shortestPath(g, 4, 5), [4, 1, 3, 5]); + assert.equal(shortestPath(g, 5, 1), null); + assert.deepEqual(shortestPath(g, 2, 2), [2]); +}); + +test('avoid list routes around sectors', () => { + assert.deepEqual(shortestPath(g, 1, 4, new Set([2])), [1, 3, 4]); + assert.equal(shortestPath(g, 1, 5, new Set([3])), null); +}); + +test('distances and SCCs', () => { + const d = distances(g, 1); + assert.equal(d.get(5), 2); + assert.equal(d.get(4), 2); + const comps = stronglyConnected(g).map((c) => c.sort()).sort((a, b) => a.length - b.length); + assert.deepEqual(comps, [[5], [1, 2, 3, 4]]); +}); diff --git a/src/doors/starlane/engine/pathfind.ts b/src/doors/starlane/engine/pathfind.ts new file mode 100644 index 0000000..624b3df --- /dev/null +++ b/src/doors/starlane/engine/pathfind.ts @@ -0,0 +1,97 @@ +/** Lane graph: sector id -> outbound lanes. */ +export type LaneGraph = Map; + +/** Shortest path (inclusive of both ends) by lane count, or null if unreachable. */ +export function shortestPath(g: LaneGraph, from: number, to: number, avoid: Set = new Set()): number[] | null { + if (from === to) return [from]; + const prev = new Map([[from, from]]); + const queue = [from]; + for (let qi = 0; qi < queue.length; qi++) { + const cur = queue[qi]; + for (const nxt of g.get(cur) ?? []) { + if (prev.has(nxt) || (avoid.has(nxt) && nxt !== to)) continue; + prev.set(nxt, cur); + if (nxt === to) { + const path = [to]; + let p = cur; + while (p !== from) { + path.push(p); + p = prev.get(p)!; + } + path.push(from); + return path.reverse(); + } + queue.push(nxt); + } + } + return null; +} + +/** Lane distances from `from` to every reachable sector. */ +export function distances(g: LaneGraph, from: number): Map { + const dist = new Map([[from, 0]]); + const queue = [from]; + for (let qi = 0; qi < queue.length; qi++) { + const cur = queue[qi]; + for (const nxt of g.get(cur) ?? []) { + if (dist.has(nxt)) continue; + dist.set(nxt, dist.get(cur)! + 1); + queue.push(nxt); + } + } + return dist; +} + +/** Strongly connected components (iterative Tarjan). */ +export function stronglyConnected(g: LaneGraph): number[][] { + let index = 0; + const idx = new Map(); + const low = new Map(); + const onStack = new Set(); + const stack: number[] = []; + const out: number[][] = []; + + for (const root of g.keys()) { + if (idx.has(root)) continue; + const work: { v: number; i: number }[] = [{ v: root, i: 0 }]; + idx.set(root, index); + low.set(root, index); + index++; + stack.push(root); + onStack.add(root); + while (work.length) { + const frame = work[work.length - 1]; + const edges = g.get(frame.v) ?? []; + if (frame.i < edges.length) { + const w = edges[frame.i++]; + if (!idx.has(w)) { + idx.set(w, index); + low.set(w, index); + index++; + stack.push(w); + onStack.add(w); + work.push({ v: w, i: 0 }); + } else if (onStack.has(w)) { + low.set(frame.v, Math.min(low.get(frame.v)!, idx.get(w)!)); + } + } else { + work.pop(); + if (work.length) { + const parent = work[work.length - 1].v; + low.set(parent, Math.min(low.get(parent)!, low.get(frame.v)!)); + } + if (low.get(frame.v) === idx.get(frame.v)) { + const comp: number[] = []; + let w: number; + do { + w = stack.pop()!; + onStack.delete(w); + comp.push(w); + } while (w !== frame.v); + out.push(comp); + } + } + } + } + return out; +} diff --git a/src/doors/starlane/engine/planets.test.ts b/src/doors/starlane/engine/planets.test.ts new file mode 100644 index 0000000..c276a46 --- /dev/null +++ b/src/doors/starlane/engine/planets.test.ts @@ -0,0 +1,36 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { advancePlanet, type PlanetState } from './planets'; +import { planetStorage } from '../data/planets'; + +const base = (): PlanetState => ({ + type: 1, colonists: 1000, stock: [0, 0, 0], fighters: 0, shields: 0, + bastion: 0, bastionTarget: 0, bastionDoneAt: null, lastUpdate: new Date(0), +}); + +test('production accrues per hour and caps at storage', () => { + const p = advancePlanet(base(), new Date(3_600_000)); + // Ferric: 12 ore per 100 colonists per hour. + assert.ok(Math.abs(p.stock[0] - 120) < 1e-6); + assert.ok(p.fighters > 0 && p.colonists > 1000); + const q = advancePlanet(base(), new Date(1000 * 3_600_000)); + assert.equal(q.stock[0], planetStorage(0)); + assert.ok(q.colonists <= 3000); +}); + +test('frequent visits do not round production away', () => { + const p = base(); + for (let m = 1; m <= 60; m++) advancePlanet(p, new Date(m * 60_000)); + assert.ok(p.stock[0] > 119 && p.stock[0] < 125, `got ${p.stock[0]}`); +}); + +test('bastion upgrade completes when due', () => { + const p = base(); + p.bastionTarget = 1; + p.bastionDoneAt = new Date(1000); + advancePlanet(p, new Date(500)); + assert.equal(p.bastion, 0); + advancePlanet(p, new Date(2000)); + assert.equal(p.bastion, 1); + assert.equal(p.bastionDoneAt, null); +}); diff --git a/src/doors/starlane/engine/planets.ts b/src/doors/starlane/engine/planets.ts new file mode 100644 index 0000000..0392c06 --- /dev/null +++ b/src/doors/starlane/engine/planets.ts @@ -0,0 +1,51 @@ +import { planetType, planetStorage, planetShieldCap, BASTION } from '../data/planets'; + +export interface PlanetState { + type: number; + colonists: number; + stock: number[]; + fighters: number; + shields: number; + bastion: number; + bastionTarget: number; + bastionDoneAt: Date | null; + lastUpdate: Date; +} + +/** Colonists grow this fraction per hour toward the type's max. */ +const GROWTH_PER_HOUR = 0.01; +const SHIELD_REGEN_PER_HOUR = 100; + +/** + * Brings a planet up to `now`: finishes bastion upgrades, runs production, + * fighter output, colonist growth and shield recharge. Mutates and returns it. + * Quantities are fractional (stored as double precision) so frequent visits + * don't round production away; floor them for display and transfers. + */ +export function advancePlanet(p: PlanetState, now: Date): PlanetState { + const hours = Math.max(0, (now.getTime() - p.lastUpdate.getTime()) / 3_600_000); + if (p.bastionDoneAt && p.bastionDoneAt <= now && p.bastionTarget > p.bastion) { + p.bastion = p.bastionTarget; + p.bastionDoneAt = null; + } + if (hours <= 0) return p; + + const t = planetType(p.type); + const mult = p.bastion >= 5 ? 1.5 : 1; + const units = p.colonists / 100; + const cap = planetStorage(p.bastion); + for (let i = 0; i < p.stock.length; i++) { + p.stock[i] = Math.min(Math.max(cap, p.stock[i]), p.stock[i] + units * t.prod[i] * mult * hours); + } + p.fighters = p.fighters + units * t.fighters * hours; + if (p.colonists > 0 && p.colonists < t.maxColonists) { + p.colonists = Math.min(t.maxColonists, p.colonists * (1 + GROWTH_PER_HOUR * hours)); + } + p.shields = Math.min(Math.max(planetShieldCap(p.bastion), p.shields), p.shields + SHIELD_REGEN_PER_HOUR * hours); + p.lastUpdate = now; + return p; +} + +export function nextBastion(level: number) { + return BASTION.find((b) => b.level === level + 1) ?? null; +} diff --git a/src/doors/starlane/engine/pricing.test.ts b/src/doors/starlane/engine/pricing.test.ts new file mode 100644 index 0000000..a0a5d79 --- /dev/null +++ b/src/doors/starlane/engine/pricing.test.ts @@ -0,0 +1,30 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { regenPort, unitPrice, quoteTotal, type PortState } from './pricing'; +import { COMMODITIES } from './commodities'; + +const port = (pattern: string, stock: number[]): PortState => ({ + sector: 5, name: 'Test', pattern, stock: [...stock], cap: [1000, 1000, 1000], lastUpdate: new Date(0), +}); + +test('regen is fractional, capped, and time based', () => { + const p = port('BSS', [0, 500, 990]); + regenPort(p, new Date(60_000), 0.04); // one minute + assert.ok(p.stock[0] > 0.6 && p.stock[0] < 0.7, 'fractional regen kept'); + regenPort(p, new Date(10 * 3_600_000), 0.04); + assert.equal(p.stock[2], 1000); + assert.ok(p.stock.every((x, i) => x <= p.cap[i])); +}); + +test('a buy-low/sell-high route is profitable on average', () => { + for (let c = 0; c < 3; c++) { + const base = COMMODITIES[c].base; + const seller = port('SSS', [1000, 1000, 1000]); + const buyer = port('BBB', [1000, 1000, 1000]); + assert.ok(unitPrice(seller, c) < base, 'full seller is cheap'); + assert.ok(unitPrice(buyer, c) > base, 'hungry buyer pays well'); + const empty = port('SSS', [0, 0, 0]); + assert.ok(unitPrice(empty, c) > unitPrice(seller, c), 'scarcity raises price'); + assert.ok(quoteTotal(seller, c, 10) >= 1); + } +}); diff --git a/src/doors/starlane/engine/pricing.ts b/src/doors/starlane/engine/pricing.ts new file mode 100644 index 0000000..22d3ba0 --- /dev/null +++ b/src/doors/starlane/engine/pricing.ts @@ -0,0 +1,43 @@ +import { COMMODITIES, portBuys, type Pattern } from './commodities'; + +export interface PortState { + sector: number; + name: string; + pattern: Pattern; + /** For a commodity the port sells: units on hand. For one it buys: units of demand left. + * Fractional (double precision) so lazy regeneration isn't rounded away; floor for trading. */ + stock: number[]; + cap: number[]; + lastUpdate: Date; +} + +/** Lazily regenerates stock toward capacity based on elapsed time. Mutates and returns the port. */ +export function regenPort(port: PortState, now: Date, perHour: number): PortState { + const hours = Math.max(0, (now.getTime() - port.lastUpdate.getTime()) / 3_600_000); + if (hours > 0) { + for (let i = 0; i < port.stock.length; i++) { + port.stock[i] = Math.min(port.cap[i], port.stock[i] + port.cap[i] * perHour * hours); + } + port.lastUpdate = now; + } + return port; +} + +export function ratio(port: PortState, c: number): number { + return port.cap[c] > 0 ? Math.max(0, Math.min(1, port.stock[c] / port.cap[c])) : 0; +} + +/** + * Per-unit price the port quotes before haggling. + * Selling ports are cheap when well stocked (0.70x..1.15x base); + * buying ports pay more when demand is high (1.00x..1.50x base). + */ +export function unitPrice(port: PortState, c: number): number { + const base = COMMODITIES[c].base; + const r = ratio(port, c); + return portBuys(port.pattern, c) ? base * (1.0 + 0.5 * r) : base * (1.15 - 0.45 * r); +} + +export function quoteTotal(port: PortState, c: number, qty: number): number { + return Math.max(1, Math.round(unitPrice(port, c) * qty)); +} diff --git a/src/doors/starlane/engine/rng.ts b/src/doors/starlane/engine/rng.ts new file mode 100644 index 0000000..c545969 --- /dev/null +++ b/src/doors/starlane/engine/rng.ts @@ -0,0 +1,26 @@ +/** Seeded PRNG so a universe can be regenerated from its seed. */ +export type Rng = () => number; + +export function mulberry32(seed: number): Rng { + let a = seed >>> 0; + return () => { + 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 const randInt = (rng: Rng, min: number, max: number) => min + Math.floor(rng() * (max - min + 1)); +export const randRange = (rng: Rng, min: number, max: number) => min + rng() * (max - min); +export const chance = (rng: Rng, p: number) => rng() < p; +export const pick = (rng: Rng, arr: readonly T[]): T => arr[Math.floor(rng() * arr.length)]; + +export function shuffle(rng: Rng, arr: T[]): T[] { + for (let i = arr.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + return arr; +} diff --git a/src/doors/starlane/engine/universe.test.ts b/src/doors/starlane/engine/universe.test.ts new file mode 100644 index 0000000..fcf9f6d --- /dev/null +++ b/src/doors/starlane/engine/universe.test.ts @@ -0,0 +1,51 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { generateUniverse, toGraph } from './universe'; +import { stronglyConnected, shortestPath } from './pathfind'; + +const opts = (seed: number, size: number) => ({ seed, size, concordMax: 10, portDensity: 0.45, oneWayChance: 0.08 }); + +test('universe is strongly connected across many seeds', () => { + for (let seed = 1; seed <= 25; seed++) { + const size = [100, 300, 1000][seed % 3]; + const u = generateUniverse(opts(seed, size)); + assert.equal(u.sectors.length, size); + const g = toGraph(u.sectors); + assert.equal(stronglyConnected(g).length, 1, `seed ${seed} not strongly connected`); + for (const s of u.sectors) { + assert.ok(s.warps.length >= 1, `sector ${s.id} has no lanes`); + for (const w of s.warps) { + assert.ok(w >= 1 && w <= size, `bad lane ${s.id}->${w}`); + assert.notEqual(w, s.id); + } + } + } +}); + +test('universe is deterministic for a seed', () => { + const a = generateUniverse(opts(42, 500)); + const b = generateUniverse(opts(42, 500)); + assert.deepEqual(a, b); +}); + +test('concord space is clustered around terminus and ports are sane', () => { + const u = generateUniverse(opts(7, 1000)); + const g = toGraph(u.sectors); + for (let i = 2; i <= 10; i++) assert.ok(shortestPath(g, 1, i)!.length <= 4, `concord ${i} far from terminus`); + assert.ok(!u.ports.some((p) => p.sector === 1), 'terminus has the bazaar, not a port'); + const frac = u.ports.length / u.sectors.length; + assert.ok(frac > 0.35 && frac < 0.55, `port density ${frac}`); + for (const p of u.ports) { + assert.match(p.pattern, /^[BS]{3}$/); + p.stock.forEach((s, i) => assert.ok(s >= 0 && s <= p.cap[i])); + } + const avgDeg = u.sectors.reduce((a, s) => a + s.warps.length, 0) / u.sectors.length; + assert.ok(avgDeg > 2 && avgDeg < 6, `avg degree ${avgDeg}`); +}); + +test('large universe generates quickly', () => { + const t = Date.now(); + const u = generateUniverse(opts(3, 5000)); + assert.equal(stronglyConnected(toGraph(u.sectors)).length, 1); + assert.ok(Date.now() - t < 5000, 'took too long'); +}); diff --git a/src/doors/starlane/engine/universe.ts b/src/doors/starlane/engine/universe.ts new file mode 100644 index 0000000..91a4a56 --- /dev/null +++ b/src/doors/starlane/engine/universe.ts @@ -0,0 +1,203 @@ +import { mulberry32, randInt, chance, shuffle, type Rng } from './rng'; +import { stronglyConnected, type LaneGraph } from './pathfind'; +import { PATTERNS, PATTERN_WEIGHTS, NUM_COMMODITIES } from './commodities'; +import { REGIONS, portName } from '../data/names'; + +export interface GenSector { + id: number; + region: string; + warps: number[]; +} + +export interface GenPort { + sector: number; + name: string; + pattern: string; + stock: number[]; + cap: number[]; +} + +export interface GenUniverse { + sectors: GenSector[]; + ports: GenPort[]; +} + +export interface GenOptions { + seed: number; + size: number; + concordMax: number; + portDensity: number; + oneWayChance: number; +} + +const MAX_LANES = 6; + +function weightedPattern(rng: Rng): string { + const total = PATTERN_WEIGHTS.reduce((a, b) => a + b, 0); + let r = rng() * total; + for (let i = 0; i < PATTERNS.length; i++) { + r -= PATTERN_WEIGHTS[i]; + if (r < 0) return PATTERNS[i]; + } + return PATTERNS[0]; +} + +/** + * Builds a random universe. Sectors are scattered on a plane and linked to + * near neighbours (so lanes feel local), a few lanes are made one-way, and + * the graph is then patched until it is strongly connected. + */ +export function generateUniverse(o: GenOptions): GenUniverse { + const rng = mulberry32(o.seed); + const n = Math.max(o.concordMax + 10, o.size); + const xs = new Float64Array(n + 1); + const ys = new Float64Array(n + 1); + for (let i = 1; i <= n; i++) { + if (i <= o.concordMax) { + const a = (i / o.concordMax) * Math.PI * 2; + xs[i] = 0.5 + Math.cos(a) * 0.02 * (i === 1 ? 0 : 1); + ys[i] = 0.5 + Math.sin(a) * 0.02 * (i === 1 ? 0 : 1); + } else { + xs[i] = rng(); + ys[i] = rng(); + } + } + const d2 = (a: number, b: number) => (xs[a] - xs[b]) ** 2 + (ys[a] - ys[b]) ** 2; + + const out = new Map>(); + for (let i = 1; i <= n; i++) out.set(i, new Set()); + const degree = (i: number) => out.get(i)!.size; + const link = (a: number, b: number, twoWay = true) => { + if (a === b) return; + out.get(a)!.add(b); + if (twoWay) out.get(b)!.add(a); + }; + + // Concord Space: a hub-and-ring cluster around Terminus. + for (let i = 2; i <= o.concordMax; i++) { + if (i <= 7) link(1, i); + link(i, i === o.concordMax ? 2 : i + 1); + } + + // Nearest-neighbour lanes. Grid buckets keep this fast for large universes. + const cells = Math.max(1, Math.floor(Math.sqrt(n / 4))); + const grid = new Map(); + const cellOf = (i: number) => Math.min(cells - 1, Math.floor(xs[i] * cells)) * cells + Math.min(cells - 1, Math.floor(ys[i] * cells)); + for (let i = 1; i <= n; i++) { + const c = cellOf(i); + if (!grid.has(c)) grid.set(c, []); + grid.get(c)!.push(i); + } + const near = (i: number): number[] => { + const cx = Math.min(cells - 1, Math.floor(xs[i] * cells)); + const cy = Math.min(cells - 1, Math.floor(ys[i] * cells)); + const cand: number[] = []; + for (let r = 1; cand.length < 12 && r <= cells; r++) { + cand.length = 0; + for (let x = cx - r; x <= cx + r; x++) { + for (let y = cy - r; y <= cy + r; y++) { + if (x < 0 || y < 0 || x >= cells || y >= cells) continue; + for (const j of grid.get(x * cells + y) ?? []) if (j !== i) cand.push(j); + } + } + } + return cand.sort((a, b) => d2(i, a) - d2(i, b)); + }; + + for (let i = o.concordMax + 1; i <= n; i++) { + const want = randInt(rng, 1, 4); + for (const j of near(i)) { + if (degree(i) >= want) break; + if (degree(j) >= MAX_LANES || out.get(i)!.has(j)) continue; + // Concord only links outward through a few gates. + if (j <= o.concordMax && degree(j) >= 4) continue; + const oneWay = chance(rng, o.oneWayChance); + if (oneWay && rng() < 0.5) link(j, i, false); + else link(i, j, !oneWay); + } + } + + // Rift lanes: a few long-range shortcuts make the Drift a "small world" + // (without them the lattice is ~40 jumps across on average). + for (let i = o.concordMax + 1; i <= n; i++) { + if (!chance(rng, 0.05) || degree(i) >= MAX_LANES) continue; + const j = randInt(rng, o.concordMax + 1, n); + if (j !== i && degree(j) < MAX_LANES) link(i, j); + } + + // Make sure each Concord sector has a gate out to the Drift. + for (let i = 2; i <= o.concordMax; i++) { + if ([...out.get(i)!].some((j) => j > o.concordMax)) continue; + const j = near(i).find((x) => x > o.concordMax); + if (j) link(i, j); + } + + // Patch strong connectivity: tie every stray component to the one holding Terminus. + for (let pass = 0; pass < 10; pass++) { + const g: LaneGraph = new Map([...out].map(([k, v]) => [k, [...v]])); + const comps = stronglyConnected(g); + if (comps.length <= 1) break; + const main = new Set(comps.find((c) => c.includes(1))!); + for (const comp of comps) { + if (comp.includes(1)) continue; + let best: [number, number] | null = null; + let bestD = Infinity; + for (const a of comp) { + for (const b of near(a)) { + if (!main.has(b)) continue; + const pen = degree(b) >= MAX_LANES ? 0.05 : 0; + if (d2(a, b) + pen < bestD) { + bestD = d2(a, b) + pen; + best = [a, b]; + } + break; + } + } + if (!best) best = [comp[0], [...main][Math.floor(rng() * main.size)]]; + link(best[0], best[1]); + for (const a of comp) main.add(a); + } + } + + // Regions: nearest of a set of random region centres (Concord is its own). + const regionCount = Math.max(4, Math.min(REGIONS.length, Math.round(n / 40))); + const regionNames = shuffle(rng, [...REGIONS]).slice(0, regionCount); + const centres = regionNames.map(() => [rng(), rng()]); + const regionOf = (i: number) => { + if (i <= o.concordMax) return 'Concord Space'; + let best = 0; + let bd = Infinity; + centres.forEach(([x, y], k) => { + const d = (xs[i] - x) ** 2 + (ys[i] - y) ** 2; + if (d < bd) { + bd = d; + best = k; + } + }); + return regionNames[best]; + }; + + const sectors: GenSector[] = []; + for (let i = 1; i <= n; i++) sectors.push({ id: i, region: regionOf(i), warps: [...out.get(i)!].sort((a, b) => a - b) }); + + const ports: GenPort[] = []; + for (let i = 2; i <= n; i++) { + const p = i <= o.concordMax ? 0.6 : o.portDensity; + if (!chance(rng, p)) continue; + const size = randInt(rng, 1, 4); + const cap = Array.from({ length: NUM_COMMODITIES }, () => size * randInt(rng, 400, 900)); + ports.push({ + sector: i, + name: portName(rng), + pattern: weightedPattern(rng), + cap, + stock: cap.map((c) => Math.floor(c * (0.4 + rng() * 0.6))), + }); + } + return { sectors, ports }; +} + +/** Builds an in-memory lane graph from generated or loaded sectors. */ +export function toGraph(sectors: { id: number; warps: number[] }[]): LaneGraph { + return new Map(sectors.map((s) => [s.id, s.warps])); +} diff --git a/src/doors/starlane/index.ts b/src/doors/starlane/index.ts new file mode 100644 index 0000000..34030e1 --- /dev/null +++ b/src/doors/starlane/index.ts @@ -0,0 +1,88 @@ +import path from 'path'; +import type { DoorModule } from '../types'; +import type { Session } from '../../session/Session'; +import { pool, withTx, today } from './repo/q'; +import { getPilot, createPilot, savePilot } from './repo/players'; +import { loadWorld, bigBang, getUniverse } from './repo/world'; +import { addNews } from './repo/news'; +import { startTicker, runTick } from './ticker'; +import { commandLoop } from './screens/main'; +import { newsCommand, awayLog } from './screens/info'; +import { titleScreen } from './art/title'; +import { art, esc, confirm } from './screens/ui'; +import { SL } from './config'; + +const VERSION = 'v1.0'; + +async function init(): Promise { + if (!(await loadWorld())) { + console.log(`[starlane] no universe yet; generating ${SL.defaultSectors} sectors`); + await bigBang(SL.defaultSectors, SL.defaultTurnsPerDay); + } + await runTick().catch((err) => console.error('[starlane] first tick failed', err)); + startTicker(); + console.log(`[starlane] universe epoch ${getUniverse().epoch} ready (${getUniverse().size} sectors)`); +} + +async function newPilot(s: Session, uid: number): Promise { + s.clear(); + const intro = [ + '|07 The Concord drew its border at sector ten and called everything past it', + ' |07"the Drift". No law out there, no patrols, no promises: only lanes, ports,', + ' |07raiders, and the fortunes of whoever is quick enough to grab them.', + '', + ' |07You have a patched-up |11Skiff|07, a few thousand credits, and a docking', + ' |07permit at |14Terminus|07. Buy low. Sell high. Don\'t die more than twice a day.', + '', + ]; + await art(s, intro); + if (!(await confirm(s, ' Sign on as a pilot?', true))) return false; + await s.print('|03 Name your ship |08(Enter for "Rustbucket")|03: '); + const name = (await s.readLine({ maxLen: 24 })).trim() || 'Rustbucket'; + await createPilot(uid, name, getUniverse().turns_per_day); + await addNews(`|07A new pilot, |11${esc(s.user!.handle)}|07, signs on at Terminus in the "${esc(name)}".`); + await s.println(' |10Welcome to the frontier. Press |15?|10 at the sector prompt for help.'); + await s.pause(); + return true; +} + +/** Daily turn refill and death-counter reset. */ +async function dailyReset(uid: number): Promise { + return withTx(async (c) => { + const p = (await getPilot(c, uid, true))!; + if (p.turns_date === today()) return false; + p.turns_date = today(); + p.turns_left = getUniverse().turns_per_day; + p.deaths_today = 0; + await savePilot(c, p); + return true; + }); +} + +async function run(s: Session): Promise { + const uid = s.user!.id; + s.activity = SL.title; + s.clear(); + await art(s, titleScreen(VERSION)); + await s.pause(); + + if (!(await getPilot(pool, uid)) && !(await newPilot(s, uid))) return; + const refilled = await dailyReset(uid); + + await newsCommand(s, 8); + if (refilled) await s.println(` |10A new day in the Drift. |07You have |15${getUniverse().turns_per_day}|07 turns.`); + await s.pause(); + await awayLog(s, uid); + + await commandLoop(s, uid); + await s.println(' |07You power down and log off the frontier. Fly safe.'); +} + +export const starlane: DoorModule = { + id: 'starlane', + name: 'STARLANE', + description: 'Frontier space trading. Haul, haggle, conquer.', + migrationsDir: path.join(__dirname, 'migrations'), + init, + run, +}; diff --git a/src/doors/starlane/migrations/001_init.sql b/src/doors/starlane/migrations/001_init.sql new file mode 100644 index 0000000..457ef1b --- /dev/null +++ b/src/doors/starlane/migrations/001_init.sql @@ -0,0 +1,143 @@ +-- STARLANE door game. All tables are prefixed sl_ and wiped by a Big Bang. + +CREATE TABLE sl_universe ( + id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1), + seed BIGINT NOT NULL, + size INTEGER NOT NULL, + epoch INTEGER NOT NULL DEFAULT 1, + turns_per_day INTEGER NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE sl_sectors ( + id INTEGER PRIMARY KEY, + region VARCHAR(40) NOT NULL, + warps INTEGER[] NOT NULL +); + +CREATE TABLE sl_ports ( + sector INTEGER PRIMARY KEY REFERENCES sl_sectors(id) ON DELETE CASCADE, + name VARCHAR(40) NOT NULL, + pattern CHAR(3) NOT NULL, + stock DOUBLE PRECISION[] NOT NULL, + cap INTEGER[] NOT NULL, + last_update TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE sl_syndicates ( + id SERIAL PRIMARY KEY, + name VARCHAR(30) NOT NULL, + leader_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + treasury BIGINT NOT NULL DEFAULT 0, + memo VARCHAR(200) NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE UNIQUE INDEX sl_syndicates_name_idx ON sl_syndicates (lower(name)); + +CREATE TABLE sl_players ( + user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + ship_type INTEGER NOT NULL DEFAULT 1, + ship_name VARCHAR(24) NOT NULL, + sector INTEGER NOT NULL DEFAULT 1, + prev_sector INTEGER, + landed_planet INTEGER, + credits BIGINT NOT NULL, + holds INTEGER NOT NULL, + cargo INTEGER[] NOT NULL DEFAULT '{0,0,0}', + colonists INTEGER NOT NULL DEFAULT 0, + fighters INTEGER NOT NULL DEFAULT 0, + shields INTEGER NOT NULL DEFAULT 0, + mines INTEGER NOT NULL DEFAULT 0, + tracers INTEGER NOT NULL DEFAULT 0, + probes INTEGER NOT NULL DEFAULT 0, + seeds INTEGER NOT NULL DEFAULT 0, + mass_scanner BOOLEAN NOT NULL DEFAULT false, + deep_scanner BOOLEAN NOT NULL DEFAULT false, + turns_left INTEGER NOT NULL, + turns_date VARCHAR(10) NOT NULL, + xp INTEGER NOT NULL DEFAULT 0, + alignment INTEGER NOT NULL DEFAULT 0, + syndicate_id INTEGER REFERENCES sl_syndicates(id) ON DELETE SET NULL, + deaths_today INTEGER NOT NULL DEFAULT 0, + kills INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX sl_players_sector_idx ON sl_players (sector); + +CREATE TABLE sl_invites ( + syndicate_id INTEGER NOT NULL REFERENCES sl_syndicates(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (syndicate_id, user_id) +); + +CREATE TABLE sl_explored ( + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + sector INTEGER NOT NULL, + PRIMARY KEY (user_id, sector) +); + +CREATE TABLE sl_planets ( + id SERIAL PRIMARY KEY, + sector INTEGER NOT NULL, + name VARCHAR(24) NOT NULL, + type INTEGER NOT NULL, + owner_id INTEGER REFERENCES users(id) ON DELETE SET NULL, + syndicate_id INTEGER REFERENCES sl_syndicates(id) ON DELETE SET NULL, + colonists DOUBLE PRECISION NOT NULL DEFAULT 0, + stock DOUBLE PRECISION[] NOT NULL DEFAULT '{0,0,0}', + fighters DOUBLE PRECISION NOT NULL DEFAULT 0, + shields DOUBLE PRECISION NOT NULL DEFAULT 0, + credits BIGINT NOT NULL DEFAULT 0, + bastion INTEGER NOT NULL DEFAULT 0, + bastion_target INTEGER NOT NULL DEFAULT 0, + bastion_done_at TIMESTAMPTZ, + last_update TIMESTAMPTZ NOT NULL DEFAULT now(), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX sl_planets_sector_idx ON sl_planets (sector); + +-- One defence stack (fighters + mines) per sector, owned by one pilot. +CREATE TABLE sl_defenses ( + sector INTEGER PRIMARY KEY, + owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + syndicate_id INTEGER REFERENCES sl_syndicates(id) ON DELETE SET NULL, + fighters INTEGER NOT NULL DEFAULT 0, + mode CHAR(1) NOT NULL DEFAULT 'D', -- D defensive, T toll, O offensive + mines INTEGER NOT NULL DEFAULT 0 +); + +CREATE TABLE sl_npcs ( + id SERIAL PRIMARY KEY, + name VARCHAR(30) NOT NULL, + clan VARCHAR(30) NOT NULL, + ship_type INTEGER NOT NULL, + sector INTEGER NOT NULL, + fighters INTEGER NOT NULL, + shields INTEGER NOT NULL, + credits BIGINT NOT NULL DEFAULT 0 +); +CREATE INDEX sl_npcs_sector_idx ON sl_npcs (sector); + +CREATE TABLE sl_tracers ( + owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + target_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + placed_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (owner_id, target_id) +); + +CREATE TABLE sl_news ( + id SERIAL PRIMARY KEY, + at TIMESTAMPTZ NOT NULL DEFAULT now(), + text VARCHAR(200) NOT NULL +); + +-- "While you were away" log. +CREATE TABLE sl_messages ( + id SERIAL PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + at TIMESTAMPTZ NOT NULL DEFAULT now(), + text VARCHAR(240) NOT NULL, + seen BOOLEAN NOT NULL DEFAULT false +); +CREATE INDEX sl_messages_user_idx ON sl_messages (user_id, seen); diff --git a/src/doors/starlane/repo/defenses.ts b/src/doors/starlane/repo/defenses.ts new file mode 100644 index 0000000..ba9859a --- /dev/null +++ b/src/doors/starlane/repo/defenses.ts @@ -0,0 +1,47 @@ +import { pool, type Q } from './q'; + +export type DefenseMode = 'D' | 'T' | 'O'; + +export interface Defense { + sector: number; + owner_id: number; + owner_handle: string; + syndicate_id: number | null; + fighters: number; + mode: DefenseMode; + mines: number; +} + +export const MODE_NAMES: Record = { D: 'Defensive', T: 'Toll', O: 'Offensive' }; + +const SELECT = `SELECT d.*, u.handle AS owner_handle FROM sl_defenses d JOIN users u ON u.id = d.owner_id`; + +export async function getDefense(q: Q, sector: number, lock = false): Promise { + const { rows } = await q.query(`${SELECT} WHERE d.sector = $1 ${lock ? 'FOR UPDATE OF d' : ''}`, [sector]); + return rows[0] ?? null; +} + +/** Upserts, or deletes the row when nothing is left. */ +export async function saveDefense(q: Q, d: Defense): Promise { + if (d.fighters <= 0 && d.mines <= 0) { + await q.query('DELETE FROM sl_defenses WHERE sector = $1', [d.sector]); + return; + } + await q.query( + `INSERT INTO sl_defenses (sector, owner_id, syndicate_id, fighters, mode, mines) VALUES ($1, $2, $3, $4, $5, $6) + ON CONFLICT (sector) DO UPDATE SET owner_id = $2, syndicate_id = $3, fighters = $4, mode = $5, mines = $6`, + [d.sector, d.owner_id, d.syndicate_id, Math.max(0, d.fighters), d.mode, Math.max(0, d.mines)], + ); +} + +export function friendlyDefense(d: Defense, userId: number, syndicateId: number | null): boolean { + return d.owner_id === userId || (d.syndicate_id !== null && d.syndicate_id === syndicateId); +} + +export async function defensesFor(userId: number, syndicateId: number | null): Promise { + const { rows } = await pool.query( + `${SELECT} WHERE d.owner_id = $1 OR (d.syndicate_id IS NOT NULL AND d.syndicate_id = $2) ORDER BY d.sector`, + [userId, syndicateId ?? -1], + ); + return rows; +} diff --git a/src/doors/starlane/repo/news.ts b/src/doors/starlane/repo/news.ts new file mode 100644 index 0000000..6cce2bb --- /dev/null +++ b/src/doors/starlane/repo/news.ts @@ -0,0 +1,54 @@ +import { pool, type Q } from './q'; +import { notifyUser, sessionsForUser } from '../../../nodes'; +import { SL } from '../config'; + +export interface NewsItem { + id: number; + at: Date; + text: string; +} + +/** Posts to the Drift Herald (pipe codes allowed; escape user text with esc()). */ +export async function addNews(text: string, q: Q = pool): Promise { + await q.query('INSERT INTO sl_news (text) VALUES ($1)', [text.slice(0, 200)]); +} + +export async function recentNews(limit = 15): Promise { + const { rows } = await pool.query('SELECT * FROM sl_news ORDER BY id DESC LIMIT $1', [limit]); + return rows; +} + +/** True if this user is currently inside STARLANE on some node. */ +export function inGame(userId: number): boolean { + return sessionsForUser(userId).some((s) => s.activity.startsWith(SL.title)); +} + +/** + * Tells a pilot something: live if they're in the game right now, + * otherwise it waits in their "while you were away" log. + */ +export async function tell(userId: number, text: string, q: Q = pool): Promise { + if (inGame(userId)) { + notifyUser(userId, text); + return; + } + await q.query('INSERT INTO sl_messages (user_id, text) VALUES ($1, $2)', [userId, text.slice(0, 240)]); +} + +/** Live-only notice for pilots who are in the game (e.g. "X warps in"). */ +export function tellIfOnline(userId: number, text: string): void { + if (inGame(userId)) notifyUser(userId, text); +} + +export async function takeMessages(userId: number): Promise { + const { rows } = await pool.query( + 'UPDATE sl_messages SET seen = true WHERE user_id = $1 AND NOT seen RETURNING id, at, text', + [userId], + ); + return rows.sort((a, b) => a.id - b.id); +} + +export async function pruneOld(): Promise { + await pool.query(`DELETE FROM sl_news WHERE at < now() - make_interval(days => $1)`, [SL.newsDays]); + await pool.query(`DELETE FROM sl_messages WHERE at < now() - make_interval(days => $1)`, [SL.messageDays]); +} diff --git a/src/doors/starlane/repo/npcs.ts b/src/doors/starlane/repo/npcs.ts new file mode 100644 index 0000000..13abe67 --- /dev/null +++ b/src/doors/starlane/repo/npcs.ts @@ -0,0 +1,46 @@ +import { pool, type Q } from './q'; + +export interface Reaver { + id: number; + name: string; + clan: string; + ship_type: number; + sector: number; + fighters: number; + shields: number; + credits: number; +} + +export async function reaversInSector(q: Q, sector: number, lock = false): Promise { + const { rows } = await q.query(`SELECT * FROM sl_npcs WHERE sector = $1 ORDER BY id ${lock ? 'FOR UPDATE' : ''}`, [sector]); + return rows; +} + +export async function getReaver(q: Q, id: number, lock = false): Promise { + const { rows } = await q.query(`SELECT * FROM sl_npcs WHERE id = $1 ${lock ? 'FOR UPDATE' : ''}`, [id]); + return rows[0] ?? null; +} + +export async function allReavers(q: Q = pool): Promise { + return (await q.query('SELECT * FROM sl_npcs ORDER BY id')).rows; +} + +export async function saveReaver(q: Q, r: Reaver): Promise { + if (r.fighters <= 0 && r.shields <= 0) { + await q.query('DELETE FROM sl_npcs WHERE id = $1', [r.id]); + return; + } + await q.query('UPDATE sl_npcs SET sector=$2, fighters=$3, shields=$4, credits=$5 WHERE id=$1', [ + r.id, r.sector, Math.max(0, r.fighters), Math.max(0, r.shields), Math.floor(r.credits), + ]); +} + +export async function deleteReaver(q: Q, id: number): Promise { + await q.query('DELETE FROM sl_npcs WHERE id = $1', [id]); +} + +export async function spawnReaver(q: Q, r: Omit): Promise { + await q.query('INSERT INTO sl_npcs (name, clan, ship_type, sector, fighters, shields, credits) VALUES ($1,$2,$3,$4,$5,$6,$7)', [ + r.name, r.clan, r.ship_type, r.sector, r.fighters, r.shields, r.credits, + ]); +} diff --git a/src/doors/starlane/repo/planets.ts b/src/doors/starlane/repo/planets.ts new file mode 100644 index 0000000..eea2707 --- /dev/null +++ b/src/doors/starlane/repo/planets.ts @@ -0,0 +1,91 @@ +import { pool, type Q } from './q'; +import { advancePlanet } from '../engine/planets'; + +export interface Planet { + id: number; + sector: number; + name: string; + type: number; + owner_id: number | null; + owner_handle: string | null; + syndicate_id: number | null; + colonists: number; + stock: number[]; + fighters: number; + shields: number; + credits: number; + bastion: number; + bastion_target: number; + bastion_done_at: Date | null; + last_update: Date; +} + +const SELECT = `SELECT pl.*, u.handle AS owner_handle FROM sl_planets pl LEFT JOIN users u ON u.id = pl.owner_id`; + +/** Applies production etc. up to now (in memory; save to persist). */ +function advance(p: Planet): Planet { + p.stock = p.stock.map(Number); + const st = { + type: p.type, + colonists: p.colonists, + stock: p.stock, + fighters: p.fighters, + shields: p.shields, + bastion: p.bastion, + bastionTarget: p.bastion_target, + bastionDoneAt: p.bastion_done_at, + lastUpdate: p.last_update, + }; + advancePlanet(st, new Date()); + Object.assign(p, { + colonists: st.colonists, + stock: st.stock, + fighters: st.fighters, + shields: st.shields, + bastion: st.bastion, + bastion_done_at: st.bastionDoneAt, + last_update: st.lastUpdate, + }); + return p; +} + +export async function getPlanet(q: Q, id: number, lock = false): Promise { + const { rows } = await q.query(`${SELECT} WHERE pl.id = $1 ${lock ? 'FOR UPDATE OF pl' : ''}`, [id]); + return rows[0] ? advance(rows[0]) : null; +} + +export async function planetsInSector(q: Q, sector: number): Promise { + const { rows } = await q.query(`${SELECT} WHERE pl.sector = $1 ORDER BY pl.id`, [sector]); + return rows.map(advance); +} + +export async function planetsFor(userId: number, syndicateId: number | null): Promise { + const { rows } = await pool.query( + `${SELECT} WHERE pl.owner_id = $1 OR (pl.syndicate_id IS NOT NULL AND pl.syndicate_id = $2) ORDER BY pl.sector, pl.id`, + [userId, syndicateId ?? -1], + ); + return rows.map(advance); +} + +export async function savePlanet(q: Q, p: Planet): Promise { + await q.query( + `UPDATE sl_planets SET name=$2, owner_id=$3, syndicate_id=$4, colonists=$5, stock=$6, fighters=$7, shields=$8, + credits=$9, bastion=$10, bastion_target=$11, bastion_done_at=$12, last_update=$13 + WHERE id=$1`, + [p.id, p.name, p.owner_id, p.syndicate_id, p.colonists, p.stock, p.fighters, p.shields, Math.floor(p.credits), + p.bastion, p.bastion_target, p.bastion_done_at, p.last_update], + ); +} + +export async function createPlanet(q: Q, sector: number, name: string, type: number, ownerId: number, syndicateId: number | null): Promise { + const { rows } = await q.query<{ id: number }>( + 'INSERT INTO sl_planets (sector, name, type, owner_id, syndicate_id) VALUES ($1, $2, $3, $4, $5) RETURNING id', + [sector, name, type, ownerId, syndicateId], + ); + return rows[0].id; +} + +/** Does this pilot (or their syndicate) control the planet? */ +export function ownsPlanet(p: Planet, userId: number, syndicateId: number | null): boolean { + return p.owner_id === userId || (p.syndicate_id !== null && p.syndicate_id === syndicateId); +} diff --git a/src/doors/starlane/repo/players.ts b/src/doors/starlane/repo/players.ts new file mode 100644 index 0000000..d6dc15c --- /dev/null +++ b/src/doors/starlane/repo/players.ts @@ -0,0 +1,132 @@ +import { pool, today, type Q } from './q'; +import { SL } from '../config'; +import { ship } from '../data/ships'; + +export interface Pilot { + user_id: number; + handle: string; + ship_type: number; + ship_name: string; + sector: number; + prev_sector: number | null; + landed_planet: number | null; + credits: number; + holds: number; + cargo: number[]; + colonists: number; + fighters: number; + shields: number; + mines: number; + tracers: number; + probes: number; + seeds: number; + mass_scanner: boolean; + deep_scanner: boolean; + turns_left: number; + turns_date: string; + xp: number; + alignment: number; + syndicate_id: number | null; + deaths_today: number; + kills: number; + created_at: Date; + last_seen_at: Date; +} + +const SELECT = `SELECT p.*, u.handle FROM sl_players p JOIN users u ON u.id = p.user_id`; + +export async function getPilot(q: Q, userId: number, lock = false): Promise { + const { rows } = await q.query(`${SELECT} WHERE p.user_id = $1 ${lock ? 'FOR UPDATE OF p' : ''}`, [userId]); + return rows[0] ?? null; +} + +/** Locks several pilots in id order (deadlock-safe). */ +export async function lockPilots(q: Q, ids: number[]): Promise> { + const sorted = [...new Set(ids)].sort((a, b) => a - b); + const out = new Map(); + for (const id of sorted) { + const p = await getPilot(q, id, true); + if (p) out.set(id, p); + } + return out; +} + +export async function findPilotByHandle(q: Q, handle: string): Promise { + const { rows } = await q.query(`${SELECT} WHERE lower(u.handle) = lower($1)`, [handle]); + return rows[0] ?? null; +} + +export async function createPilot(userId: number, shipName: string, turns: number): Promise { + const start = ship(1); + await pool.query( + `INSERT INTO sl_players (user_id, ship_type, ship_name, sector, credits, holds, fighters, shields, turns_left, turns_date) + VALUES ($1, 1, $2, $3, $4, $5, $6, $7, $8, $9)`, + [userId, shipName, SL.terminus, SL.startCredits, start.holds, SL.startFighters, SL.startShields, turns, today()], + ); + await markExplored(pool, userId, SL.terminus); +} + +/** Writes back every mutable column. */ +export async function savePilot(q: Q, p: Pilot): Promise { + await q.query( + `UPDATE sl_players SET ship_type=$2, ship_name=$3, sector=$4, prev_sector=$5, landed_planet=$6, credits=$7, + holds=$8, cargo=$9, colonists=$10, fighters=$11, shields=$12, mines=$13, tracers=$14, probes=$15, seeds=$16, + mass_scanner=$17, deep_scanner=$18, turns_left=$19, turns_date=$20, xp=$21, alignment=$22, syndicate_id=$23, + deaths_today=$24, kills=$25, last_seen_at=now() + WHERE user_id=$1`, + [ + p.user_id, p.ship_type, p.ship_name, p.sector, p.prev_sector, p.landed_planet, Math.floor(p.credits), + p.holds, p.cargo, p.colonists, p.fighters, p.shields, p.mines, p.tracers, p.probes, p.seeds, + p.mass_scanner, p.deep_scanner, p.turns_left, p.turns_date, p.xp, p.alignment, p.syndicate_id, + p.deaths_today, p.kills, + ], + ); +} + +export const usedHolds = (p: Pilot) => p.cargo.reduce((a, b) => a + b, 0) + p.colonists; +export const freeHolds = (p: Pilot) => Math.max(0, p.holds - usedHolds(p)); + +/** Ships in open space in a sector (pilots landed on planets are hidden). */ +export async function pilotsInSector(q: Q, sector: number, exceptUser?: number): Promise { + const { rows } = await q.query( + `${SELECT} WHERE p.sector = $1 AND p.landed_planet IS NULL AND p.user_id <> $2 ORDER BY u.handle`, + [sector, exceptUser ?? 0], + ); + return rows; +} + +export async function markExplored(q: Q, userId: number, sector: number): Promise { + await q.query('INSERT INTO sl_explored (user_id, sector) VALUES ($1, $2) ON CONFLICT DO NOTHING', [userId, sector]); +} + +export async function exploredSet(userId: number): Promise> { + const { rows } = await pool.query<{ sector: number }>('SELECT sector FROM sl_explored WHERE user_id = $1', [userId]); + return new Set(rows.map((r) => r.sector)); +} + +export async function allPilots(): Promise { + const { rows } = await pool.query(`${SELECT} ORDER BY u.handle`); + return rows; +} + +/** Ship lost: escape pod to Terminus in a fresh Skiff. Credits on hand are kept (minus loot). */ +export function podPilot(p: Pilot): void { + const s = ship(1); + p.ship_type = 1; + p.holds = s.holds; + p.cargo = [0, 0, 0]; + p.colonists = 0; + p.fighters = 0; + p.shields = 0; + p.mines = 0; + p.tracers = 0; + p.probes = 0; + p.seeds = 0; + p.mass_scanner = false; + p.deep_scanner = false; + p.prev_sector = p.sector; + p.sector = SL.terminus; + p.landed_planet = null; + p.deaths_today++; + if (p.deaths_today >= SL.maxDeathsPerDay) p.turns_left = 0; +} diff --git a/src/doors/starlane/repo/q.ts b/src/doors/starlane/repo/q.ts new file mode 100644 index 0000000..cdc730d --- /dev/null +++ b/src/doors/starlane/repo/q.ts @@ -0,0 +1,10 @@ +import type { Pool, PoolClient } from 'pg'; +export { pool, withTx } from '../../../db'; + +/** Anything that can run a query: the pool, or a client inside withTx. */ +export type Q = Pool | PoolClient; + +/** Today's date in the server's TZ, YYYY-MM-DD. Daily turns reset on change. */ +export function today(): string { + return new Date().toLocaleDateString('en-CA'); +} diff --git a/src/doors/starlane/repo/syndicates.ts b/src/doors/starlane/repo/syndicates.ts new file mode 100644 index 0000000..5d871f2 --- /dev/null +++ b/src/doors/starlane/repo/syndicates.ts @@ -0,0 +1,38 @@ +import { pool, type Q } from './q'; + +export interface Syndicate { + id: number; + name: string; + leader_id: number; + treasury: number; + memo: string; + created_at: Date; +} + +export async function getSyndicate(q: Q, id: number | null, lock = false): Promise { + if (id === null) return null; + const { rows } = await q.query(`SELECT * FROM sl_syndicates WHERE id = $1 ${lock ? 'FOR UPDATE' : ''}`, [id]); + return rows[0] ?? null; +} + +export async function syndicateNames(): Promise> { + const { rows } = await pool.query<{ id: number; name: string }>('SELECT id, name FROM sl_syndicates'); + return new Map(rows.map((r) => [r.id, r.name])); +} + +export async function members(id: number): Promise<{ user_id: number; handle: string; sector: number; xp: number }[]> { + const { rows } = await pool.query( + `SELECT p.user_id, u.handle, p.sector, p.xp FROM sl_players p JOIN users u ON u.id = p.user_id + WHERE p.syndicate_id = $1 ORDER BY p.xp DESC`, + [id], + ); + return rows; +} + +export async function invitesFor(userId: number): Promise { + const { rows } = await pool.query( + 'SELECT s.* FROM sl_invites i JOIN sl_syndicates s ON s.id = i.syndicate_id WHERE i.user_id = $1', + [userId], + ); + return rows; +} diff --git a/src/doors/starlane/repo/world.ts b/src/doors/starlane/repo/world.ts new file mode 100644 index 0000000..8722c0d --- /dev/null +++ b/src/doors/starlane/repo/world.ts @@ -0,0 +1,128 @@ +import { pool, withTx, type Q } from './q'; +import { SL } from '../config'; +import { generateUniverse, toGraph } from '../engine/universe'; +import { regenPort, type PortState } from '../engine/pricing'; +import type { LaneGraph } from '../engine/pathfind'; + +export interface Universe { + seed: number; + size: number; + epoch: number; + turns_per_day: number; + created_at: Date; +} + +/** Lanes never change between Big Bangs, so the graph lives in memory. */ +let graph: LaneGraph = new Map(); +let regions = new Map(); +let universe: Universe | null = null; + +export const lanes = () => graph; +export const warpsFrom = (sector: number) => graph.get(sector) ?? []; +export const regionOf = (sector: number) => regions.get(sector) ?? 'Uncharted'; +export const isConcord = (sector: number) => sector >= 1 && sector <= SL.concordMax; + +export function getUniverse(): Universe { + if (!universe) throw new Error('STARLANE universe not loaded'); + return universe; +} + +export async function loadWorld(): Promise { + const u = await pool.query('SELECT * FROM sl_universe WHERE id = 1'); + if (!u.rows[0]) return false; + universe = u.rows[0]; + const { rows } = await pool.query<{ id: number; region: string; warps: number[] }>('SELECT * FROM sl_sectors'); + graph = toGraph(rows); + regions = new Map(rows.map((r) => [r.id, r.region])); + return true; +} + +const SL_TABLES = [ + 'sl_tracers', 'sl_messages', 'sl_news', 'sl_npcs', 'sl_defenses', 'sl_planets', 'sl_explored', + 'sl_invites', 'sl_players', 'sl_syndicates', 'sl_ports', 'sl_sectors', 'sl_universe', +]; + +/** Wipes the game and creates a new universe. */ +export async function bigBang(size: number, turnsPerDay: number, seed = Math.floor(Math.random() * 2 ** 31)): Promise { + const gen = generateUniverse({ + seed, + size, + concordMax: SL.concordMax, + portDensity: SL.portDensity, + oneWayChance: SL.oneWayChance, + }); + await withTx(async (c) => { + await c.query('SELECT pg_advisory_xact_lock(727300)'); + const prev = await c.query<{ epoch: number }>('SELECT epoch FROM sl_universe WHERE id = 1'); + const epoch = (prev.rows[0]?.epoch ?? 0) + 1; + await c.query(`TRUNCATE ${SL_TABLES.join(', ')} RESTART IDENTITY CASCADE`); + await c.query('INSERT INTO sl_universe (id, seed, size, epoch, turns_per_day) VALUES (1, $1, $2, $3, $4)', [ + seed, gen.sectors.length, epoch, turnsPerDay, + ]); + for (let i = 0; i < gen.sectors.length; i += 500) { + const chunk = gen.sectors.slice(i, i + 500); + await c.query( + `INSERT INTO sl_sectors (id, region, warps) + SELECT id, region, warps::int[] FROM unnest($1::int[], $2::text[], $3::text[]) AS t(id, region, warps)`, + [chunk.map((s) => s.id), chunk.map((s) => s.region), chunk.map((s) => `{${s.warps.join(',')}}`)], + ); + } + for (const p of gen.ports) { + await c.query('INSERT INTO sl_ports (sector, name, pattern, stock, cap) VALUES ($1, $2, $3, $4, $5)', [ + p.sector, p.name, p.pattern, p.stock, p.cap, + ]); + } + await c.query('INSERT INTO sl_news (text) VALUES ($1)', [ + `|14BIG BANG!|07 A new frontier of |15${gen.sectors.length}|07 sectors opens. Terminus is taking pilots.`, + ]); + }); + await loadWorld(); +} + +// ---- ports ---------------------------------------------------------------- + +interface PortRow { + sector: number; + name: string; + pattern: string; + stock: number[]; + cap: number[]; + last_update: Date; +} + +const toPort = (r: PortRow): PortState => ({ + sector: r.sector, + name: r.name, + pattern: r.pattern, + stock: r.stock.map(Number), + cap: r.cap.map(Number), + lastUpdate: r.last_update, +}); + +export async function getPort(q: Q, sector: number, lock = false): Promise { + const { rows } = await q.query(`SELECT * FROM sl_ports WHERE sector = $1 ${lock ? 'FOR UPDATE' : ''}`, [sector]); + return rows[0] ? regenPort(toPort(rows[0]), new Date(), SL.portRegenPerHour) : null; +} + +export async function savePort(q: Q, p: PortState): Promise { + await q.query('UPDATE sl_ports SET stock = $2, last_update = $3 WHERE sector = $1', [p.sector, p.stock, p.lastUpdate]); +} + +export async function portsIn(sectors: number[]): Promise { + if (!sectors.length) return []; + const { rows } = await pool.query('SELECT * FROM sl_ports WHERE sector = ANY($1::int[]) ORDER BY sector', [sectors]); + const now = new Date(); + return rows.map((r) => regenPort(toPort(r), now, SL.portRegenPerHour)); +} + +export async function worldStats() { + const one = async (sql: string) => Number((await pool.query<{ n: number }>(sql)).rows[0]?.n ?? 0); + return { + sectors: graph.size, + ports: await one('SELECT count(*) AS n FROM sl_ports'), + pilots: await one('SELECT count(*) AS n FROM sl_players'), + planets: await one('SELECT count(*) AS n FROM sl_planets'), + reavers: await one('SELECT count(*) AS n FROM sl_npcs'), + syndicates: await one('SELECT count(*) AS n FROM sl_syndicates'), + }; +} diff --git a/src/doors/starlane/screens/arrival.ts b/src/doors/starlane/screens/arrival.ts new file mode 100644 index 0000000..93fad85 --- /dev/null +++ b/src/doors/starlane/screens/arrival.ts @@ -0,0 +1,191 @@ +import type { Session } from '../../../session/Session'; +import { pool, withTx } from '../repo/q'; +import { getPilot, lockPilots, pilotsInSector, savePilot } from '../repo/players'; +import { getDefense, saveDefense, friendlyDefense } from '../repo/defenses'; +import { planetsInSector, getPlanet, savePlanet, ownsPlanet } from '../repo/planets'; +import { reaversInSector, saveReaver } from '../repo/npcs'; +import { isConcord } from '../repo/world'; +import { tell, tellIfOnline } from '../repo/news'; +import { battle, mineStrike } from '../engine/combat'; +import { lanceDamage } from '../data/planets'; +import { ship } from '../data/ships'; +import { destroyPilot } from '../actions/fate'; +import { applyDamage } from '../actions/damage'; +import { EXPLOSION, ESCAPE_POD, REAVER } from '../art/scenes'; +import { attackDefense } from './combat'; +import { commas, esc, art, beat, readNumber } from './ui'; + +export type Arrival = 'clear' | 'hazard' | 'retreated' | 'destroyed'; + +/** + * Everything that happens when a ship drops into a sector: mines, offensive + * fighters, Lance batteries, Reaver ambushes, then the toll/blockade choice. + */ +export async function arrive(s: Session, uid: number): Promise { + const events: string[] = []; + let hazard = false; + + const result = await withTx(async (c) => { + const p = (await getPilot(c, uid, true))!; + const sector = p.sector; + if (isConcord(sector)) return 'ok' as const; + + // Mines and offensive fighters. + const d = await getDefense(c, sector, true); + if (d && !friendlyDefense(d, uid, p.syndicate_id)) { + hazard = true; + if (d.mines > 0) { + const m = mineStrike(d.mines, p, Math.random); + d.mines -= m.detonated; + p.shields -= m.shieldLoss; + p.fighters -= m.fighterLoss; + events.push(`|12BOOM!|07 ${m.detonated} mine${m.detonated === 1 ? '' : 's'} detonate against your hull: -${m.shieldLoss} shields, -${m.fighterLoss} fighters.`); + await tell(d.owner_id, `|10Your mines in sector ${sector} hit ${esc(p.handle)}${m.destroyed ? ' and destroyed the ship!' : '.'}`, c); + if (m.destroyed) { + await saveDefense(c, d); + await destroyPilot(c, p, { kind: 'hazard', what: `${esc(d.owner_handle)}'s minefield`, ownerId: d.owner_id }, true); + return 'dead' as const; + } + } + if (d.fighters > 0 && d.mode === 'O') { + const b = battle({ fighters: d.fighters, shields: 0 }, { fighters: p.fighters, shields: p.shields }, Math.random); + d.fighters = b.attacker.fighters; + p.fighters = b.defender.fighters; + p.shields = b.defender.shields; + events.push(`|12Offensive fighters swarm you!|07 You lose ${b.defenderFightersLost} fighters and ${b.defenderShieldsLost} shields; ${b.attackerLost} of theirs go down.`); + await tell(d.owner_id, `|10Your offensive fighters in sector ${sector} engaged ${esc(p.handle)}${b.defenderBroken ? ' and destroyed the ship!' : '.'}`, c); + if (b.defenderBroken) { + await saveDefense(c, d); + await destroyPilot(c, p, { kind: 'hazard', what: `${esc(d.owner_handle)}'s fighters`, ownerId: d.owner_id }, true); + return 'dead' as const; + } + } + await saveDefense(c, d); + } + + // Lance batteries on hostile planets. + for (const seen of await planetsInSector(c, sector)) { + if (ownsPlanet(seen, uid, p.syndicate_id) || lanceDamage(seen.bastion) <= 0) continue; + const pl = await getPlanet(c, seen.id, true); + if (!pl || pl.stock[0] < 10) continue; + hazard = true; + pl.stock[0] -= 10; + const hit = applyDamage(p, lanceDamage(pl.bastion)); + events.push(`|14A Lance Battery on ${esc(pl.name)} fires!|07 -${hit.shieldLoss} shields, -${hit.fighterLoss} fighters.`); + await savePlanet(c, pl); + if (pl.owner_id) await tell(pl.owner_id, `|10The Lance on ${esc(pl.name)} fired on ${esc(p.handle)}${hit.destroyed ? ' and destroyed the ship!' : '.'}`, c); + if (hit.destroyed) { + await destroyPilot(c, p, { kind: 'hazard', what: `the Lance on ${esc(pl.name)}`, ownerId: pl.owner_id }, true); + return 'dead' as const; + } + } + + // Reaver ambush: they prey on ships weaker than them. + for (const r of await reaversInSector(c, sector, true)) { + hazard = true; + if (r.fighters <= p.fighters || Math.random() > 0.45) continue; + const sent = Math.ceil(r.fighters * 0.5); + const b = battle({ fighters: sent, shields: 0 }, { fighters: p.fighters, shields: p.shields }, Math.random); + r.fighters -= b.attackerLost; + p.fighters = b.defender.fighters; + p.shields = b.defender.shields; + events.push(`|12The Reaver "${esc(r.name)}" opens fire!|07 You lose ${b.defenderFightersLost} fighters and ${b.defenderShieldsLost} shields.`); + if (b.defenderBroken) { + await destroyPilot(c, p, { kind: 'reaver', reaver: r }, true); + await saveReaver(c, r); + return 'dead' as const; + } + await saveReaver(c, r); + } + await savePilot(c, p); + return 'ok' as const; + }); + + if (events.length) { + if (events.some((e) => e.includes('Reaver'))) await art(s, REAVER); + for (const e of events) { + await s.println(` ${e}`); + await beat(250); + } + } + if (result === 'dead') { + await art(s, EXPLOSION); + await s.println(' |12Your ship is destroyed!'); + await art(s, ESCAPE_POD); + await s.pause(); + return 'destroyed'; + } + + const blocked = await blockade(s, uid); + if (blocked === 'retreated') return 'retreated'; + + const me = (await getPilot(pool, uid))!; + for (const o of await pilotsInSector(pool, me.sector, uid)) { + tellIfOnline(o.user_id, `|11${esc(me.handle)}|07 warps into sector ${me.sector} in a ${ship(me.ship_type).name}.`); + } + return hazard || blocked === 'fought' ? 'hazard' : 'clear'; +} + +/** Hostile fighters still in the sector: pay the toll, fight, or back off. */ +async function blockade(s: Session, uid: number): Promise<'none' | 'paid' | 'fought' | 'retreated'> { + for (;;) { + const p = (await getPilot(pool, uid))!; + if (isConcord(p.sector)) return 'none'; + const d = await getDefense(pool, p.sector); + if (!d || d.fighters <= 0 || friendlyDefense(d, uid, p.syndicate_id)) return 'none'; + + const toll = Math.max(50, d.fighters * 3); + await s.println(` |12${commas(d.fighters)} fighters belonging to ${esc(d.owner_handle)} block your way.`); + const canRetreat = p.prev_sector !== null && p.prev_sector !== p.sector; + const opts = (d.mode === 'T' ? `|08[|15P|08]|07ay ${commas(toll)} cr toll ` : '') + '|08[|15A|08]|07ttack ' + (canRetreat ? '|08[|15R|08]|07etreat' : ''); + const k = await s.promptChoice(` ${opts}|07: `, (d.mode === 'T' ? 'P' : '') + 'A' + (canRetreat ? 'R' : '')); + await s.println(); + + if (k === 'P') { + const paid = await withTx(async (c) => { + const locked = await lockPilots(c, [uid, d.owner_id]); + const me = locked.get(uid)!; + const owner = locked.get(d.owner_id); + if (me.credits < toll) return false; + me.credits -= toll; + await savePilot(c, me); + if (owner) { + owner.credits += toll; + await savePilot(c, owner); + } + await tell(d.owner_id, `|10${esc(me.handle)} paid you a ${toll} cr toll in sector ${me.sector}.`, c); + return true; + }); + if (paid) { + await s.println(' |07The fighters peel away and let you pass.'); + return 'paid'; + } + await s.println(" |12You can't afford the toll."); + continue; + } + if (k === 'A') { + if (p.fighters <= 0) { + await s.println(' |12You have no fighters!'); + if (!canRetreat) return 'fought'; + continue; + } + await s.print(`|03 Commit how many fighters |08(Enter=all ${commas(p.fighters)})|03: `); + const n = (await readNumber(s, 1, p.fighters, p.fighters)) ?? p.fighters; + const cleared = await attackDefense(s, uid, n); + if (cleared) return 'fought'; + if (!canRetreat) return 'fought'; + await s.println(' |07Beaten back, you limp out the way you came.'); + } + // Retreat (chosen or forced after a failed attack). No turn cost. + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + if (me.prev_sector === null) return; + const back = me.prev_sector; + me.prev_sector = me.sector; + me.sector = back; + await savePilot(c, me); + }); + await s.println(' |07You retreat to the previous sector.'); + return 'retreated'; + } +} diff --git a/src/doors/starlane/screens/bazaar.ts b/src/doors/starlane/screens/bazaar.ts new file mode 100644 index 0000000..6f79c76 --- /dev/null +++ b/src/doors/starlane/screens/bazaar.ts @@ -0,0 +1,291 @@ +import type { Session } from '../../../session/Session'; +import { pool, withTx } from '../repo/q'; +import { getPilot, savePilot, freeHolds, usedHolds, type Pilot } from '../repo/players'; +import { allReavers } from '../repo/npcs'; +import { warpsFrom } from '../repo/world'; +import { addNews } from '../repo/news'; +import { SHIPS, ship, tradeInValue } from '../data/ships'; +import { COMMODITIES, portBuys } from '../engine/commodities'; +import { pick } from '../engine/rng'; +import { SL, PRICES, LIMITS } from '../config'; +import { BAZAAR } from '../art/scenes'; +import { header, padRight, padLeft, commas, esc, readNumber, art, confirm } from './ui'; + +const wanted = (p: Pilot) => p.alignment <= SL.wantedAlignment; +const tariff = (p: Pilot, price: number) => Math.ceil(wanted(p) ? price * (1 + SL.bazaarTariff) : price); + +export async function bazaar(s: Session, uid: number): Promise { + await art(s, BAZAAR); + for (;;) { + const p = (await getPilot(pool, uid))!; + await s.println(); + if (wanted(p)) await s.println(' |12Concord has your face on a poster. Merchants add a 25% "risk surcharge".'); + await s.println(`|08 Credits: |15${commas(p.credits)} |08Holds: |15${usedHolds(p)}|08/|15${p.holds}`); + const k = await s.promptChoice( + '|08 [|15S|08]|07hipyard |08[|15H|08]|07ardware |08[|15C|08]|07olonists |08[|15T|08]|07avern |08[|15L|08]|07eave|08: |07', + 'SHCTL\r', + ); + await s.println(); + if (k === 'L' || k === '\r') return; + if (k === 'S') await shipyard(s, uid); + if (k === 'H') await hardware(s, uid); + if (k === 'C') await colonists(s, uid); + if (k === 'T') await tavern(s, uid); + } +} + +async function shipyard(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + s.clear(); + await s.println(header('Shipyard', `|07Trade-in on your ${ship(p.ship_type).name}: |15${commas(tradeInValue(p.ship_type))}`)); + await s.println(`|03 ${padRight('#', 3)}${padRight('Class', 18)}${padLeft('Price', 9)}${padLeft('Holds', 9)}${padLeft('Fighters', 9)}${padLeft('Shields', 8)}${padLeft('Turns/jump', 11)} Seed`); + for (const sh of SHIPS) { + await s.println( + ` |15${padRight(String(sh.id), 3)}|11${padRight(sh.name, 18)}|14${padLeft(commas(tariff(p, sh.price)), 9)}|07${padLeft(`${sh.holds}-${sh.maxHolds}`, 9)}` + + `${padLeft(commas(sh.maxFighters), 9)}${padLeft(commas(sh.maxShields), 8)}${padLeft(String(sh.turnsPerWarp), 11)} ${sh.seeds ? '|10yes' : '|08no'}`, + ); + } + await s.println(); + await s.print('|03 Buy which class |08(Enter=cancel)|03: '); + const id = await readNumber(s, 1, SHIPS.length, null, 2); + if (id === null) return; + const sh = ship(id); + if (id === p.ship_type) return void (await s.println(' |07You already fly one of those.')); + const net = tariff(p, sh.price) - tradeInValue(p.ship_type); + await s.println(`|07 |11${sh.name}|07: ${sh.blurb}`); + await s.println(`|07 Net cost after trade-in: |15${commas(Math.max(0, net))}|07 cr.`); + if (net > p.credits) return void (await s.println(' |12You can\'t afford it.')); + if (!(await confirm(s, ' Sign the papers?', false))) return; + await s.print('|03 Name your new ship: '); + const name = (await s.readLine({ maxLen: 24 })).trim() || sh.name; + + const msg = await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const cost = tariff(me, sh.price) - tradeInValue(me.ship_type); + if (cost > me.credits) return 'You can\'t afford it.'; + me.credits -= Math.max(0, cost); + if (cost < 0) me.credits += -cost; + me.ship_type = sh.id; + me.ship_name = name; + me.holds = sh.holds; + me.fighters = Math.min(me.fighters, sh.maxFighters); + me.shields = Math.min(me.shields, sh.maxShields); + if (!sh.seeds && me.seeds) { + me.credits += Math.floor((me.seeds * PRICES.seed) / 2); + me.seeds = 0; + } + // Cargo that doesn't fit is left on the dock. + while (usedHolds(me) > me.holds) { + if (me.colonists > 0) me.colonists--; + else { + const i = me.cargo.findIndex((x) => x > 0); + me.cargo[i]--; + } + } + me.cargo = [...me.cargo]; + await savePilot(c, me); + if (sh.price >= 175000) await addNews(`|11${esc(me.handle)}|07 rolls out of the Terminus yards in a brand-new |15${sh.name}|07, the "${esc(name)}".`, c); + return null; + }); + await s.println(msg ? ` |12${msg}` : ` |10The ${esc(name)} is yours. Fly her well.`); +} + +interface Item { + label: string; + price: (p: Pilot) => number; + have: (p: Pilot) => number; + max: (p: Pilot) => number; + apply: (p: Pilot, n: number) => void; + /** Total cost for n (defaults to n * price). */ + total?: (p: Pilot, n: number) => number; +} + +function holdCost(p: Pilot, n: number): number { + const bought = p.holds - ship(p.ship_type).holds; + let sum = 0; + for (let i = 0; i < n; i++) sum += Math.round(PRICES.holdBase * (1 + (bought + i) / 10)); + return sum; +} + +const ITEMS: Item[] = [ + { label: 'Fighters', price: () => PRICES.fighter, have: (p) => p.fighters, max: (p) => ship(p.ship_type).maxFighters, apply: (p, n) => (p.fighters += n) }, + { label: 'Shield points', price: () => PRICES.shield, have: (p) => p.shields, max: (p) => ship(p.ship_type).maxShields, apply: (p, n) => (p.shields += n) }, + { label: 'Cargo holds', price: (p) => holdCost(p, 1), have: (p) => p.holds, max: (p) => ship(p.ship_type).maxHolds, apply: (p, n) => (p.holds += n), total: holdCost }, + { label: 'Proximity mines', price: () => PRICES.mine, have: (p) => p.mines, max: () => LIMITS.mines, apply: (p, n) => (p.mines += n) }, + { label: 'Tracer beacons', price: () => PRICES.tracer, have: (p) => p.tracers, max: () => LIMITS.tracers, apply: (p, n) => (p.tracers += n) }, + { label: 'Drone probes', price: () => PRICES.probe, have: (p) => p.probes, max: () => LIMITS.probes, apply: (p, n) => (p.probes += n) }, + { label: 'Mass scanner', price: () => PRICES.massScanner, have: (p) => (p.mass_scanner ? 1 : 0), max: () => 1, apply: (p) => (p.mass_scanner = true) }, + { label: 'Deep scanner', price: () => PRICES.deepScanner, have: (p) => (p.deep_scanner ? 1 : 0), max: () => 1, apply: (p) => (p.deep_scanner = true) }, + { label: 'Terraform Seed', price: () => PRICES.seed, have: (p) => p.seeds, max: (p) => (ship(p.ship_type).seeds ? LIMITS.seeds : 0), apply: (p, n) => (p.seeds += n) }, +]; + +async function hardware(s: Session, uid: number): Promise { + for (;;) { + const p = (await getPilot(pool, uid))!; + s.clear(); + await s.println(header('Hardware Emporium', `|07Credits: |15${commas(p.credits)}`)); + await s.println(`|03 ${padRight('#', 4)}${padRight('Item', 20)}${padLeft('Price', 10)}${padLeft('Have', 9)}${padLeft('Max', 9)}`); + for (let i = 0; i < ITEMS.length; i++) { + const it = ITEMS[i]; + await s.println(` |15${padRight(String(i + 1), 4)}|11${padRight(it.label, 20)}|14${padLeft(commas(tariff(p, it.price(p))), 10)}|07${padLeft(commas(it.have(p)), 9)}${padLeft(commas(it.max(p)), 9)}`); + } + await s.println('|08 Terraform Seeds need a seed-capable hull. Mines/tracers/probes are deployed from the sector prompt.'); + await s.print('|03 Buy which item |08(Enter=done)|03: '); + const i = await readNumber(s, 1, ITEMS.length, null, 2); + if (i === null) return; + const it = ITEMS[i - 1]; + const room = it.max(p) - it.have(p); + if (room <= 0) { + await s.println(' |07You can\'t carry any more of those.'); + await s.pause(); + continue; + } + const unit = tariff(p, it.price(p)); + let afford = Math.min(room, Math.floor(p.credits / Math.max(1, unit))); + while (afford > 0 && tariff(p, it.total ? it.total(p, afford) : unit * afford) > p.credits) afford--; + if (afford <= 0) { + await s.println(' |12You can\'t afford any.'); + await s.pause(); + continue; + } + let n = 1; + if (room > 1) { + await s.print(`|03 How many |08(max ${commas(afford)})|03: `); + n = (await readNumber(s, 0, afford, afford, 6)) ?? 0; + } + if (!n) continue; + const err = await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const cost = tariff(me, it.total ? it.total(me, n) : it.price(me) * n); + if (cost > me.credits) return 'You can\'t afford that.'; + if (it.have(me) + n > it.max(me)) return 'No room for that many.'; + me.credits -= cost; + it.apply(me, n); + await savePilot(c, me); + return null; + }); + if (err) { + await s.println(` |12${err}`); + await s.pause(); + } + } +} + +async function colonists(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + const price = tariff(p, PRICES.colonist); + const max = Math.min(freeHolds(p), Math.floor(p.credits / price)); + await s.println(' |07Settlers crowd the boarding ramps, clutching everything they own.'); + await s.println(` |07Passage costs |15${price}|07 cr a head. Each colonist takes a hold. You have |15${freeHolds(p)}|07 free.`); + if (max <= 0) return; + await s.print(`|03 Take how many |08[${max}]|03? `); + const n = (await readNumber(s, 0, max, max, 6)) ?? 0; + if (!n) return; + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const k = Math.min(n, freeHolds(me), Math.floor(me.credits / price)); + me.colonists += k; + me.credits -= k * price; + await savePilot(c, me); + }); + await s.println(` |10${n} colonists aboard. |07Find them a world.`); +} + +// ---- tavern ---------------------------------------------------------------- + +async function rumor(): Promise { + const roll = Math.random(); + if (roll < 0.35) { + // A matched pair: two adjacent ports that each buy what the other sells. + const { rows } = await pool.query<{ a: number; b: number; pa: string; pb: string }>( + `SELECT pa.sector AS a, pb.sector AS b, pa.pattern AS pa, pb.pattern AS pb + FROM sl_ports pa JOIN sl_sectors s ON s.id = pa.sector + JOIN sl_ports pb ON pb.sector = ANY(s.warps) + WHERE pa.sector < pb.sector ORDER BY random() LIMIT 40`, + ); + for (const r of rows) { + const fits = [0, 1, 2].filter((i) => portBuys(r.pa, i) !== portBuys(r.pb, i)).length; + if (fits >= 2 && warpsFrom(r.b).includes(r.a)) { + return `"Ports at |15${r.a}|03 and |15${r.b}|03 are next door and want each other's goods. Haulers get rich on routes like that."`; + } + } + } + if (roll < 0.6) { + const reavers = await allReavers(); + if (reavers.length) { + const r = pick(Math.random, reavers); + const near = pick(Math.random, warpsFrom(r.sector).concat(r.sector)); + return `"Saw the |12${esc(r.name)}|03 near sector |15${near}|03. Clan ${esc(r.clan)}. Stay clear unless you're loaded with fighters."`; + } + } + if (roll < 0.8) { + const c = Math.floor(Math.random() * COMMODITIES.length); + const { rows } = await pool.query<{ sector: number; name: string }>( + `SELECT sector, name FROM sl_ports WHERE substr(pattern, $1, 1) = 'B' ORDER BY stock[$1] / GREATEST(cap[$1], 1) DESC LIMIT 5`, + [c + 1], + ); + if (rows.length) { + const r = pick(Math.random, rows); + return `"${esc(r.name)} out in sector |15${r.sector}|03 is desperate for ${COMMODITIES[c].name}. Paying top credit."`; + } + } + const lines = [ + '"Landing on your own planet before you log off keeps your ship off the Reavers\' menu."', + '"Haggle, but don\'t insult a broker. They remember."', + '"A Bastion with a Lance Battery will ruin a raider\'s day. Keep it stocked with Ore."', + '"Toll fighters pay while you sleep. Put them on a busy lane."', + '"Couriers burn half the turns per jump. Great for scouting."', + '"The Concord can\'t protect you past sector ten, friend."', + ]; + return pick(Math.random, lines); +} + +async function tavern(s: Session, uid: number): Promise { + await s.println(' |06The Rusty Airlock |08- |07smoke, cheap synth-gin, and loose talk.'); + for (;;) { + const k = await s.promptChoice( + '|08 [|15B|08]|07uy a round (100 cr) |08[|15D|08]|07onate to Concord relief |08[|15W|08]|07anted board |08[|15L|08]|07eave|08: |07', + 'BDWL\r', + ); + await s.println(); + if (k === 'L' || k === '\r') return; + if (k === 'B') { + const ok = await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + if (me.credits < 100) return false; + me.credits -= 100; + await savePilot(c, me); + return true; + }); + if (!ok) await s.println(' |07The barkeep looks at your empty pockets and sighs.'); + else await s.println(` |03A grizzled hauler leans in: ${await rumor()}`); + } + if (k === 'D') { + const p = (await getPilot(pool, uid))!; + await s.println(' |07Every 200 credits buys a little forgiveness (+1 alignment).'); + await s.print(`|03 Donate how much |08(0-${commas(p.credits)})|03? `); + const n = (await readNumber(s, 0, p.credits, 0, 11)) ?? 0; + if (n >= 200) { + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const amt = Math.min(n, me.credits); + me.credits -= amt; + me.alignment += Math.floor(amt / 200); + await savePilot(c, me); + }); + await s.println(' |10The relief chaplain blesses your ship. You feel slightly less wanted.'); + } + } + if (k === 'W') { + const { rows } = await pool.query<{ handle: string; alignment: number; kills: number }>( + `SELECT u.handle, p.alignment, p.kills FROM sl_players p JOIN users u ON u.id = p.user_id + WHERE p.alignment <= $1 ORDER BY p.alignment LIMIT 10`, + [SL.wantedAlignment], + ); + await s.println(' |12W A N T E D |08- by order of the Concord'); + if (!rows.length) await s.println(' |07The board is empty. Suspiciously peaceful out there.'); + for (const r of rows) await s.println(` |11${padRight(esc(r.handle), 22)}|07alignment |12${r.alignment}|07, ${r.kills} kills`); + } + } +} + diff --git a/src/doors/starlane/screens/combat.ts b/src/doors/starlane/screens/combat.ts new file mode 100644 index 0000000..51f5e49 --- /dev/null +++ b/src/doors/starlane/screens/combat.ts @@ -0,0 +1,249 @@ +import type { Session } from '../../../session/Session'; +import { pool, withTx } from '../repo/q'; +import { getPilot, lockPilots, pilotsInSector, savePilot, type Pilot } from '../repo/players'; +import { reaversInSector, getReaver, saveReaver } from '../repo/npcs'; +import { getDefense, saveDefense, friendlyDefense } from '../repo/defenses'; +import { planetsInSector, getPlanet, savePlanet, ownsPlanet } from '../repo/planets'; +import { isConcord } from '../repo/world'; +import { addNews, tell } from '../repo/news'; +import { battle, alignmentShift } from '../engine/combat'; +import { lanceDamage } from '../data/planets'; +import { ship } from '../data/ships'; +import { destroyPilot } from '../actions/fate'; +import { EXPLOSION } from '../art/scenes'; +import { commas, esc, readNumber, pickFromList, art, beat } from './ui'; + +type Target = + | { kind: 'pilot'; id: number; label: string } + | { kind: 'reaver'; id: number; label: string } + | { kind: 'defense'; label: string } + | { kind: 'planet'; id: number; label: string }; + +async function sayBattle(s: Session, mine: number, lost: number, killed: number, shields: number): Promise { + await s.println(' |07Your fighters scream out of the launch bays...'); + await beat(); + await s.println(` |08» |07Committed |15${commas(mine)}|07, lost |12${commas(lost)}|07. Destroyed |10${commas(killed)}|07 fighters` + + (shields ? ` and |10${commas(shields)}|07 shield points.` : '.')); +} + +/** The "A" command: pick something in the sector to shoot. */ +export async function attackMenu(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + if (isConcord(p.sector)) { + await s.println(' |10Concord Patrol cutters lock weapons on you. |07"Not in Concord Space, pilot."'); + return; + } + if (p.fighters <= 0) { + await s.println(' |12You have no fighters to attack with.'); + return; + } + const targets: Target[] = []; + for (const o of await pilotsInSector(pool, p.sector, uid)) { + if (p.syndicate_id && o.syndicate_id === p.syndicate_id) continue; + targets.push({ kind: 'pilot', id: o.user_id, label: `|11${esc(o.handle)} |08in "${esc(o.ship_name)}" (${ship(o.ship_type).name})` }); + } + for (const r of await reaversInSector(pool, p.sector)) { + targets.push({ kind: 'reaver', id: r.id, label: `|12Reaver "${esc(r.name)}" |08(${ship(r.ship_type).name})` }); + } + const def = await getDefense(pool, p.sector); + if (def && def.fighters > 0 && !friendlyDefense(def, uid, p.syndicate_id)) { + targets.push({ kind: 'defense', label: `|15${commas(def.fighters)} |07fighters |08owned by ${esc(def.owner_handle)}` }); + } + for (const pl of await planetsInSector(pool, p.sector)) { + if (!ownsPlanet(pl, uid, p.syndicate_id)) targets.push({ kind: 'planet', id: pl.id, label: `|10Planet ${esc(pl.name)} |08(${pl.owner_handle ? esc(pl.owner_handle) : 'unclaimed'})` }); + } + if (!targets.length) { + await s.println(' |07Nothing here worth shooting at.'); + return; + } + await s.println(); + const i = await pickFromList(s, 'Targets in sector', targets.map((t) => t.label)); + if (i === null) return; + await s.print(`|03 Commit how many fighters |08(1-${commas(p.fighters)}, Enter=all)|03: `); + const n = await readNumber(s, 1, p.fighters, p.fighters); + if (!n) return; + const t = targets[i]; + if (t.kind === 'pilot') await attackPilot(s, uid, t.id, n); + else if (t.kind === 'reaver') await attackReaver(s, uid, t.id, n); + else if (t.kind === 'defense') await attackDefense(s, uid, n); + else await attackPlanet(s, uid, t.id, n); +} + +/** Spends the attack turn; returns false (and explains) if out of turns. */ +function spendTurn(p: Pilot): boolean { + if (p.turns_left <= 0) return false; + p.turns_left--; + return true; +} + +export async function attackPilot(s: Session, uid: number, targetId: number, n: number): Promise { + const out = await withTx(async (c) => { + const locked = await lockPilots(c, [uid, targetId]); + const me = locked.get(uid)!; + const them = locked.get(targetId); + if (!them || them.sector !== me.sector || them.landed_planet !== null) return { gone: true as const }; + if (!spendTurn(me)) return { noTurns: true as const }; + n = Math.min(n, me.fighters); + const b = battle({ fighters: n, shields: 0 }, { fighters: them.fighters, shields: them.shields }, Math.random); + me.fighters -= b.attackerLost; + them.fighters = b.defender.fighters; + them.shields = b.defender.shields; + let loot = 0; + if (b.defenderBroken) { + loot = await destroyPilot(c, them, { kind: 'pilot', pilot: me }, false); + } else { + me.alignment += Math.round(alignmentShift(them.alignment) / 5); + await savePilot(c, them); + await tell(them.user_id, `|12${esc(me.handle)} attacked you in sector ${me.sector}!|07 You lost ${b.defenderFightersLost} fighters and ${b.defenderShieldsLost} shields.`, c); + } + await savePilot(c, me); + return { b, loot, name: them.handle }; + }); + if ('gone' in out) return void (await s.println(' |07Your target is no longer here.')); + if ('noTurns' in out) return void (await s.println(' |12You are out of turns for today.')); + await sayBattle(s, n, out.b.attackerLost, out.b.defenderFightersLost, out.b.defenderShieldsLost); + if (out.b.defenderBroken) { + await art(s, EXPLOSION); + await s.println(` |14${esc(out.name)}'s ship breaks apart! |07You salvage |15${commas(out.loot)}|07 credits.`); + } else { + await s.println(` |07${esc(out.name)} survives the exchange.`); + } +} + +export async function attackReaver(s: Session, uid: number, reaverId: number, n: number): Promise { + const out = await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const r = await getReaver(c, reaverId, true); + if (!r || r.sector !== me.sector) return { gone: true as const }; + if (!spendTurn(me)) return { noTurns: true as const }; + n = Math.min(n, me.fighters); + const b = battle({ fighters: n, shields: 0 }, { fighters: r.fighters, shields: r.shields }, Math.random); + me.fighters -= b.attackerLost; + r.fighters = b.defender.fighters; + r.shields = b.defender.shields; + let bounty = 0; + if (b.defenderBroken) { + bounty = r.credits + 2000 + r.ship_type * 1500; + me.credits += bounty; + me.xp += 20 + r.ship_type * 10; + me.alignment += 10; + me.kills++; + await addNews(`|11${esc(me.handle)}|07 destroyed the Reaver |12"${esc(r.name)}"|07 of clan ${esc(r.clan)} in sector ${me.sector}.`, c); + } + await saveReaver(c, r); + await savePilot(c, me); + return { b, bounty, name: r.name }; + }); + if ('gone' in out) return void (await s.println(' |07The Reaver has slipped away.')); + if ('noTurns' in out) return void (await s.println(' |12You are out of turns for today.')); + await sayBattle(s, n, out.b.attackerLost, out.b.defenderFightersLost, out.b.defenderShieldsLost); + if (out.b.defenderBroken) { + await art(s, EXPLOSION); + await s.println(` |14"${esc(out.name)}" is scrap! |07Concord pays a bounty of |15${commas(out.bounty)}|07 credits.`); + } else { + await s.println(` |07"${esc(out.name)}" is still out there, and now it's angry.`); + } +} + +/** Returns true if the sector's hostile fighters were wiped out. */ +export async function attackDefense(s: Session, uid: number, n: number): Promise { + const out = await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const d = await getDefense(c, me.sector, true); + if (!d || d.fighters <= 0 || friendlyDefense(d, uid, me.syndicate_id)) return { gone: true as const }; + if (!spendTurn(me)) return { noTurns: true as const }; + n = Math.min(n, me.fighters); + const b = battle({ fighters: n, shields: 0 }, { fighters: d.fighters, shields: 0 }, Math.random); + me.fighters -= b.attackerLost; + d.fighters = b.defender.fighters; + let swept = 0; + if (b.defenderBroken && d.mines > 0) { + swept = Math.min(d.mines, b.attacker.fighters); + d.mines -= swept; + me.fighters -= swept; + } + if (b.defenderBroken) me.xp += 5; + await saveDefense(c, d); + await savePilot(c, me); + await tell(d.owner_id, `|12${esc(me.handle)} hit your fighters in sector ${me.sector}:|07 ${b.defenderFightersLost} lost${b.defenderBroken ? ' (all gone)' : ''}.`, c); + return { b, swept }; + }); + if ('gone' in out) return true; + if ('noTurns' in out) { + await s.println(' |12You are out of turns for today.'); + return false; + } + await sayBattle(s, n, out.b.attackerLost, out.b.defenderFightersLost, 0); + if (out.b.defenderBroken) { + await s.println(' |10The sector is clear.' + (out.swept ? ` |07Your fighters sweep |15${out.swept}|07 mines (and are lost doing it).` : '')); + } + return out.b.defenderBroken; +} + +export async function attackPlanet(s: Session, uid: number, planetId: number, n: number): Promise { + const out = await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const pl = await getPlanet(c, planetId, true); + if (!pl || pl.sector !== me.sector || ownsPlanet(pl, uid, me.syndicate_id)) return { gone: true as const }; + if (!spendTurn(me)) return { noTurns: true as const }; + n = Math.min(n, me.fighters); + let lance = 0; + if (lanceDamage(pl.bastion) > 0 && pl.stock[0] >= 10) { + pl.stock[0] -= 10; + lance = Math.min(n, lanceDamage(pl.bastion)); + n -= lance; + me.fighters -= lance; + } + const b = battle({ fighters: n, shields: 0 }, { fighters: Math.floor(pl.fighters), shields: Math.floor(pl.shields) }, Math.random, 1, 1.2); + me.fighters -= b.attackerLost; + pl.fighters = b.defender.fighters; + pl.shields = b.defender.shields; + const prevOwner = pl.owner_id; + if (b.defenderBroken) { + pl.owner_id = uid; + pl.syndicate_id = me.syndicate_id; + me.xp += 50 + pl.bastion * 25; + me.alignment -= prevOwner ? 20 : 0; + await addNews(`|11${esc(me.handle)}|07 seized the planet |10${esc(pl.name)}|07 in sector ${pl.sector}${pl.owner_handle ? ` from ${esc(pl.owner_handle)}` : ''}!`, c); + } + await savePlanet(c, pl); + await savePilot(c, me); + if (prevOwner && prevOwner !== uid) { + await tell(prevOwner, b.defenderBroken + ? `|12${esc(me.handle)} CAPTURED your planet ${esc(pl.name)} in sector ${pl.sector}!` + : `|12${esc(me.handle)} assaulted your planet ${esc(pl.name)} (sector ${pl.sector}) and was driven off.`, c); + } + return { b, lance, name: pl.name, sent: n + lance }; + }); + if ('gone' in out) return void (await s.println(' |07You cannot attack that planet now.')); + if ('noTurns' in out) return void (await s.println(' |12You are out of turns for today.')); + if (out.lance) await s.println(` |14The planet's Lance Battery fires! |12${commas(out.lance)}|07 of your fighters are vaporized.`); + await sayBattle(s, out.sent, out.b.attackerLost + out.lance, out.b.defenderFightersLost, out.b.defenderShieldsLost); + if (out.b.defenderBroken) await s.println(` |14The defenders of ${esc(out.name)} surrender. |10The planet is yours!`); + else await s.println(` |07${esc(out.name)} holds out.`); +} + +/** The "T" command: tag a ship with a tracer beacon. */ +export async function placeTracer(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + if (p.tracers <= 0) return void (await s.println(' |07You have no tracer beacons. The Bazaar sells them.')); + const others = await pilotsInSector(pool, p.sector, uid); + if (!others.length) return void (await s.println(' |07There are no other ships here.')); + const i = await pickFromList(s, 'Tag which ship?', others.map((o) => `|11${esc(o.handle)} |08"${esc(o.ship_name)}"`)); + if (i === null) return; + const target = others[i]; + const spotted = Math.random() < 0.2; + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + if (me.tracers <= 0) return; + me.tracers--; + await savePilot(c, me); + await c.query( + 'INSERT INTO sl_tracers (owner_id, target_id) VALUES ($1, $2) ON CONFLICT (owner_id, target_id) DO UPDATE SET placed_at = now()', + [uid, target.user_id], + ); + if (spotted) await tell(target.user_id, `|14Your hull sensors pick up a tracer beacon. Someone in sector ${me.sector} is following you.`, c); + }); + await s.println(` |10Tracer attached to ${esc(target.handle)}'s hull.${spotted ? ' |12(They may have noticed.)' : ''} |07Track them from the Computer.`); +} + diff --git a/src/doors/starlane/screens/computer.ts b/src/doors/starlane/screens/computer.ts new file mode 100644 index 0000000..da4b08e --- /dev/null +++ b/src/doors/starlane/screens/computer.ts @@ -0,0 +1,119 @@ +import type { Session } from '../../../session/Session'; +import { pool } from '../repo/q'; +import { getPilot, exploredSet } from '../repo/players'; +import { lanes, portsIn, getUniverse, regionOf } from '../repo/world'; +import { planetsFor } from '../repo/planets'; +import { defensesFor, MODE_NAMES } from '../repo/defenses'; +import { shortestPath, distances } from '../engine/pathfind'; +import { patternTag, COMMODITIES } from '../engine/commodities'; +import { planetType } from '../data/planets'; +import { ship } from '../data/ships'; +import { autopilot } from './move'; +import { header, padRight, padLeft, commas, esc, readNumber, confirm } from './ui'; + +export async function computer(s: Session, uid: number): Promise { + for (;;) { + await s.println(); + await s.println(header('Nav Computer')); + await s.println('|08 [|15P|08]|07lot course |08[|15R|08]|07eport: nearby ports |08[|15F|08]|07ind port type |08[|15A|08]|07ssets'); + await s.println('|08 [|15T|08]|07racers |08[|15E|08]|07xplored stats |08[|15Q|08]|07uit computer'); + const k = await s.promptChoice('|08 Computer|07: ', 'PRFATEQ\r'); + await s.println(); + if (k === 'Q' || k === '\r') return; + if (k === 'P') await plot(s, uid); + if (k === 'R') await portReport(s, uid); + if (k === 'F') await findPort(s, uid); + if (k === 'A') await assets(s, uid); + if (k === 'T') await tracers(s, uid); + if (k === 'E') await exploredStats(s, uid); + } +} + +async function plot(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + await s.print(`|03 Destination sector |08(1-${getUniverse().size})|03: `); + const to = await readNumber(s, 1, getUniverse().size, null, 5); + if (to === null) return; + await s.print('|03 Sectors to avoid |08(space separated, Enter=none)|03: '); + const avoid = new Set((await s.readLine({ maxLen: 40 })).split(/[\s,]+/).filter(Boolean).map(Number).filter((n) => n > 0)); + const path = shortestPath(lanes(), p.sector, to, avoid); + if (!path) return void (await s.println(' |12No route found.')); + const known = await exploredSet(uid); + await s.println(` |07Route: ${path.map((x) => (known.has(x) ? `|11${x}` : `|08(${x})`)).join(' |08> ')}`); + const cost = (path.length - 1) * ship(p.ship_type).turnsPerWarp; + await s.println(` |07${path.length - 1} jumps, |15${cost}|07 turns.`); + if (path.length > 1 && (await confirm(s, ' Engage autopilot?', false))) await autopilot(s, uid, path.slice(1)); +} + +/** Ports you've visited, nearest first. */ +async function portReport(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + const known = await exploredSet(uid); + const dist = distances(lanes(), p.sector); + const ports = (await portsIn([...known])).sort((a, b) => (dist.get(a.sector) ?? 999) - (dist.get(b.sector) ?? 999)).slice(0, 16); + if (!ports.length) return void (await s.println(' |07You have not visited any ports yet.')); + await s.println(`|03 ${padRight('Sector', 8)}${padRight('Jumps', 6)}${padRight('Port', 22)}${padRight('Type', 6)}` + COMMODITIES.map((c) => padLeft(c.name, 11)).join('')); + for (const pt of ports) { + await s.println( + ` |15${padRight(String(pt.sector), 8)}|07${padRight(String(dist.get(pt.sector) ?? '?'), 6)}|14${padRight(esc(pt.name).slice(0, 21), 22)}${padRight(patternTag(pt.pattern), 6)}` + + pt.stock.map((x, i) => (pt.pattern[i] === 'B' ? '|12' : '|10') + padLeft(commas(x), 11)).join(''), + ); + } + await s.println('|08 Red = units the port will buy, green = units for sale.'); +} + +/** Nearest explored port that buys (or sells) a given commodity. */ +async function findPort(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + await s.println(' |07Find a port that: |08[|151|08] buys Ore [|152|08] buys Biomass [|153|08] buys Circuitry'); + await s.println(' |08[|154|08] sells Ore [|155|08] sells Biomass [|156|08] sells Circuitry'); + const k = await s.promptChoice('|08 Choice|07: ', '123456\r'); + await s.println(); + if (k === '\r') return; + const n = Number(k) - 1; + const c = n % 3; + const want = n < 3 ? 'B' : 'S'; + const known = await exploredSet(uid); + const dist = distances(lanes(), p.sector); + const hits = (await portsIn([...known])).filter((pt) => pt.pattern[c] === want).sort((a, b) => (dist.get(a.sector) ?? 999) - (dist.get(b.sector) ?? 999)).slice(0, 8); + if (!hits.length) return void (await s.println(' |07None among the sectors you have explored.')); + for (const h of hits) await s.println(` |15${padRight(String(h.sector), 6)}|14${padRight(esc(h.name), 24)}|07${dist.get(h.sector) ?? '?'} jumps, ${commas(h.stock[c])} units`); +} + +async function assets(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + const planets = await planetsFor(uid, p.syndicate_id); + const defs = await defensesFor(uid, p.syndicate_id); + await s.println('|15 Planets'); + if (!planets.length) await s.println(' |08none'); + for (const pl of planets) { + await s.println( + ` |10${padRight(esc(pl.name), 18)}|07sector |15${padRight(String(pl.sector), 6)}|08${padRight(planetType(pl.type).name, 9)}|07B${pl.bastion}` + + ` |07col ${commas(pl.colonists)} ftr ${commas(pl.fighters)} ` + pl.stock.map((x) => commas(x)).join('/'), + ); + } + await s.println('|15 Sector defenses'); + if (!defs.length) await s.println(' |08none'); + for (const d of defs) { + await s.println(` |07sector |15${padRight(String(d.sector), 6)}|07${padRight(commas(d.fighters) + ' ftrs', 12)}|08${padRight(MODE_NAMES[d.mode], 10)}|07${d.mines} mines |08(${esc(d.owner_handle)})`); + } +} + +async function tracers(s: Session, uid: number): Promise { + const { rows } = await pool.query<{ handle: string; sector: number; landed_planet: number | null; placed_at: Date }>( + `SELECT u.handle, p.sector, p.landed_planet, t.placed_at FROM sl_tracers t + JOIN sl_players p ON p.user_id = t.target_id JOIN users u ON u.id = t.target_id + WHERE t.owner_id = $1 ORDER BY u.handle`, + [uid], + ); + if (!rows.length) return void (await s.println(' |07No active tracers. Tag ships with T at the sector prompt.')); + for (const r of rows) { + await s.println(` |11${padRight(esc(r.handle), 22)}|07sector |15${padRight(String(r.sector), 6)}|08${r.landed_planet ? '(landed on a planet)' : regionOf(r.sector)}`); + } +} + +async function exploredStats(s: Session, uid: number): Promise { + const known = await exploredSet(uid); + const size = getUniverse().size; + await s.println(` |07You have charted |15${commas(known.size)}|07 of |15${commas(size)}|07 sectors (${((known.size / size) * 100).toFixed(1)}%).`); +} diff --git a/src/doors/starlane/screens/deploy.ts b/src/doors/starlane/screens/deploy.ts new file mode 100644 index 0000000..36513cb --- /dev/null +++ b/src/doors/starlane/screens/deploy.ts @@ -0,0 +1,62 @@ +import type { Session } from '../../../session/Session'; +import { pool, withTx } from '../repo/q'; +import { getPilot, savePilot } from '../repo/players'; +import { getDefense, saveDefense, friendlyDefense, MODE_NAMES, type Defense, type DefenseMode } from '../repo/defenses'; +import { isConcord } from '../repo/world'; +import { ship } from '../data/ships'; +import { LIMITS } from '../config'; +import { commas, esc, readNumber } from './ui'; + +/** The "F" command: station fighters and mines in this sector, or take them back. */ +export async function deployCommand(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + if (isConcord(p.sector)) return void (await s.println(' |10Concord law forbids deployments in Concord Space.')); + const d = await getDefense(pool, p.sector); + if (d && !friendlyDefense(d, uid, p.syndicate_id)) { + return void (await s.println(` |12${esc(d.owner_handle)} already controls this sector. Clear their defenses first.`)); + } + const stack: Defense = d ?? { sector: p.sector, owner_id: uid, owner_handle: p.handle, syndicate_id: p.syndicate_id, fighters: 0, mode: 'D', mines: 0 }; + await s.println(` |07Sector: |15${commas(stack.fighters)}|07 fighters |08[${MODE_NAMES[stack.mode]}]|07, |15${stack.mines}|07 mines. Ship: |15${commas(p.fighters)}|07 fighters, |15${p.mines}|07 mines.`); + const k = await s.promptChoice('|08 [|15F|08]|07ighters |08[|15M|08]|07ines |08[|15Q|08]|07uit|08: |07', 'FMQ\r'); + await s.println(); + if (k === 'Q' || k === '\r') return; + + const maxShip = k === 'F' ? ship(p.ship_type).maxFighters : LIMITS.mines; + const inSector = k === 'F' ? stack.fighters : stack.mines; + const onShip = k === 'F' ? p.fighters : p.mines; + const pool2 = inSector + onShip; + const minLeave = Math.max(0, pool2 - maxShip); + await s.print(`|03 Leave how many ${k === 'F' ? 'fighters' : 'mines'} in the sector |08(${minLeave}-${pool2}, now ${inSector})|03: `); + const leave = await readNumber(s, minLeave, pool2, null, 7); + if (leave === null) return; + let mode: DefenseMode = stack.mode; + if (k === 'F' && leave > 0) { + const m = await s.promptChoice('|08 Mode: [|15D|08]|07efensive |08[|15T|08]|07oll |08[|15O|08]|07ffensive|08: |07', 'DTO'); + await s.println(); + mode = m as DefenseMode; + } + + const err = await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const cur = await getDefense(c, me.sector, true); + if (cur && !friendlyDefense(cur, uid, me.syndicate_id)) return 'Someone else took the sector!'; + const st: Defense = cur ?? { sector: me.sector, owner_id: uid, owner_handle: me.handle, syndicate_id: me.syndicate_id, fighters: 0, mode: 'D', mines: 0 }; + if (k === 'F') { + const total = st.fighters + me.fighters; + if (leave > total || total - leave > ship(me.ship_type).maxFighters) return 'Numbers changed; try again.'; + st.fighters = leave; + me.fighters = total - leave; + st.mode = mode; + } else { + const total = st.mines + me.mines; + if (leave > total || total - leave > LIMITS.mines) return 'Numbers changed; try again.'; + st.mines = leave; + me.mines = total - leave; + } + if (!cur) st.syndicate_id = me.syndicate_id; + await saveDefense(c, st); + await savePilot(c, me); + return null; + }); + await s.println(err ? ` |12${err}` : ' |10Deployment updated.'); +} diff --git a/src/doors/starlane/screens/help.ts b/src/doors/starlane/screens/help.ts new file mode 100644 index 0000000..336f420 --- /dev/null +++ b/src/doors/starlane/screens/help.ts @@ -0,0 +1,36 @@ +import type { Session } from '../../../session/Session'; +import { header } from './ui'; + +const PAGE1 = [ + ' |15M|07ove warp to a sector (adjacent, or plot a course and autopilot)', + ' |15P|07ort dock and trade (at Terminus: the Bazaar - ships, gear, tavern)', + ' |15C|07omputer plot courses, port reports, find ports, your assets, tracers', + ' |15S|07can mass scan (free) / deep scan (1 turn) the adjacent sectors', + ' |15E|07 probe fire a drone probe down a course to chart it', + ' |15L|07and land on a planet you own (or an unclaimed one)', + ' |15G|07 seed plant a Terraform Seed to create a planet', + ' |15F|07ighters station fighters/mines here (Defensive, Toll, Offensive)', + ' |15A|07ttack fight a ship, a Reaver, sector fighters or a planet (1 turn)', + ' |15T|07racer tag another ship so you can follow it', + ' |15I|07nfo |15R|07ankings |15N|07ews |15Y|07 syndicate |15D|07isplay sector |15Q|07uit', +]; + +const TIPS = [ + '|14 How to get rich', + ' |07Buy where a port |10sells|07, sell where a port |12buys|07. Two neighbouring ports that', + ' |07want each other\'s goods make a trade route you can run all day.', + ' |07Haggle: press Enter to take the quote, or counter. Push a broker too far', + ' |07and they throw you out. A sharp deal earns extra experience.', + ' |07Turns refill daily. Ports restock over time. Planets produce while you sleep.', + ' |07Logging off in open space leaves your ship exposed. Land on a planet first.', +]; + +export async function helpScreen(s: Session): Promise { + s.clear(); + await s.println(header('STARLANE Commands')); + for (const l of PAGE1) await s.println(l); + await s.println(); + for (const l of TIPS) await s.println(l); + await s.println(); + await s.pause(); +} diff --git a/src/doors/starlane/screens/info.ts b/src/doors/starlane/screens/info.ts new file mode 100644 index 0000000..c02d451 --- /dev/null +++ b/src/doors/starlane/screens/info.ts @@ -0,0 +1,90 @@ +import type { Session } from '../../../session/Session'; +import { pool } from '../repo/q'; +import { getPilot, allPilots, usedHolds, type Pilot } from '../repo/players'; +import { recentNews, takeMessages } from '../repo/news'; +import { syndicateNames, getSyndicate } from '../repo/syndicates'; +import { regionOf } from '../repo/world'; +import { ship } from '../data/ships'; +import { rankTitle, nextRankXp, alignmentLabel } from '../data/ranks'; +import { COMMODITIES } from '../engine/commodities'; +import { PRICES } from '../config'; +import { header, field, padRight, padLeft, commas, esc } from './ui'; + +export function netWorth(p: Pilot): number { + return p.credits + ship(p.ship_type).price + p.fighters * PRICES.fighter + p.shields * PRICES.shield; +} + +/** The "I" command. */ +export async function infoCommand(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + const sh = ship(p.ship_type); + const syn = await getSyndicate(pool, p.syndicate_id); + const next = nextRankXp(p.xp); + s.clear(); + await s.println(header(`${rankTitle(p.xp, p.alignment)} ${esc(p.handle)}`, `|07"${esc(p.ship_name)}"`)); + const rows = [ + field('Ship', `|11${sh.name} |08(${sh.turnsPerWarp} turn${sh.turnsPerWarp > 1 ? 's' : ''}/jump)`), + field('Sector', `|15${p.sector} |08${regionOf(p.sector)}`), + field('Turns', `|15${p.turns_left}|07 left today`), + field('Credits', `|15${commas(p.credits)}`), + field('Holds', `|15${usedHolds(p)}|07/|15${p.holds} |08(` + COMMODITIES.map((c, i) => `${c.name} ${p.cargo[i]}`).join(', ') + `, colonists ${p.colonists})`), + field('Fighters', `|15${commas(p.fighters)}|07/${commas(sh.maxFighters)}`), + field('Shields', `|15${commas(p.shields)}|07/${commas(sh.maxShields)}`), + field('Gear', `|07mines ${p.mines}, tracers ${p.tracers}, probes ${p.probes}, seeds ${p.seeds}` + + `${p.mass_scanner ? ', mass scanner' : ''}${p.deep_scanner ? ', deep scanner' : ''}`), + field('Experience', `|15${commas(p.xp)}${next ? ` |08(next rank at ${commas(next)})` : ''}`), + field('Alignment', `${alignmentLabel(p.alignment)} |08(${p.alignment})`), + field('Syndicate', syn ? `|05${esc(syn.name)}` : '|08none'), + field('Kills', `|15${p.kills}|07, ships lost today: ${p.deaths_today}`), + field('Net worth', `|14${commas(netWorth(p))}|07 cr`), + ]; + for (const r of rows) await s.println(r); + await s.println(); + await s.pause(); +} + +/** The "R" command. */ +export async function rankings(s: Session): Promise { + const pilots = (await allPilots()).sort((a, b) => netWorth(b) - netWorth(a)).slice(0, 18); + const syns = await syndicateNames(); + s.clear(); + await s.println(header('Top Pilots of the Drift')); + await s.println(`|03 ${padRight('#', 4)}${padRight('Pilot', 20)}${padRight('Rank', 20)}${padRight('Ship', 17)}${padLeft('Net worth', 13)}`); + for (let i = 0; i < pilots.length; i++) { + const p = pilots[i]; + const syn = p.syndicate_id ? syns.get(p.syndicate_id) : null; + await s.println( + ` |15${padRight(String(i + 1), 4)}|11${padRight(esc(p.handle).slice(0, 19), 20)}${p.alignment < 0 ? '|12' : '|10'}${padRight(rankTitle(p.xp, p.alignment), 20)}` + + `|07${padRight(ship(p.ship_type).name, 17)}|14${padLeft(commas(netWorth(p)), 13)}${syn ? ` |05${esc(syn).slice(0, 10)}` : ''}`, + ); + } + if (!pilots.length) await s.println(' |08No pilots yet.'); + await s.println(); + await s.pause(); +} + +/** The "N" command: The Drift Herald. */ +export async function newsCommand(s: Session, limit = 18): Promise { + const items = await recentNews(limit); + await s.println(); + await s.println(header('The Drift Herald', '|07all the news that fits')); + if (!items.length) await s.println(' |08Quiet out there. Too quiet.'); + for (const n of items.reverse()) { + const when = n.at.toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false }); + await s.println(` |08${padRight(when, 14)}|07${n.text}`); + } + await s.println(); +} + +/** Shows the "while you were away" log, if any. */ +export async function awayLog(s: Session, uid: number): Promise { + const msgs = await takeMessages(uid); + if (!msgs.length) return; + await s.println(header('While you were away')); + for (const m of msgs.slice(-18)) { + const when = m.at.toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false }); + await s.println(` |08${padRight(when, 14)}|07${m.text}`); + } + await s.println(); + await s.pause(); +} diff --git a/src/doors/starlane/screens/main.ts b/src/doors/starlane/screens/main.ts new file mode 100644 index 0000000..f63d097 --- /dev/null +++ b/src/doors/starlane/screens/main.ts @@ -0,0 +1,58 @@ +import type { Session } from '../../../session/Session'; +import { pool } from '../repo/q'; +import { getPilot, exploredSet } from '../repo/players'; +import { isSysop } from '../../../users/userRepo'; +import { drawSector } from './sectorView'; +import { moveCommand } from './move'; +import { portCommand } from './port'; +import { computer } from './computer'; +import { scanCommand, probeCommand } from './scan'; +import { deployCommand } from './deploy'; +import { attackMenu, placeTracer } from './combat'; +import { seedCommand, landCommand } from './planet'; +import { syndicateCommand } from './syndicate'; +import { infoCommand, rankings, newsCommand } from './info'; +import { helpScreen } from './help'; +import { sysopMenu } from './sysop'; + +/** The sector command loop. Returns when the pilot quits the game. */ +export async function commandLoop(s: Session, uid: number): Promise { + const sysop = !!s.user && isSysop(s.user); + let redraw = true; + for (;;) { + const p = await getPilot(pool, uid); + if (!p) { + await s.println(' |14The universe has been reborn while you were flying. Come back in to start anew.'); + await s.pause(); + return; + } + if (redraw) await drawSector(s, p, await exploredSet(uid)); + redraw = true; + const keys = 'MPCSELGFATIRNYDQ?' + (sysop ? 'Z' : ''); + const k = await s.promptChoice( + `|08[|15${p.sector}|08] |07Command |08(|15?|08=help, |15${p.turns_left}|08 turns)|07: `, + keys, + ); + await s.println(); + switch (k) { + case 'M': await moveCommand(s, uid); break; + case 'P': await portCommand(s, uid); break; + case 'C': await computer(s, uid); redraw = false; break; + case 'S': await scanCommand(s, uid); redraw = false; break; + case 'E': await probeCommand(s, uid); redraw = false; break; + case 'L': if (await landCommand(s, uid)) return; break; + case 'G': await seedCommand(s, uid); break; + case 'F': await deployCommand(s, uid); break; + case 'A': await attackMenu(s, uid); break; + case 'T': await placeTracer(s, uid); redraw = false; break; + case 'I': await infoCommand(s, uid); break; + case 'R': await rankings(s); break; + case 'N': await newsCommand(s); redraw = false; break; + case 'Y': await syndicateCommand(s, uid); break; + case 'Z': await sysopMenu(s); break; + case '?': await helpScreen(s); break; + case 'D': break; + case 'Q': return; + } + } +} diff --git a/src/doors/starlane/screens/move.ts b/src/doors/starlane/screens/move.ts new file mode 100644 index 0000000..90334bb --- /dev/null +++ b/src/doors/starlane/screens/move.ts @@ -0,0 +1,76 @@ +import type { Session } from '../../../session/Session'; +import { pool, withTx } from '../repo/q'; +import { getPilot, savePilot, markExplored, pilotsInSector } from '../repo/players'; +import { warpsFrom, lanes, getUniverse } from '../repo/world'; +import { tellIfOnline } from '../repo/news'; +import { shortestPath } from '../engine/pathfind'; +import { ship } from '../data/ships'; +import { arrive, type Arrival } from './arrival'; +import { readNumber, confirm, commas, esc, beat } from './ui'; + +/** One jump along a lane. Returns null if the jump couldn't be made. */ +export async function warp(s: Session, uid: number, to: number): Promise { + const res = await withTx(async (c) => { + const p = (await getPilot(c, uid, true))!; + const cost = ship(p.ship_type).turnsPerWarp; + if (!warpsFrom(p.sector).includes(to)) return { err: `There is no lane from ${p.sector} to ${to}.` }; + if (p.turns_left < cost) return { err: `Not enough turns (a jump costs ${cost}).` }; + const from = p.sector; + p.turns_left -= cost; + p.prev_sector = from; + p.sector = to; + p.landed_planet = null; + await savePilot(c, p); + await markExplored(c, uid, to); + return { from, handle: p.handle }; + }); + if ('err' in res) { + await s.println(` |12${res.err}`); + return null; + } + for (const o of await pilotsInSector(pool, res.from, uid)) { + tellIfOnline(o.user_id, `|11${esc(res.handle)}|07 warps out of sector ${res.from}.`); + } + await s.println(` |08» |07Warping to sector |15${to}|07...`); + await beat(200); + return arrive(s, uid); +} + +/** The "M" command: adjacent jump, or plot a course and fly it on autopilot. */ +export async function moveCommand(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + const max = getUniverse().size; + await s.print(`|03 Warp to sector |08(1-${max})|03: `); + const to = await readNumber(s, 1, max, null, 5); + if (to === null || to === p.sector) return; + + if (warpsFrom(p.sector).includes(to)) { + await warp(s, uid, to); + return; + } + + const path = shortestPath(lanes(), p.sector, to); + if (!path) { + await s.println(` |12No known route to sector ${to}.`); + return; + } + const jumps = path.length - 1; + const cost = jumps * ship(p.ship_type).turnsPerWarp; + await s.println(` |07Course plotted: |11${path.join(' |08> |11')}`); + await s.println(` |07${jumps} jumps, |15${commas(cost)}|07 turns |08(you have ${commas(p.turns_left)})`); + if (!(await confirm(s, ' Engage autopilot?', true))) return; + await autopilot(s, uid, path.slice(1)); +} + +/** Flies a path, stopping at the first sign of trouble. */ +export async function autopilot(s: Session, uid: number, path: number[]): Promise { + for (const step of path) { + const r = await warp(s, uid, step); + if (r === null) return; + if (r !== 'clear') { + await s.println(' |14Autopilot disengaged.'); + return; + } + } + await s.println(' |10Autopilot: arrived.'); +} diff --git a/src/doors/starlane/screens/planet.ts b/src/doors/starlane/screens/planet.ts new file mode 100644 index 0000000..31a7a3f --- /dev/null +++ b/src/doors/starlane/screens/planet.ts @@ -0,0 +1,317 @@ +import type { Session } from '../../../session/Session'; +import { pool, withTx } from '../repo/q'; +import { getPilot, savePilot, freeHolds } from '../repo/players'; +import { planetsInSector, getPlanet, savePlanet, createPlanet, ownsPlanet, planetsFor, type Planet } from '../repo/planets'; +import { isConcord } from '../repo/world'; +import { addNews } from '../repo/news'; +import { planetType, PLANET_TYPES, BASTION, planetStorage, planetShieldCap, lanceDamage } from '../data/planets'; +import { planetName } from '../data/names'; +import { nextBastion } from '../engine/planets'; +import { COMMODITIES } from '../engine/commodities'; +import { pick } from '../engine/rng'; +import { ship } from '../data/ships'; +import { SL } from '../config'; +import { planetArt } from '../art/scenes'; +import { header, field, padRight, commas, esc, readNumber, pickFromList, art, confirm } from './ui'; + +/** The "G" command: plant a Terraform Seed. */ +export async function seedCommand(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + if (p.seeds <= 0) return void (await s.println(' |07You have no Terraform Seed. The Bazaar sells them (seed-capable hulls only).')); + if (isConcord(p.sector)) return void (await s.println(' |10Concord Space is fully settled. Take it to the Drift.')); + const here = await planetsInSector(pool, p.sector); + if (here.length >= SL.maxPlanetsPerSector) return void (await s.println(' |07This sector is too crowded for another world.')); + if (!(await confirm(s, ' Fire the Terraform Seed into the void?', true))) return; + const type = pick(Math.random, PLANET_TYPES); + await s.print(`|03 Name your new world |08(Enter for a random name)|03: `); + const name = (await s.readLine({ maxLen: 24 })).trim() || planetName(Math.random); + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + if (me.seeds <= 0) return; + me.seeds--; + me.xp += 25; + await savePilot(c, me); + await createPlanet(c, me.sector, name, type.id, uid, me.syndicate_id); + await addNews(`|11${esc(me.handle)}|07 seeded a new ${type.name} world, |10${esc(name)}|07, out in the Drift.`, c); + }); + await art(s, planetArt(type.art)); + await s.println(` |10The seed blooms. |15${esc(name)}|10, a ${type.name} world, is born.`); + await s.println(' |07Land on it (|15L|07) to drop colonists and start production.'); +} + +/** + * The "L" command: land on a planet in the sector. Returns true if the pilot + * chose to leave the game while staying landed (safe from Reavers). + */ +export async function landCommand(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + const here = await planetsInSector(pool, p.sector); + if (!here.length) return (await s.println(' |07There are no planets here.'), false); + let pl = here[0]; + if (here.length > 1) { + const i = await pickFromList(s, 'Land where?', here.map((x) => `|10${esc(x.name)} |08(${x.owner_handle ? esc(x.owner_handle) : 'unclaimed'})`)); + if (i === null) return false; + pl = here[i]; + } + if (!ownsPlanet(pl, uid, p.syndicate_id) && pl.owner_id !== null) { + await s.println(` |12${esc(pl.name)}'s defense grid refuses your landing request. |07(Attack to take it.)`); + return false; + } + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + me.landed_planet = pl.id; + await savePilot(c, me); + const cur = await getPlanet(c, pl.id, true); + if (cur && cur.owner_id === null) { + cur.owner_id = uid; + cur.syndicate_id = me.syndicate_id; + await savePlanet(c, cur); + } + }); + let stay = false; + try { + stay = await planetMenu(s, uid, pl.id); + return stay; + } finally { + if (s.isOpen && !stay) { + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + if (me.landed_planet === pl.id) { + me.landed_planet = null; + await savePilot(c, me); + } + }); + } + } +} + +async function drawPlanet(s: Session, pl: Planet): Promise { + const t = planetType(pl.type); + s.clear(); + const pic = planetArt(t.art); + const info = [ + header(`${esc(pl.name)}`, `|07Sector |15${pl.sector}`), + field('Class', `|10${t.name} |08(max ${commas(t.maxColonists)} colonists)`), + field('Owner', `|11${pl.owner_handle ? esc(pl.owner_handle) : 'none'}`), + field('Colonists', `|15${commas(pl.colonists)}`), + field('Fighters', `|15${commas(pl.fighters)}`), + field('Shields', `|15${commas(pl.shields)} |08/ ${commas(planetShieldCap(pl.bastion))}`), + field('Vault', `|15${commas(pl.credits)} |07cr`), + field('Bastion', `|14${pl.bastion ? `Level ${pl.bastion} (${BASTION[pl.bastion - 1].name})` : 'none'}` + + (pl.bastion_done_at ? ` |08- building L${pl.bastion_target}, ready ${pl.bastion_done_at.toLocaleString('en-US', { weekday: 'short', hour: '2-digit', minute: '2-digit' })}` : '')), + ]; + for (const l of info) await s.println(l); + await s.println(`|03 ${padRight('Stock', 12)}` + COMMODITIES.map((c, i) => `${c.color}${padRight(c.name, 10)}|15${padRight(commas(pl.stock[i]), 9)}`).join('')); + await s.println(`|08 Storage cap ${commas(planetStorage(pl.bastion))} each. Production/hr: ` + + t.prod.map((x, i) => `${COMMODITIES[i].name} ${(x * (pl.colonists / 100) * (pl.bastion >= 5 ? 1.5 : 1)).toFixed(0)}`).join(', ') + + `, fighters ${(t.fighters * (pl.colonists / 100)).toFixed(0)}`); + for (const l of pic) await s.println(' ' + l); +} + +/** Returns true if the pilot exits the game while landed. */ +async function planetMenu(s: Session, uid: number, planetId: number): Promise { + for (;;) { + const pl = await getPlanet(pool, planetId); + const p = (await getPilot(pool, uid))!; + if (!pl || !ownsPlanet(pl, uid, p.syndicate_id)) return false; + await drawPlanet(s, pl); + const transporter = pl.bastion >= 4; + await s.println('|08 [E]xit logs you off while landed: your ship is safe from Reavers here.'); + const k = await s.promptChoice( + '|08 [|15C|08]|07argo |08[|15P|08]|07eople |08[|15F|08]|07ighters |08[|15V|08]|07ault |08[|15B|08]|07astion ' + + (transporter ? '|08[|15X|08]|07fer ' : '') + '|08[|15N|08]|07ame |08[|15E|08]|07xit |08[|15Q|08]|07uit|08: |07', + 'CPFVBNEQ\r' + (transporter ? 'X' : ''), + ); + await s.println(); + if (k === 'Q' || k === '\r') return false; + if (k === 'E') { + await s.println(' |10You bunk down planetside. Your ship stays landed and out of harm\'s way.'); + return true; + } + if (k === 'C') await moveCargo(s, uid, planetId); + if (k === 'P') await moveColonists(s, uid, planetId); + if (k === 'F') await moveFighters(s, uid, planetId); + if (k === 'V') await vault(s, uid, planetId); + if (k === 'B') await bastion(s, uid, planetId); + if (k === 'N') { + await s.print('|03 New name: '); + const n = (await s.readLine({ maxLen: 24 })).trim(); + if (n) await withTx(async (c) => { + const x = (await getPlanet(c, planetId, true))!; + x.name = n; + await savePlanet(c, x); + }); + } + if (k === 'X') { + if (await transport(s, uid, planetId)) return false; + } + } +} + +type Tx = Parameters[0]>[0]; + +/** Runs a planet+pilot mutation with both rows locked (pilot first). */ +async function onPlanet(uid: number, planetId: number, fn: (me: Awaited> & object, pl: Planet, c: Tx) => string | null | Promise) { + return withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const pl = (await getPlanet(c, planetId, true))!; + if (!ownsPlanet(pl, uid, me.syndicate_id) || me.landed_planet !== planetId) return 'You are not on that planet.'; + const err = await fn(me, pl, c); + if (err) return err; + me.cargo = [...me.cargo]; + pl.stock = [...pl.stock]; + await savePlanet(c, pl); + await savePilot(c, me); + return null; + }); +} + +async function moveCargo(s: Session, uid: number, planetId: number): Promise { + const i = await pickFromList(s, 'Which commodity?', COMMODITIES.map((c) => c.name)); + if (i === null) return; + const k = await s.promptChoice('|08 [|15T|08]|07ake from planet or |08[|15L|08]|07eave on planet|08: |07', 'TL\r'); + await s.println(); + if (k === '\r') return; + const p = (await getPilot(pool, uid))!; + const pl = (await getPlanet(pool, planetId))!; + const max = k === 'T' ? Math.min(Math.floor(pl.stock[i]), freeHolds(p)) : Math.min(p.cargo[i], Math.floor(planetStorage(pl.bastion) - pl.stock[i])); + if (max <= 0) return void (await s.println(' |07Nothing to move.')); + await s.print(`|03 How many |08[${max}]|03? `); + const n = (await readNumber(s, 0, max, max, 6)) ?? 0; + if (!n) return; + const err = await onPlanet(uid, planetId, (me, x) => { + if (k === 'T') { + if (Math.floor(x.stock[i]) < n || freeHolds(me) < n) return 'Not enough room or stock.'; + x.stock[i] -= n; + me.cargo[i] += n; + } else { + if (me.cargo[i] < n) return 'You do not have that much.'; + me.cargo[i] -= n; + x.stock[i] += n; + } + return null; + }); + if (err) await s.println(` |12${err}`); +} + +async function moveColonists(s: Session, uid: number, planetId: number): Promise { + const k = await s.promptChoice('|08 [|15D|08]|07rop colonists or |08[|15P|08]|07ick up|08: |07', 'DP\r'); + await s.println(); + if (k === '\r') return; + const p = (await getPilot(pool, uid))!; + const pl = (await getPlanet(pool, planetId))!; + const room = Math.floor(planetType(pl.type).maxColonists - pl.colonists); + const max = k === 'D' ? Math.min(p.colonists, room) : Math.min(Math.floor(pl.colonists), freeHolds(p)); + if (max <= 0) return void (await s.println(' |07No one to move (or no room).')); + await s.print(`|03 How many |08[${max}]|03? `); + const n = (await readNumber(s, 0, max, max, 6)) ?? 0; + if (!n) return; + const err = await onPlanet(uid, planetId, (me, x) => { + if (k === 'D') { + if (me.colonists < n) return 'Not that many aboard.'; + me.colonists -= n; + x.colonists += n; + } else { + if (Math.floor(x.colonists) < n || freeHolds(me) < n) return 'Not enough room.'; + x.colonists -= n; + me.colonists += n; + } + return null; + }); + if (err) await s.println(` |12${err}`); +} + +async function moveFighters(s: Session, uid: number, planetId: number): Promise { + const p = (await getPilot(pool, uid))!; + const pl = (await getPlanet(pool, planetId))!; + const total = p.fighters + Math.floor(pl.fighters); + const cap = ship(p.ship_type).maxFighters; + await s.print(`|03 Fighters to keep on the ship |08(${Math.max(0, total - 1_000_000)}-${Math.min(cap, total)}, now ${p.fighters})|03: `); + const keep = await readNumber(s, 0, Math.min(cap, total), null, 7); + if (keep === null) return; + const err = await onPlanet(uid, planetId, (me, x) => { + const t = me.fighters + x.fighters; + if (keep > Math.floor(t)) return 'Numbers changed.'; + x.fighters = t - keep; + me.fighters = keep; + return null; + }); + if (err) await s.println(` |12${err}`); +} + +async function vault(s: Session, uid: number, planetId: number): Promise { + const k = await s.promptChoice('|08 [|15D|08]|07eposit or |08[|15W|08]|07ithdraw|08: |07', 'DW\r'); + await s.println(); + if (k === '\r') return; + const p = (await getPilot(pool, uid))!; + const pl = (await getPlanet(pool, planetId))!; + const max = k === 'D' ? p.credits : pl.credits; + await s.print(`|03 Amount |08(0-${commas(max)})|03: `); + const n = (await readNumber(s, 0, max, 0, 11)) ?? 0; + if (!n) return; + const err = await onPlanet(uid, planetId, (me, x) => { + if (k === 'D') { + if (me.credits < n) return 'Not enough credits.'; + me.credits -= n; + x.credits += n; + } else { + if (x.credits < n) return 'Not enough in the vault.'; + x.credits -= n; + me.credits += n; + } + return null; + }); + if (err) await s.println(` |12${err}`); + else if (k === 'D' && pl.bastion < 1) await s.println(' |14Without a Bastion vault, Reavers can loot those credits.'); +} + +async function bastion(s: Session, uid: number, planetId: number): Promise { + const pl = (await getPlanet(pool, planetId))!; + await s.println(header('Bastion Works')); + for (const b of BASTION) { + const mark = pl.bastion >= b.level ? '|10■' : '|08□'; + await s.println(` ${mark} |15L${b.level} |14${padRight(b.name, 14)}|07${commas(b.credits)} cr + ${b.cost.map((x, i) => `${commas(x)} ${COMMODITIES[i].name}`).join(', ')}, ${b.hours}h`); + await s.println(` |08${b.perk}`); + } + if (pl.bastion_done_at) return void (await s.println(' |07Construction is already under way.')); + const next = nextBastion(pl.bastion); + if (!next) return void (await s.println(' |10This Bastion is complete.')); + await s.println(` |07Credits come from your ship; materials from the planet's stock.`); + if (!(await confirm(s, ` Begin Level ${next.level} (${next.name})?`, false))) return; + const err = await onPlanet(uid, planetId, (me, x) => { + if (x.bastion_done_at) return 'Already building.'; + if (me.credits < next.credits) return 'Not enough credits on your ship.'; + for (let i = 0; i < 3; i++) if (x.stock[i] < next.cost[i]) return `The planet needs ${commas(next.cost[i])} ${COMMODITIES[i].name}.`; + me.credits -= next.credits; + for (let i = 0; i < 3; i++) x.stock[i] -= next.cost[i]; + x.bastion_target = next.level; + x.bastion_done_at = new Date(Date.now() + next.hours * 3_600_000); + me.xp += 10 * next.level; + return null; + }); + await s.println(err ? ` |12${err}` : ` |10Crews break ground. Level ${next.level} will be ready in ${next.hours} hours.`); + if (!err && lanceDamage(next.level) > 0) await s.println(' |08Remember: the Lance burns Ore. Keep some in stock.'); +} + +/** Beams the ship to another planet you own. Returns true if you left. */ +async function transport(s: Session, uid: number, fromId: number): Promise { + const p = (await getPilot(pool, uid))!; + const dests = (await planetsFor(uid, p.syndicate_id)).filter((x) => x.id !== fromId); + if (!dests.length) return (await s.println(' |07You have no other planets.'), false); + const i = await pickFromList(s, 'Beam to', dests.map((x) => `|10${esc(x.name)} |08sector ${x.sector}`)); + if (i === null) return false; + const dest = dests[i]; + const err = await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + if (me.turns_left < 3) return 'Transport takes 3 turns.'; + me.turns_left -= 3; + me.prev_sector = me.sector; + me.sector = dest.sector; + me.landed_planet = null; + await savePilot(c, me); + return null; + }); + if (err) return (await s.println(` |12${err}`), false); + await s.println(` |11Shimmer... |07You materialize above |10${esc(dest.name)}|07 in sector |15${dest.sector}|07.`); + return true; +} diff --git a/src/doors/starlane/screens/port.ts b/src/doors/starlane/screens/port.ts new file mode 100644 index 0000000..cf7b786 --- /dev/null +++ b/src/doors/starlane/screens/port.ts @@ -0,0 +1,195 @@ +import type { Session } from '../../../session/Session'; +import { pool, withTx } from '../repo/q'; +import { getPilot, savePilot, freeHolds, type Pilot } from '../repo/players'; +import { getPort, savePort } from '../repo/world'; +import { COMMODITIES, portBuys } from '../engine/commodities'; +import { unitPrice, quoteTotal, ratio, type PortState } from '../engine/pricing'; +import { startHaggle, makeOffer, haggleXp, type Side } from '../engine/haggle'; +import { pick } from '../engine/rng'; +import { DOCKING } from '../art/scenes'; +import { SL } from '../config'; +import { bazaar } from './bazaar'; +import { header, padRight, padLeft, commas, esc, readNumber, art, beat } from './ui'; + +const ACCEPT = ['"Pleasure doing business."', '"Deal. Don\'t spend it all in one sector."', '"Fine, fine. Load it up."', '"You drive a hard bargain, pilot."']; +const COUNTER = ['"Hah! How about', '"You\'re joking. I could do', '"My kids have to eat. Best I can do is', '"Let\'s be serious.']; +const REFUSE = ['"Get out of my port, you thief!"', '"We\'re done talking."', '"Come back when you\'re serious."']; +const SHREWD = ['|10(A shrewd deal!)', '|10(The broker winces. Nice haggling.)']; + +async function drawPort(s: Session, port: PortState, p: Pilot): Promise { + await s.println(header(`Docked at ${esc(port.name)}`, `|07Sector |15${port.sector}`)); + await s.println(`|03 ${padRight('Commodity', 13)}${padRight('Trading', 10)}${padLeft('Amount', 8)}${padLeft('Price', 9)}${padLeft('Your holds', 13)}`); + for (let i = 0; i < COMMODITIES.length; i++) { + const c = COMMODITIES[i]; + const buys = portBuys(port.pattern, i); + await s.println( + ` ${padRight(c.color + c.name, 13)}${padRight(buys ? '|12Buying' : '|10Selling', 10)}|15${padLeft(commas(port.stock[i]), 8)}` + + `|14${padLeft(commas(Math.round(unitPrice(port, i))), 9)}|07${padLeft(commas(p.cargo[i]), 13)}`, + ); + } + await s.println(`|08 Free holds: |15${freeHolds(p)}|08 of |15${p.holds} |08Credits: |15${commas(p.credits)}`); + await s.println(); +} + +/** + * Interactive haggle. Returns the agreed total and deal quality, or null if + * the port threw you out. + */ +async function haggle(s: Session, side: Side, quote: number, stockRatio: number): Promise<{ price: number; quality: number } | null> { + const h = startHaggle(side, quote, stockRatio, Math.random); + for (;;) { + await s.print(side === 'sell' ? `|07 We'll pay |15${commas(h.quote)}|07 cr. Your price? ` : `|07 We want |15${commas(h.quote)}|07 cr. Your offer? `); + const offer = await readNumber(s, 1, 2_000_000_000, h.quote, 11); + const r = makeOffer(h, offer ?? h.quote); + if (r.kind === 'accept') { + await s.println(` |03${pick(Math.random, ACCEPT)} ${r.quality >= 0.9 ? pick(Math.random, SHREWD) : ''}`); + return { price: r.price, quality: r.quality }; + } + if (r.kind === 'counter') { + await s.println(` |03${pick(Math.random, COUNTER)} |15${commas(r.quote)}|03?"`); + continue; + } + await s.println(` |12${pick(Math.random, REFUSE)}`); + return null; + } +} + +/** The "P" command. At Terminus this is the Bazaar. */ +export async function portCommand(s: Session, uid: number): Promise { + const p0 = (await getPilot(pool, uid))!; + if (p0.sector === SL.terminus) return bazaar(s, uid); + const port0 = await getPort(pool, p0.sector); + if (!port0) return void (await s.println(' |07There is no port in this sector.')); + if (p0.turns_left < 1) return void (await s.println(' |12Docking takes a turn, and you have none left today.')); + + await withTx(async (c) => { + const p = (await getPilot(c, uid, true))!; + p.turns_left--; + await savePilot(c, p); + }); + await art(s, DOCKING); + await beat(); + + const refused = new Set(); + for (;;) { + const p = (await getPilot(pool, uid))!; + const port = (await getPort(pool, p.sector))!; + await drawPort(s, port, p); + const k = await s.promptChoice('|08 [|15T|08]|07rade |08[|15S|08]|07muggle |08[|15L|08]|07eave port|08: |07', 'TSL\r'); + await s.println(); + if (k === 'L' || k === '\r') return; + if (k === 'S') { + await smuggle(s, uid); + return; + } + await tradeRound(s, uid, refused); + } +} + +async function tradeRound(s: Session, uid: number, refused: Set): Promise { + // Sell first (frees holds), then buy. + for (const phase of ['sell', 'buy'] as const) { + for (let i = 0; i < COMMODITIES.length; i++) { + if (refused.has(i)) continue; + const p = (await getPilot(pool, uid))!; + const port = (await getPort(pool, p.sector))!; + const name = COMMODITIES[i].name; + const buys = portBuys(port.pattern, i); + if (phase === 'sell' && (!buys || p.cargo[i] <= 0)) continue; + if (phase === 'buy' && buys) continue; + + const avail = Math.floor(port.stock[i]); + let max: number; + if (phase === 'sell') { + if (avail <= 0) { + await s.println(` |07The port isn't buying ${name} right now.`); + continue; + } + max = Math.min(p.cargo[i], avail); + await s.print(`|07 We'll buy up to |15${commas(avail)}|07 ${name}. You have |15${p.cargo[i]}|07. Sell how many |08[${max}]|07? `); + } else { + const afford = Math.floor(p.credits / Math.max(1, unitPrice(port, i))); + max = Math.min(avail, freeHolds(p), afford); + if (max <= 0) continue; + await s.print(`|07 We have |15${commas(avail)}|07 ${name} for sale. Buy how many |08[${max}]|07? `); + } + const qty = await readNumber(s, 0, max, max, 6); + if (!qty) continue; + + const deal = await haggle(s, phase, quoteTotal(port, i, qty), ratio(port, i)); + if (!deal) { + refused.add(i); + continue; + } + const ok = await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const pt = (await getPort(c, me.sector, true))!; + if (Math.floor(pt.stock[i]) < qty) return 'The port has run short.'; + if (phase === 'sell') { + if (me.cargo[i] < qty) return 'You no longer have that much.'; + me.cargo[i] -= qty; + me.credits += deal.price; + } else { + if (me.credits < deal.price) return "You can't cover that."; + if (freeHolds(me) < qty) return 'Not enough free holds.'; + me.cargo[i] += qty; + me.credits -= deal.price; + } + pt.stock[i] -= qty; + me.cargo = [...me.cargo]; + me.xp += haggleXp(deal.quality); + await savePort(c, pt); + await savePilot(c, me); + return null; + }); + if (ok) await s.println(` |12${ok}`); + else await s.println(` |08» |07${phase === 'sell' ? 'Sold' : 'Bought'} |15${qty}|07 ${name} for |15${commas(deal.price)}|07 cr.`); + } + } + await s.println(); +} + +/** Outlaw option: grab cargo off the docks and run. */ +async function smuggle(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + const port = (await getPort(pool, p.sector))!; + const sold = COMMODITIES.map((_, i) => i).filter((i) => !portBuys(port.pattern, i)); + if (!sold.length) return void (await s.println(' |07This port has nothing on its docks worth stealing.')); + const i = sold.reduce((best, x) => (COMMODITIES[x].base > COMMODITIES[best].base ? x : best), sold[0]); + const max = Math.min(freeHolds(p), Math.floor(port.stock[i])); + if (max <= 0) return void (await s.println(' |07No room in your holds.')); + await s.print(`|12 Lift how many ${COMMODITIES[i].name} off the docks |08[${max}]|12? `); + const qty = await readNumber(s, 0, max, max, 5); + if (!qty) return; + + const odds = Math.max(0.2, Math.min(0.85, 0.7 - qty / (p.holds * 3) + Math.min(0.15, p.xp / 20000))); + const caught = Math.random() > odds; + const out = await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const pt = (await getPort(c, me.sector, true))!; + me.alignment -= caught ? 15 : 5; + if (caught) { + const fine = Math.min(me.credits, qty * COMMODITIES[i].base * 3); + const lostF = Math.floor(me.fighters * 0.3); + me.credits -= fine; + me.fighters -= lostF; + await savePilot(c, me); + return { fine, lostF }; + } + const q = Math.min(qty, Math.floor(pt.stock[i]), freeHolds(me)); + me.cargo[i] += q; + me.cargo = [...me.cargo]; + me.xp += Math.ceil(q / 10); + pt.stock[i] -= q; + await savePort(c, pt); + await savePilot(c, me); + return { got: q }; + }); + await beat(500); + if ('got' in out) { + await s.println(` |10You slip away with |15${out.got}|10 ${COMMODITIES[i].name}. Nobody saw a thing.`); + } else { + await s.println(` |12Port security catches you red-handed!|07 Fined |15${commas(out.fine)}|07 cr; their guns take out |12${out.lostF}|07 fighters.`); + } + await s.println(' |08You are escorted off the station.'); +} diff --git a/src/doors/starlane/screens/scan.ts b/src/doors/starlane/screens/scan.ts new file mode 100644 index 0000000..eb48906 --- /dev/null +++ b/src/doors/starlane/screens/scan.ts @@ -0,0 +1,97 @@ +import type { Session } from '../../../session/Session'; +import { pool, withTx } from '../repo/q'; +import { getPilot, savePilot, markExplored, pilotsInSector } from '../repo/players'; +import { warpsFrom, getPort, lanes, getUniverse, regionOf } from '../repo/world'; +import { getDefense, friendlyDefense } from '../repo/defenses'; +import { planetsInSector } from '../repo/planets'; +import { reaversInSector } from '../repo/npcs'; +import { shortestPath } from '../engine/pathfind'; +import { patternTag } from '../engine/commodities'; +import { SL } from '../config'; +import { padRight, commas, esc, readNumber } from './ui'; + +async function contents(sector: number) { + const [port, pilots, def, planets, reavers] = await Promise.all([ + getPort(pool, sector), + pilotsInSector(pool, sector), + getDefense(pool, sector), + planetsInSector(pool, sector), + reaversInSector(pool, sector), + ]); + return { port, pilots, def, planets, reavers }; +} + +/** The "S" command. Mass scan is free; deep scan costs a turn. */ +export async function scanCommand(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + if (!p.mass_scanner && !p.deep_scanner) return void (await s.println(' |07You have no scanners. The Bazaar sells them.')); + let deep = false; + if (p.deep_scanner) { + const k = await s.promptChoice('|08 [|15M|08]|07ass scan or |08[|15D|08]|07eep scan (1 turn)|08: |07', 'MD\r'); + await s.println(); + if (k === '\r') return; + deep = k === 'D'; + } + if (deep) { + const ok = await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + if (me.turns_left < 1) return false; + me.turns_left--; + await savePilot(c, me); + return true; + }); + if (!ok) return void (await s.println(' |12No turns left.')); + } + await s.println(`|03 ${deep ? 'Deep' : 'Mass'} scan from sector ${p.sector}`); + for (const w of warpsFrom(p.sector)) { + const c = await contents(w); + if (!deep) { + const density = (c.port ? 100 : 0) + c.pilots.length * 40 + c.reavers.length * 60 + c.planets.length * 200 + + Math.round((c.def?.fighters ?? 0) / 5) + (c.def?.mines ?? 0) * 3; + const warn = c.def && !friendlyDefense(c.def, uid, p.syndicate_id) ? ' |12! hostile defenses' : ''; + await s.println(` |15${padRight(String(w), 6)}|07density |14${padRight(commas(density), 8)}|08${padRight(String(warpsFrom(w).length) + ' lanes', 9)}${warn}`); + continue; + } + await markExplored(pool, uid, w); + const bits: string[] = []; + if (w === SL.terminus) bits.push('|14Bazaar'); + if (c.port) bits.push(`|14${esc(c.port.name)} ${patternTag(c.port.pattern)}`); + for (const pl of c.planets) bits.push(`|10planet ${esc(pl.name)}`); + for (const o of c.pilots) bits.push(`|11${esc(o.handle)}`); + for (const r of c.reavers) bits.push(`|12Reaver ${esc(r.name)}`); + if (c.def) bits.push(`${friendlyDefense(c.def, uid, p.syndicate_id) ? '|10' : '|12'}${commas(c.def.fighters)}f/${c.def.mines}m`); + await s.println(` |15${padRight(String(w), 6)}${bits.length ? bits.join(' |08· ') : '|08empty'}`); + } +} + +/** The "E" command: fire a drone probe along a course; it charts each sector it passes. */ +export async function probeCommand(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + if (p.probes <= 0) return void (await s.println(' |07No drone probes aboard.')); + await s.print(`|03 Probe target sector |08(1-${getUniverse().size})|03: `); + const to = await readNumber(s, 1, getUniverse().size, null, 5); + if (to === null || to === p.sector) return; + const path = shortestPath(lanes(), p.sector, to); + if (!path) return void (await s.println(' |12No route.')); + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + me.probes--; + await savePilot(c, me); + }); + await s.println(' |07Probe away...'); + for (const sec of path.slice(1)) { + await markExplored(pool, uid, sec); + const c = await contents(sec); + const bits: string[] = []; + if (c.port) bits.push(`|14${esc(c.port.name)} ${patternTag(c.port.pattern)}`); + if (c.planets.length) bits.push(`|10${c.planets.length} planet${c.planets.length > 1 ? 's' : ''}`); + if (c.pilots.length) bits.push(`|11${c.pilots.map((o) => esc(o.handle)).join(', ')}`); + if (c.reavers.length) bits.push(`|12${c.reavers.length} Reaver${c.reavers.length > 1 ? 's' : ''}`); + await s.println(` |15${padRight(String(sec), 6)}|08${padRight(regionOf(sec), 22)}${bits.join(' |08· ')}`); + if (c.def && c.def.fighters > 0 && !friendlyDefense(c.def, uid, p.syndicate_id)) { + await s.println(` |12Probe destroyed by ${commas(c.def.fighters)} fighters in sector ${sec}.`); + return; + } + } + await s.println(' |10Probe reached its target and burned out.'); +} diff --git a/src/doors/starlane/screens/sectorView.ts b/src/doors/starlane/screens/sectorView.ts new file mode 100644 index 0000000..f31a3bc --- /dev/null +++ b/src/doors/starlane/screens/sectorView.ts @@ -0,0 +1,69 @@ +import type { Session } from '../../../session/Session'; +import { pool } from '../repo/q'; +import { header, field, esc, commas } from './ui'; +import type { Pilot } from '../repo/players'; +import { pilotsInSector } from '../repo/players'; +import { regionOf, warpsFrom, getPort, isConcord } from '../repo/world'; +import { planetsInSector } from '../repo/planets'; +import { getDefense, MODE_NAMES, friendlyDefense } from '../repo/defenses'; +import { reaversInSector } from '../repo/npcs'; +import { syndicateNames } from '../repo/syndicates'; +import { describePattern, patternTag } from '../engine/commodities'; +import { ship } from '../data/ships'; +import { planetType } from '../data/planets'; +import { SL } from '../config'; + +/** Draws the "you are here" panel for the pilot's current sector. */ +export async function drawSector(s: Session, p: Pilot, explored: Set): Promise { + const sec = p.sector; + const [port, planets, ships, def, reavers, syns] = await Promise.all([ + getPort(pool, sec), + planetsInSector(pool, sec), + pilotsInSector(pool, sec, p.user_id), + getDefense(pool, sec), + reaversInSector(pool, sec), + syndicateNames(), + ]); + const synTag = (id: number | null) => (id && syns.get(id) ? ` |05<${esc(syns.get(id)!)}>` : ''); + + await s.println(); + await s.println(header(`Sector ${sec}`, `|03${regionOf(sec)}${isConcord(sec) ? ' |10(safe)' : ''}`)); + + if (sec === SL.terminus) { + await s.println(field('Port', '|14The Bazaar of Terminus |08(ships, hardware, colonists, tavern)')); + } else if (port) { + await s.println(field('Port', `|14${esc(port.name)} |08(${patternTag(port.pattern)}|08) ${describePattern(port.pattern)}`)); + } + + for (const pl of planets) { + const owner = pl.owner_handle ? `|07${esc(pl.owner_handle)}` : '|08unclaimed'; + const bast = pl.bastion ? `, Bastion ${pl.bastion}` : ''; + await s.println(field('Planet', `|10${esc(pl.name)} |08(${planetType(pl.type).name}${bast}) |08- ${owner}${synTag(pl.syndicate_id)}`)); + } + + const MAX_SHIPS = 5; + for (const o of ships.slice(0, MAX_SHIPS)) { + await s.println( + field('Ship', `|11${esc(o.handle)} |08in |07"${esc(o.ship_name)}" |08(${ship(o.ship_type).name}, ${commas(o.fighters)} ftrs)${synTag(o.syndicate_id)}`), + ); + } + + if (ships.length > MAX_SHIPS) await s.println(field('', `|08...and ${ships.length - MAX_SHIPS} more ships`)); + for (const r of reavers.slice(0, 3)) { + await s.println(field('Reaver', `|12"${esc(r.name)}" |08of clan |04${esc(r.clan)} |08(${ship(r.ship_type).name}, ~${commas(Math.round(r.fighters / 10) * 10)} ftrs)`)); + } + + if (def) { + const mine = friendlyDefense(def, p.user_id, p.syndicate_id); + const parts: string[] = []; + if (def.fighters) parts.push(`|15${commas(def.fighters)} |07fighters |08[${MODE_NAMES[def.mode]}]`); + if (def.mines) parts.push(`|15${commas(def.mines)} |07mines`); + await s.println(field('Defenses', `${parts.join(' |08+ ')} |08- ${mine ? '|10' : '|12'}${esc(def.owner_handle)}${synTag(def.syndicate_id)}`)); + } + + const lanes = warpsFrom(sec) + .map((w) => (explored.has(w) ? `|11${w}` : `|08(${w})`)) + .join(' |08- '); + await s.println(field('Lanes out', lanes)); + await s.println(); +} diff --git a/src/doors/starlane/screens/syndicate.ts b/src/doors/starlane/screens/syndicate.ts new file mode 100644 index 0000000..ab6d6c6 --- /dev/null +++ b/src/doors/starlane/screens/syndicate.ts @@ -0,0 +1,158 @@ +import type { Session } from '../../../session/Session'; +import { pool, withTx } from '../repo/q'; +import { getPilot, savePilot, findPilotByHandle } from '../repo/players'; +import { getSyndicate, members, invitesFor } from '../repo/syndicates'; +import { addNews, tell } from '../repo/news'; +import { SL } from '../config'; +import { header, padRight, commas, esc, readNumber, pickFromList, confirm } from './ui'; + +/** The "Y" command: player corporations. */ +export async function syndicateCommand(s: Session, uid: number): Promise { + for (;;) { + const p = (await getPilot(pool, uid))!; + const syn = await getSyndicate(pool, p.syndicate_id); + await s.println(); + if (!syn) { + const inv = await invitesFor(uid); + await s.println(header('Syndicates', '|07You fly alone')); + if (inv.length) await s.println(` |14You have ${inv.length} invitation${inv.length > 1 ? 's' : ''}: |07${inv.map((x) => esc(x.name)).join(', ')}`); + const k = await s.promptChoice('|08 [|15F|08]|07ound a syndicate (10,000 cr) |08[|15J|08]|07oin by invitation |08[|15Q|08]|07uit|08: |07', 'FJQ\r'); + await s.println(); + if (k === 'Q' || k === '\r') return; + if (k === 'F') await found(s, uid); + if (k === 'J') await join(s, uid); + continue; + } + + const leader = syn.leader_id === uid; + const list = await members(syn.id); + await s.println(header(`Syndicate: ${esc(syn.name)}`, `|07Treasury |15${commas(syn.treasury)}|07 cr`)); + if (syn.memo) await s.println(` |14Memo: |07${esc(syn.memo)}`); + for (const m of list) { + await s.println(` ${m.user_id === syn.leader_id ? '|14*' : ' '} |11${padRight(esc(m.handle), 22)}|07sector |15${padRight(String(m.sector), 6)}|07xp ${commas(m.xp)}`); + } + await s.println('|08 Members share planets and sector defenses. Members never attack each other.'); + const opts = '|08 [|15D|08]|07eposit ' + (leader ? '|08[|15W|08]|07ithdraw |08[|15I|08]|07nvite |08[|15K|08]|07ick |08[|15M|08]|07emo ' : '') + '|08[|15L|08]|07eave |08[|15Q|08]|07uit|08: |07'; + const k = await s.promptChoice(opts, 'DLQ\r' + (leader ? 'WIKM' : '')); + await s.println(); + if (k === 'Q' || k === '\r') return; + if (k === 'D' || k === 'W') await treasury(s, uid, k === 'D'); + if (k === 'I') await invite(s, uid); + if (k === 'K') await kick(s, list.filter((m) => m.user_id !== uid)); + if (k === 'M') { + await s.print('|03 Memo: '); + const memo = (await s.readLine({ maxLen: 70 })).trim(); + await pool.query('UPDATE sl_syndicates SET memo = $2 WHERE id = $1', [syn.id, memo]); + } + if (k === 'L' && (await confirm(s, leader ? ' Leave? Leadership passes on (or the syndicate dissolves).' : ' Leave the syndicate?', false))) { + await leave(uid); + } + } +} + +async function found(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + if (p.credits < 10000) return void (await s.println(' |12Founding papers cost 10,000 credits.')); + await s.print('|03 Syndicate name: '); + const name = (await s.readLine({ maxLen: 30 })).trim(); + if (name.length < 3) return; + try { + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + if (me.credits < 10000 || me.syndicate_id) throw new Error('nope'); + const { rows } = await c.query<{ id: number }>('INSERT INTO sl_syndicates (name, leader_id) VALUES ($1, $2) RETURNING id', [name, uid]); + me.credits -= 10000; + me.syndicate_id = rows[0].id; + await savePilot(c, me); + await c.query('UPDATE sl_planets SET syndicate_id = $2 WHERE owner_id = $1', [uid, rows[0].id]); + await c.query('UPDATE sl_defenses SET syndicate_id = $2 WHERE owner_id = $1', [uid, rows[0].id]); + await addNews(`|11${esc(me.handle)}|07 founded the |05${esc(name)}|07 syndicate.`, c); + }); + await s.println(` |10The ${esc(name)} is open for business.`); + } catch (err) { + if ((err as { code?: string }).code === '23505') await s.println(' |12That name is taken.'); + else await s.println(' |12The registry clerk rejects your paperwork.'); + } +} + +async function join(s: Session, uid: number): Promise { + const inv = await invitesFor(uid); + const i = await pickFromList(s, 'Accept which invitation?', inv.map((x) => `|05${esc(x.name)}`)); + if (i === null) return; + const syn = inv[i]; + const full = (await members(syn.id)).length >= SL.maxSyndicateMembers; + if (full) return void (await s.println(' |12That syndicate is full.')); + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + me.syndicate_id = syn.id; + await savePilot(c, me); + await c.query('DELETE FROM sl_invites WHERE user_id = $1', [uid]); + await c.query('UPDATE sl_planets SET syndicate_id = $2 WHERE owner_id = $1', [uid, syn.id]); + await c.query('UPDATE sl_defenses SET syndicate_id = $2 WHERE owner_id = $1', [uid, syn.id]); + await tell(syn.leader_id, `|10${esc(me.handle)} joined ${esc(syn.name)}.`, c); + }); + await s.println(` |10Welcome to ${esc(syn.name)}.`); +} + +async function invite(s: Session, uid: number): Promise { + const p = (await getPilot(pool, uid))!; + await s.print('|03 Invite which pilot (handle): '); + const h = (await s.readLine({ maxLen: 20 })).trim(); + if (!h) return; + const t = await findPilotByHandle(pool, h); + if (!t) return void (await s.println(' |12No such pilot.')); + if (t.syndicate_id) return void (await s.println(' |07They already belong to a syndicate.')); + await pool.query('INSERT INTO sl_invites (syndicate_id, user_id) VALUES ($1, $2) ON CONFLICT DO NOTHING', [p.syndicate_id, t.user_id]); + const syn = await getSyndicate(pool, p.syndicate_id); + await tell(t.user_id, `|14${esc(p.handle)} invites you to join the ${esc(syn?.name ?? 'syndicate')}. |07(Y at the sector prompt)`); + await s.println(' |10Invitation sent.'); +} + +async function kick(s: Session, list: { user_id: number; handle: string }[]): Promise { + const i = await pickFromList(s, 'Remove which member?', list.map((m) => `|11${esc(m.handle)}`)); + if (i === null) return; + await leave(list[i].user_id); + await tell(list[i].user_id, '|12You have been removed from your syndicate.'); +} + +async function leave(uid: number): Promise { + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const syn = await getSyndicate(c, me.syndicate_id, true); + me.syndicate_id = null; + await savePilot(c, me); + await c.query('UPDATE sl_planets SET syndicate_id = NULL WHERE owner_id = $1', [uid]); + await c.query('UPDATE sl_defenses SET syndicate_id = NULL WHERE owner_id = $1', [uid]); + if (!syn) return; + if (syn.leader_id === uid) { + const { rows } = await c.query<{ user_id: number }>('SELECT user_id FROM sl_players WHERE syndicate_id = $1 ORDER BY xp DESC LIMIT 1', [syn.id]); + if (rows[0]) await c.query('UPDATE sl_syndicates SET leader_id = $2 WHERE id = $1', [syn.id, rows[0].user_id]); + else { + await c.query('DELETE FROM sl_syndicates WHERE id = $1', [syn.id]); + await addNews(`|07The |05${esc(syn.name)}|07 syndicate has dissolved.`, c); + } + } + }); +} + +async function treasury(s: Session, uid: number, deposit: boolean): Promise { + const p = (await getPilot(pool, uid))!; + const syn = (await getSyndicate(pool, p.syndicate_id))!; + const max = deposit ? p.credits : syn.treasury; + await s.print(`|03 Amount |08(0-${commas(max)})|03: `); + const n = (await readNumber(s, 0, max, 0, 11)) ?? 0; + if (!n) return; + await withTx(async (c) => { + const me = (await getPilot(c, uid, true))!; + const sy = (await getSyndicate(c, me.syndicate_id, true))!; + if (deposit && me.credits >= n) { + me.credits -= n; + sy.treasury += n; + } else if (!deposit && sy.leader_id === uid && sy.treasury >= n) { + sy.treasury -= n; + me.credits += n; + } else return; + await c.query('UPDATE sl_syndicates SET treasury = $2 WHERE id = $1', [sy.id, sy.treasury]); + await savePilot(c, me); + }); +} diff --git a/src/doors/starlane/screens/sysop.ts b/src/doors/starlane/screens/sysop.ts new file mode 100644 index 0000000..4205368 --- /dev/null +++ b/src/doors/starlane/screens/sysop.ts @@ -0,0 +1,69 @@ +import type { Session } from '../../../session/Session'; +import { withTx } from '../repo/q'; +import { allPilots, getPilot, savePilot } from '../repo/players'; +import { bigBang, worldStats, getUniverse } from '../repo/world'; +import { addNews } from '../repo/news'; +import { runTick } from '../ticker'; +import { BIG_BANG } from '../art/scenes'; +import { header, field, commas, esc, readNumber, pickFromList, art, confirm } from './ui'; + +export async function sysopMenu(s: Session): Promise { + for (;;) { + const st = await worldStats(); + const u = getUniverse(); + await s.println(); + await s.println(header('STARLANE Sysop', `|07Epoch |15${u.epoch}`)); + await s.println(field('Universe', `|15${commas(st.sectors)}|07 sectors, ${commas(st.ports)} ports, seed ${u.seed}, ${u.turns_per_day} turns/day`)); + await s.println(field('Population', `|15${st.pilots}|07 pilots, ${st.planets} planets, ${st.reavers} Reavers, ${st.syndicates} syndicates`)); + const k = await s.promptChoice( + '|08 [|15E|08]|07dit pilot |08[|15T|08]|07ick now |08[|15P|08]|07ost news |08[|15B|08]|07ig Bang |08[|15Q|08]|07uit|08: |07', + 'ETPBQ\r', + ); + await s.println(); + if (k === 'Q' || k === '\r') return; + if (k === 'T') { + await runTick(); + await s.println(' |10World tick complete.'); + } + if (k === 'P') { + await s.print('|03 Headline: '); + const t = (await s.readLine({ maxLen: 70 })).trim(); + if (t) await addNews(`|14SYSOP:|07 ${esc(t)}`); + } + if (k === 'E') await editPilot(s); + if (k === 'B') await doBigBang(s); + } +} + +async function editPilot(s: Session): Promise { + const pilots = await allPilots(); + const i = await pickFromList(s, 'Pilot', pilots.slice(0, 18).map((p) => `|11${esc(p.handle)} |08${commas(p.credits)} cr, ${p.turns_left} turns, sector ${p.sector}`)); + if (i === null) return; + const uid = pilots[i].user_id; + await s.print('|03 Set credits |08(Enter=keep)|03: '); + const cr = await readNumber(s, 0, 2_000_000_000, null, 11); + await s.print('|03 Set turns left |08(Enter=keep)|03: '); + const tu = await readNumber(s, 0, 100000, null, 6); + await withTx(async (c) => { + const p = (await getPilot(c, uid, true))!; + if (cr !== null) p.credits = cr; + if (tu !== null) p.turns_left = tu; + await savePilot(c, p); + }); + await s.println(' |10Saved.'); +} + +async function doBigBang(s: Session): Promise { + await s.println(' |12This destroys every pilot, planet, syndicate and port and builds a new universe.'); + await s.print(`|03 Sectors |08(100-5000, Enter=${getUniverse().size})|03: `); + const size = (await readNumber(s, 100, 5000, getUniverse().size, 5))!; + await s.print(`|03 Turns per day |08(10-5000, Enter=${getUniverse().turns_per_day})|03: `); + const turns = (await readNumber(s, 10, 5000, getUniverse().turns_per_day, 5))!; + if (!(await confirm(s, ' Are you absolutely sure?', false))) return; + await s.print('|12 Type BIGBANG to confirm: '); + if ((await s.readLine({ maxLen: 10 })).trim() !== 'BIGBANG') return; + await s.println(' |07Collapsing the old universe...'); + await bigBang(size, turns); + await art(s, BIG_BANG); + await s.println(' |10A new frontier is born. All pilots start fresh.'); +} diff --git a/src/doors/starlane/screens/ui.ts b/src/doors/starlane/screens/ui.ts new file mode 100644 index 0000000..8374ab3 --- /dev/null +++ b/src/doors/starlane/screens/ui.ts @@ -0,0 +1,38 @@ +import type { Session } from '../../../session/Session'; +import { padRight, vlen } from '../../../session/ansi'; +import { commas } from '../../../ui/widgets'; + +export { commas }; +export { padLeft, readNumber, pickFromList } from '../../../ui/widgets'; +export { esc, padRight, center } from '../../../session/ansi'; + +/** "─[ Title ]──────" header line, 79 wide. */ +export function header(title: string, right = ''): string { + const left = `|08─[ |15${title} |08]`; + const r = right ? `|08[ ${right} |08]─` : ''; + const fill = Math.max(1, 79 - vlen(left) - vlen(r)); + return left + '|08' + '─'.repeat(fill) + r; +} + +/** Label/value line for status panels. */ +export const field = (label: string, value: string, w = 10) => ` |03${padRight(label, w)}|08: |07${value}`; + +export const cr = (n: number) => `|15${commas(n)}|07 cr`; + +/** Y/N prompt on one line. */ +export async function confirm(s: Session, question: string, defaultYes = false): Promise { + await s.print(`|07${question} |08(${defaultYes ? '|15Y|08/n' : 'y/|15N|08'})|07: `); + return s.yesNo(defaultYes); +} + +export async function msg(s: Session, text: string): Promise { + await s.println(` ${text}`); +} + +/** Prints a list of lines (art). */ +export async function art(s: Session, lines: string[]): Promise { + for (const l of lines) await s.println(l); +} + +/** Short pause for dramatic effect (combat, docking). */ +export const beat = (ms = 350) => new Promise((r) => setTimeout(r, ms)); diff --git a/src/doors/starlane/ticker.ts b/src/doors/starlane/ticker.ts new file mode 100644 index 0000000..91bd3e5 --- /dev/null +++ b/src/doors/starlane/ticker.ts @@ -0,0 +1,149 @@ +import { pool, withTx } from './repo/q'; +import { allReavers, saveReaver, spawnReaver, getReaver } from './repo/npcs'; +import { getPilot, pilotsInSector, savePilot } from './repo/players'; +import { planetsInSector, savePlanet, getPlanet } from './repo/planets'; +import { getDefense, saveDefense } from './repo/defenses'; +import { warpsFrom, isConcord, getUniverse } from './repo/world'; +import { addNews, tell, pruneOld } from './repo/news'; +import { battle } from './engine/combat'; +import { pick, randInt } from './engine/rng'; +import { reaverName, REAVER_CLANS } from './data/names'; +import { destroyPilot } from './actions/fate'; +import { esc } from '../../session/ansi'; +import { SL } from './config'; + +const rng = Math.random; +let timer: NodeJS.Timeout | null = null; + +export function startTicker(): void { + if (timer) return; + timer = setInterval(() => { + runTick().catch((err) => console.error('[starlane] tick failed', err)); + }, SL.tickMinutes * 60_000); + timer.unref(); +} + +/** One world step: Reavers roam, grow, raid; old news is pruned. */ +export async function runTick(): Promise { + // Session-level advisory lock must be taken and released on the same connection. + const lockConn = await pool.connect(); + try { + const got = await lockConn.query<{ ok: boolean }>('SELECT pg_try_advisory_lock(727301) AS ok'); + if (!got.rows[0].ok) return; + try { + await respawn(); + for (const r of await allReavers()) await reaverTurn(r.id); + await pruneOld(); + } finally { + await lockConn.query('SELECT pg_advisory_unlock(727301)'); + } + } finally { + lockConn.release(); + } +} + +async function respawn(): Promise { + const have = (await allReavers()).length; + const size = getUniverse().size; + for (let i = have; i < SL.reaverCount; i++) { + const shipType = pick(rng, [2, 3, 4, 4, 6, 7]); + const fighters = randInt(rng, 80, 300) * shipType; + await spawnReaver(pool, { + name: reaverName(rng), + clan: pick(rng, REAVER_CLANS), + ship_type: shipType, + sector: randInt(rng, SL.concordMax + 1, size), + fighters, + shields: Math.round(fighters / 3), + credits: randInt(rng, 500, 5000), + }); + } +} + +async function reaverTurn(id: number): Promise { + // Roam a few lanes, never into Concord Space. + await withTx(async (c) => { + const r = await getReaver(c, id, true); + if (!r) return; + const steps = randInt(rng, 1, 3); + for (let i = 0; i < steps; i++) { + const opts = warpsFrom(r.sector).filter((w) => !isConcord(w)); + if (!opts.length) break; + r.sector = pick(rng, opts); + const d = await getDefense(c, r.sector, true); + if (d && d.fighters > 0) { + // Reavers smash into sector fighters they find. + const b = battle({ fighters: r.fighters, shields: 0 }, { fighters: d.fighters, shields: 0 }, rng); + r.fighters = b.attacker.fighters; + d.fighters = b.defender.fighters; + await saveDefense(c, d); + await tell(d.owner_id, `|12The Reaver "${esc(r.name)}" tore through your fighters in sector ${r.sector}${b.defenderBroken ? ' (all lost)' : ''}.`, c); + if (b.attackerBroken) { + await addNews(`|07Defenses in sector ${r.sector} destroyed the Reaver |12"${esc(r.name)}"|07.`, c); + await c.query('DELETE FROM sl_npcs WHERE id = $1', [r.id]); + return; + } + break; + } + } + // Grow a little stronger over time. + r.fighters = Math.round(r.fighters * 1.03) + 5; + r.shields = Math.round(r.shields * 1.02); + await saveReaver(c, r); + }); + + const r = await getReaver(pool, id); + if (!r || isConcord(r.sector)) return; + + // Prey on a weak ship left in open space. + const prey = (await pilotsInSector(pool, r.sector)).filter((p) => p.fighters * 1.5 < r.fighters); + if (prey.length && rng() < 0.5) { + const target = pick(rng, prey); + await withTx(async (c) => { + const p = await getPilot(c, target.user_id, true); + const me = await getReaver(c, id, true); + if (!p || !me || p.sector !== me.sector || p.landed_planet !== null) return; + const b = battle({ fighters: Math.ceil(me.fighters * 0.6), shields: 0 }, { fighters: p.fighters, shields: p.shields }, rng); + me.fighters -= b.attackerLost; + p.fighters = b.defender.fighters; + p.shields = b.defender.shields; + if (b.defenderBroken) { + await destroyPilot(c, p, { kind: 'reaver', reaver: me }, false); + } else { + await savePilot(c, p); + await tell(p.user_id, `|12The Reaver "${esc(me.name)}" attacked you in sector ${p.sector}!|07 You lost ${b.defenderFightersLost} fighters, ${b.defenderShieldsLost} shields.`, c); + } + await saveReaver(c, me); + }); + return; + } + + // Or plunder a poorly defended planet. + const planets = (await planetsInSector(pool, r.sector)).filter((pl) => pl.fighters + pl.shields < r.fighters * 0.5); + if (planets.length && rng() < 0.35) { + const target = pick(rng, planets); + await withTx(async (c) => { + const me = await getReaver(c, id, true); + const pl = await getPlanet(c, target.id, true); + if (!me || !pl) return; + const b = battle({ fighters: Math.ceil(me.fighters * 0.5), shields: 0 }, { fighters: Math.floor(pl.fighters), shields: Math.floor(pl.shields) }, rng, 1, 1.2); + me.fighters -= b.attackerLost; + pl.fighters = b.defender.fighters; + pl.shields = b.defender.shields; + let note = 'was beaten off'; + if (b.defenderBroken) { + pl.stock = pl.stock.map((x) => x * 0.6); + if (pl.bastion < 1) { + me.credits += pl.credits; + pl.credits = 0; + } + pl.colonists *= 0.9; + note = 'plundered it'; + await addNews(`|12Reavers|07 of clan ${esc(me.clan)} raided the planet |10${esc(pl.name)}|07.`, c); + } + await savePlanet(c, pl); + await saveReaver(c, me); + if (pl.owner_id) await tell(pl.owner_id, `|12The Reaver "${esc(me.name)}" attacked ${esc(pl.name)} (sector ${pl.sector}) and ${note}.`, c); + }); + } +} diff --git a/src/doors/types.ts b/src/doors/types.ts new file mode 100644 index 0000000..296f1b6 --- /dev/null +++ b/src/doors/types.ts @@ -0,0 +1,22 @@ +import type { Session } from '../session/Session'; + +/** + * A door game / external program. See src/doors/CLAUDE.md for the contract. + * Doors must not import from other doors or from src/screens. + */ +export interface DoorModule { + /** Short stable id; also the migration namespace (e.g. "starlane/001_init.sql"). */ + id: string; + /** Display name in the door menu. */ + name: string; + /** One-line description shown in the door menu (keep under ~45 chars). */ + description: string; + /** Minimum users.security_level required to see/run the door. */ + minSecurity?: number; + /** Absolute path to a folder of *.sql migrations for this door's own tables. */ + migrationsDir?: string; + /** Called once at server start, after migrations. Start timers here. */ + init?(): Promise; + /** Runs the door for one caller. Return to drop back to the BBS. */ + run(s: Session): Promise; +} diff --git a/src/nodes.ts b/src/nodes.ts index bb04caa..7f0daca 100644 --- a/src/nodes.ts +++ b/src/nodes.ts @@ -7,3 +7,23 @@ export function initNodes(count: number): void { nodes.length = 0; for (let i = 0; i < count; i++) nodes.push(null); } + +/** Live sessions whose caller is logged in as this user. */ +export function sessionsForUser(userId: number): Session[] { + return nodes.filter((n): n is Session => !!n && n.isOpen && n.user?.id === userId); +} + +/** + * Queues a message for a logged-in user (shown at their next prompt). + * Returns true if the user is online on at least one node. + */ +export function notifyUser(userId: number, text: string): boolean { + const live = sessionsForUser(userId); + for (const s of live) s.notify(text); + return live.length > 0; +} + +/** Queues a message for every logged-in caller, optionally skipping one node. */ +export function broadcast(text: string, exceptNode?: number): void { + for (const n of nodes) if (n && n.isOpen && n.user && n.node !== exceptNode) n.notify(text); +} diff --git a/src/screens/mainMenu.ts b/src/screens/mainMenu.ts index bc3b27b..d3d5c63 100644 --- a/src/screens/mainMenu.ts +++ b/src/screens/mainMenu.ts @@ -1,32 +1,19 @@ import type { Session } from '../session/Session'; import { esc, padRight, center } from '../session/ansi'; import { nodes } from '../nodes'; -import { lastCallers, SYSOP_LEVEL } from '../users/userRepo'; +import { lastCallers } from '../users/userRepo'; import { config } from '../config'; +import { makeBox } from '../ui/box'; +import { menuItem, securityLabel } from '../ui/widgets'; +import { doorMenu } from '../doors/doorMenu'; -const W = 78; // inner box width - -const box = { - top: `|09╔${'═'.repeat(W)}╗`, - mid: `|09╟${'─'.repeat(W)}╢`, - bot: `|09╚${'═'.repeat(W)}╝`, - row: (content: string) => `|09║|07${padRight(content, W)}|09║`, -}; - -const item = (key: string, label: string) => padRight(` |08[|15${key}|08] |11${label}`, 39); +const box = makeBox(78); +const item = (key: string, label: string) => menuItem(key, label); function minutesOn(s: Session): number { return Math.floor((Date.now() - (s.loginAt ?? s.connectedAt).getTime()) / 60000); } -function securityLabel(level: number): string { - if (level >= SYSOP_LEVEL) return 'Sysop'; - if (level >= 100) return 'Co-Sysop'; - if (level >= 50) return 'Elite'; - if (level >= 20) return 'Validated'; - return 'New User'; -} - async function drawMenu(s: Session): Promise { const u = s.user!; const time = new Date().toLocaleTimeString('en-US', { hour12: false }); @@ -74,7 +61,7 @@ export async function mainMenu(s: Session): Promise { await underConstruction(s, 'File Areas'); break; case 'D': - await underConstruction(s, 'Door Games'); + await doorMenu(s); break; case 'B': await underConstruction(s, 'Bulletins'); diff --git a/src/server.ts b/src/server.ts index d1ca2ae..09a2db2 100644 --- a/src/server.ts +++ b/src/server.ts @@ -7,13 +7,15 @@ import { migrate } from './db'; import { nodes, initNodes } from './nodes'; import { Session, Disconnected } from './session/Session'; import { runCall } from './screens/connect'; +import { doors } from './doors/registry'; const ROOT = path.resolve(__dirname, '..'); const send = (ws: import('ws').WebSocket, msg: object) => ws.send(JSON.stringify(msg)); async function main(): Promise { - await migrate(); + await migrate(doors.filter((d) => d.migrationsDir).map((d) => ({ namespace: `${d.id}/`, dir: d.migrationsDir! }))); initNodes(config.maxNodes); + for (const d of doors) await d.init?.(); const app = express(); app.disable('x-powered-by'); diff --git a/src/session/Session.ts b/src/session/Session.ts index ba38a25..d3fc521 100644 --- a/src/session/Session.ts +++ b/src/session/Session.ts @@ -31,6 +31,8 @@ export class Session { private printing = false; private skipThrottle = false; private idleTimer: NodeJS.Timeout | null = null; + private notices: string[] = []; + private liveNotice: ((text: string) => void) | null = null; constructor( private readonly ws: WebSocket, @@ -145,6 +147,60 @@ export class Session { this.write('\r\x1b[2K'); } + // ---- notices -------------------------------------------------------- + + /** + * Queues a message from another node / the system (pipe codes allowed). + * Screens show these with takeNotices() just before drawing a prompt, so a + * notice never lands in the middle of a line the caller is typing. + */ + notify(text: string): void { + if (this.closed) return; + if (this.liveNotice) { + this.liveNotice(text); + return; + } + this.notices.push(text); + if (this.notices.length > 50) this.notices.splice(0, this.notices.length - 50); + } + + /** Returns and clears queued notices. */ + takeNotices(): string[] { + const out = this.notices; + this.notices = []; + return out; + } + + /** Prints any queued notices. Call right before a prompt. */ + async showNotices(): Promise { + const list = this.takeNotices(); + if (!list.length) return; + for (const n of list) await this.println(`|08» |07${n}`); + } + + /** + * Shows queued notices, a one-line prompt, and waits for a hotkey. Notices + * that arrive while waiting are printed above the prompt straight away + * (safe because no partial input exists at a hotkey prompt). + */ + async promptChoice(prompt: string, valid: string): Promise { + await this.showNotices(); + await this.print(prompt); + const rendered = pipe(prompt); + this.liveNotice = (text) => { + try { + this.write('\r\x1b[2K' + pipe(`|08» |07${text}`) + '\r\n' + rendered); + } catch { + /* disconnected */ + } + }; + try { + return await this.readChoice(valid); + } finally { + this.liveNotice = null; + } + } + // ---- output --------------------------------------------------------- /** Immediate, unthrottled output (echo, cursor control). */ diff --git a/src/ui/box.ts b/src/ui/box.ts new file mode 100644 index 0000000..cbbb54b --- /dev/null +++ b/src/ui/box.ts @@ -0,0 +1,21 @@ +import { padRight } from '../session/ansi'; + +/** + * Double-line box helpers. `width` is the inner width (between the borders); + * an 80-column screen fits width 78. Rows are padded using the visible + * length, so pipe codes inside `content` are fine. + */ +export function makeBox(width = 78, border = '|09', text = '|07') { + return { + width, + top: `${border}╔${'═'.repeat(width)}╗`, + mid: `${border}╟${'─'.repeat(width)}╢`, + bot: `${border}╚${'═'.repeat(width)}╝`, + row: (content: string) => `${border}║${text}${padRight(content, width)}${border}║`, + }; +} + +/** Single-line horizontal rule. */ +export function rule(width = 79, color = '|08'): string { + return color + '─'.repeat(width); +} diff --git a/src/ui/widgets.ts b/src/ui/widgets.ts new file mode 100644 index 0000000..acc6e22 --- /dev/null +++ b/src/ui/widgets.ts @@ -0,0 +1,63 @@ +import type { Session } from '../session/Session'; +import { padRight, vlen } from '../session/ansi'; +import { SYSOP_LEVEL } from '../users/userRepo'; + +/** "[K] Label" menu entry padded to a column width. */ +export function menuItem(key: string, label: string, width = 39): string { + return padRight(` |08[|15${key}|08] |11${label}`, width); +} + +export function securityLabel(level: number): string { + if (level >= SYSOP_LEVEL) return 'Sysop'; + if (level >= 100) return 'Co-Sysop'; + if (level >= 50) return 'Elite'; + if (level >= 20) return 'Validated'; + return 'New User'; +} + +/** Left-pads to a visible width (for right-aligned numbers). */ +export function padLeft(text: string, width: number): string { + return ' '.repeat(Math.max(0, width - vlen(text))) + text; +} + +/** 1234567 -> "1,234,567" */ +export function commas(n: number): string { + return Math.trunc(n).toLocaleString('en-US'); +} + +/** + * Prompts for an integer in [min, max]. Empty input returns `dflt` (or null + * when no default is given), so callers can treat Enter as "cancel". + */ +export async function readNumber( + s: Session, + min: number, + max: number, + dflt: number | null = null, + maxLen = 10, +): Promise { + for (;;) { + const raw = (await s.readLine({ maxLen })).trim().replace(/,/g, ''); + if (!raw) return dflt; + if (/^-?\d+$/.test(raw)) { + const n = Number(raw); + if (n >= min && n <= max) return n; + } + await s.print(`|12 Enter a number from ${commas(min)} to ${commas(max)}: |07`); + } +} + +/** + * Shows a numbered list and returns the chosen index, or null on Enter. + * Fits up to ~18 entries on one screen. + */ +export async function pickFromList(s: Session, title: string, entries: string[]): Promise { + if (!entries.length) return null; + await s.println(`|15 ${title}`); + for (let i = 0; i < entries.length; i++) { + await s.println(` |08[|15${padLeft(String(i + 1), 2)}|08] |07${entries[i]}`); + } + await s.print(`|03 Choice |08(|07Enter to cancel|08)|03: `); + const n = await readNumber(s, 1, entries.length, null, 3); + return n === null ? null : n - 1; +}