Files
2026-11-01 15:22:21 -05:00

202 lines
15 KiB
JavaScript
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { DatabaseSync } from 'node:sqlite';
import { randomUUID } from 'node:crypto';
export const PLACES = {
crossing: { title: 'The River Crossing', text: 'A weathered bridge spans the Alder. Caravans once met here; now its repair is in the hands of those who come after.', neighbors: ['wood', 'market'] },
wood: { title: 'Alderwood', text: 'Silver trunks rise from a carpet of moss. Fallen timber supplies the valley; pale antlers sometimes move between the trees.', neighbors: ['crossing'] },
market: { title: 'Lantern Market', text: 'An open exchange beneath slate roofs. Every offer belongs to a player. Goods stay here until their buyer carries them onward.', neighbors: ['crossing'] },
};
export const DURATIONS = { travel: 20_000, gather: 12_000, craft: 15_000, build: 18_000, observe: 10_000, rest: 10_000 };
const id = () => randomUUID();
export class RuleError extends Error {}
const requireRule = (condition, message) => { if (!condition) throw new RuleError(message); };
export function worldClock(now, epoch) {
const elapsed = Math.max(0, now - epoch);
const fraction = elapsed % 72_000_000 / 72_000_000;
const hour = fraction * 24;
return { day: Math.floor(elapsed / 72_000_000) + 1, hour: Math.floor(hour), minute: Math.floor(hour % 1 * 60), phase: hour < 5 || hour >= 20 ? 'Night' : hour < 7 ? 'Dawn' : hour < 18 ? 'Daylight' : 'Dusk', nextPhaseAt: now + (([5, 7, 18, 20, 29].find(h => h > hour) - hour) * 3_000_000) };
}
export class Game {
constructor(filename, { now = Date.now } = {}) {
this.now = now;
this.db = new DatabaseSync(filename);
this.db.exec('CREATE TABLE IF NOT EXISTS world (id INTEGER PRIMARY KEY CHECK(id=1), data TEXT NOT NULL)');
const saved = this.db.prepare('SELECT data FROM world WHERE id=1').get();
this.state = saved ? JSON.parse(saved.data) : { epoch: now() - 8 * 3_000_000, accounts: {}, characters: {}, events: [], orders: [], journal: [], bridge: 0, timber: 40 };
if (!saved) {
for (const [key, name, location] of [['demo-fern', 'Fern Ash', 'crossing'], ['demo-rowan', 'Rowan Vale', 'market']]) {
this.state.accounts[key] = { id: key, balance: 100, allocated: true };
this.createCharacterIn(this.state, key, name, location);
this.state.journal.push({ id: id(), at: now(), entries: [{ account: 'issuance', amount: -100 }, { account: key, amount: 100 }], memo: 'Bounded demo allocation' });
}
this.save(this.state);
}
this.tick();
}
close() { this.db.close(); }
save(next) {
this.db.prepare('INSERT INTO world(id,data) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET data=excluded.data').run(JSON.stringify(next));
this.state = next;
}
mutate(fn) {
const next = structuredClone(this.state); const result = fn(next);
if (this.request) {
next.receipts ||= {};
const receipts = next.receipts[this.request.account] ||= {};
receipts[this.request.key] = this.request.signature;
// Bounded retry window for this demo; production needs durable retention policy.
const keys = Object.keys(receipts); if (keys.length > 1000) delete receipts[keys[0]];
}
this.save(next); return result;
}
runOnce(account, key, signature, fn) {
requireRule(typeof key === 'string' && /^[A-Za-z0-9_-]{16,80}$/.test(key), 'A valid Idempotency-Key is required.');
const prior = this.state.receipts?.[account]?.[key];
if (prior !== undefined) { requireRule(prior === signature, 'Request key was already used for a different action.'); return; }
this.tick();
this.request = { account, key, signature };
try { fn(); } finally { this.request = null; }
}
createCharacterIn(s, account, name, location = 'crossing') {
requireRule(!Object.values(s.characters).some(c => c.account === account && c.alive), 'This account already has a living character.');
requireRule(typeof name === 'string' && name.trim().length >= 2 && name.trim().length <= 40 && !/[\x00-\x1f]/.test(name), 'Use a character name of 2–40 characters.');
const newcomer = !Object.values(s.characters).some(c => c.account === account);
const character = { id: id(), account, name: name.trim(), location, alive: true, bio: 'A traveler with a story still unwritten.', inventory: { timber: newcomer ? 4 : 0, plank: 0 }, activity: null, hidden: false, knowledge: [] };
s.characters[character.id] = character;
return character.id;
}
accountForIdentity(issuer, subject, name) {
requireRule(typeof subject === 'string' && subject.length > 0 && subject.length <= 512, 'Invalid identity.');
return this.mutate(s => {
const found = Object.values(s.accounts).find(a => a.issuer === issuer && a.subject === subject);
if (found) return found.id;
const key = id();
s.accounts[key] = { id: key, issuer, subject, balance: 0, allocated: false };
this.createCharacterIn(s, key, typeof name === 'string' ? name.slice(0, 40) : 'New traveler');
return key;
});
}
successor(account, name) {
this.tick();
return this.mutate(s => { requireRule(s.accounts[account], 'Unknown account.'); return this.createCharacterIn(s, account, name); });
}
// Domain-only lifecycle hook. No browser endpoint can kill another character.
die(characterId) {
this.tick();
this.mutate(s => {
const c = s.characters[characterId];
requireRule(c?.alive, 'Character is not alive.');
this.refund(c); c.alive = false; c.activity = null; c.hidden = false;
this.event(s, c, 'A life ended', `${c.name}'s life has ended. Their story remains in the valley's history.`, this.now(), [c.location]);
});
}
character(s, account) {
requireRule(s.accounts[account], 'Unknown account.');
const c = Object.values(s.characters).find(c => c.account === account && c.alive);
requireRule(c, 'Create a successor before acting.'); return c;
}
witnesses(s, c, places) {
return Object.values(s.characters).filter(other => other.id === c.id || (!c.hidden && other.alive && !other.activity?.destination && places.includes(other.location))).map(other => other.id);
}
event(s, c, title, text, at, places, audience = this.witnesses(s, c, places)) {
s.events.push({ id: id(), title, text, at, places, actor: c.id, audience: [...new Set(audience)] });
}
refund(c) {
if (c.activity?.type === 'craft') c.inventory.timber += 2;
if (c.activity?.type === 'build') c.inventory.plank += 1;
}
tick() {
const time = this.now();
if (!Object.values(this.state.characters).some(c => c.activity && c.activity.endsAt <= time)) return;
this.mutate(s => {
const due = Object.values(s.characters).filter(c => c.activity && c.activity.endsAt <= time).sort((a, b) => a.activity.endsAt - b.activity.endsAt || a.id.localeCompare(b.id));
for (const c of due) {
const a = c.activity;
let title, text;
if (a.type === 'travel') { c.location = a.destination; title = 'A journey completed'; text = `${c.name} reached ${PLACES[c.location].title}.`; }
if (a.type === 'gather') { const count = Math.min(3, s.timber); s.timber -= count; c.inventory.timber += count; title = 'Timber gathered'; text = `${c.name} gathered ${count} timber in Alderwood.`; }
if (a.type === 'craft') { c.inventory.plank += 1; title = 'A plank crafted'; text = `${c.name} shaped two timber into a sturdy plank.`; }
if (a.type === 'build') { if (s.bridge < 6) { s.bridge += 1; title = 'The crossing restored'; text = `${c.name} contributed a plank. The bridge now has ${s.bridge} of 6 required contributions.`; } else { c.inventory.plank += 1; title = 'The crossing already stands'; text = `${c.name}'s reserved plank was returned because the bridge was already complete.`; } }
if (a.type === 'observe') { if (c.location === 'wood' && !c.knowledge.includes('stag')) c.knowledge.push('stag'); title = 'A careful observation'; text = c.location === 'wood' ? `${c.name} observed a moon-antler stag grazing among the silver trees.` : `${c.name} watched the valley, learning the shape of the place.`; }
if (a.type === 'rest') { title = 'A moment of rest'; text = `${c.name} rested beneath the changing sky.`; }
this.event(s, c, title, text, a.endsAt, [c.location]);
c.activity = null;
// Concealment persists at destination until a physical action reveals the traveler.
}
});
}
act(account, input) {
this.tick();
return this.mutate(s => {
const c = this.character(s, account);
requireRule(!c.activity, 'Your character is occupied. Finish or cancel the current activity.');
requireRule(Object.hasOwn(DURATIONS, input.type), 'Unsupported activity.');
if (input.type === 'travel') requireRule(PLACES[c.location].neighbors.includes(input.destination), 'That destination is not adjacent.');
if (input.type === 'gather') requireRule(c.location === 'wood' && s.timber > 0, 'Gathering requires available timber in Alderwood.');
if (input.type === 'craft') { requireRule(c.inventory.timber >= 2, 'Crafting requires two timber.'); c.inventory.timber -= 2; }
if (input.type === 'build') { requireRule(c.location === 'crossing' && c.inventory.plank >= 1 && s.bridge < 6, 'Bring a plank to the unfinished crossing.'); c.inventory.plank -= 1; }
c.hidden = input.type === 'travel' && input.hidden === true;
c.activity = { type: input.type, startedAt: this.now(), endsAt: this.now() + DURATIONS[input.type], ...(input.type === 'travel' ? { destination: input.destination } : {}) };
this.event(s, c, 'An undertaking begun', `${c.name} began ${input.type === 'travel' ? 'a journey' : input.type + ' work'}.`, this.now(), [c.location]);
});
}
cancel(account) {
this.tick(); this.mutate(s => { const c = this.character(s, account); requireRule(c.activity, 'No activity to cancel.'); this.refund(c); c.activity = null; this.event(s, c, 'An undertaking stopped', `${c.name} stopped their activity. Reserved materials were returned; elapsed work was lost.`, this.now(), [c.location]); });
}
biography(account, bio) {
requireRule(typeof bio === 'string' && bio.length <= 500 && !/[\x00-\x08]/.test(bio), 'Biography must be at most 500 characters.');
this.tick(); this.mutate(s => { this.character(s, account).bio = bio; });
}
order(account, { item, quantity, price }) {
this.tick(); this.mutate(s => {
const c = this.character(s, account);
requireRule(!c.activity && c.location === 'market' && !c.hidden, 'You must be available at Lantern Market.');
requireRule(['timber', 'plank'].includes(item) && Number.isSafeInteger(quantity) && quantity >= 1 && quantity <= 100 && Number.isSafeInteger(price) && price >= 1 && price <= 1000, 'Invalid order.');
requireRule(c.inventory[item] >= quantity, 'Insufficient unreserved goods.');
c.inventory[item] -= quantity;
s.orders.push({ id: id(), seller: c.id, account, item, remaining: quantity, price, location: 'market', closed: false });
});
}
buy(account, { orderId, quantity }) {
this.tick(); this.mutate(s => {
const c = this.character(s, account), order = s.orders.find(o => o.id === orderId && !o.closed);
requireRule(!c.activity && c.location === 'market' && !c.hidden, 'You must be available at Lantern Market.');
requireRule(order && order.account !== account && Number.isSafeInteger(quantity) && quantity > 0 && quantity <= order.remaining, 'Order unavailable or invalid quantity.');
const amount = quantity * order.price;
requireRule(s.accounts[account].balance >= amount, 'Insufficient funds.');
s.accounts[account].balance -= amount; s.accounts[order.account].balance += amount;
order.remaining -= quantity; order.closed = order.remaining === 0; c.inventory[order.item] += quantity;
s.journal.push({ id: id(), at: this.now(), entries: [{ account, amount: -amount }, { account: order.account, amount }], memo: `${quantity} ${order.item}` });
this.event(s, c, 'An exchange settled', `${quantity} ${order.item} changed hands at Lantern Market for ${amount} crowns.`, this.now(), ['market'], [c.id, order.seller]);
});
}
withdraw(account, orderId) {
this.tick(); this.mutate(s => {
const c = this.character(s, account), o = s.orders.find(o => o.id === orderId && !o.closed && o.seller === c.id);
requireRule(o && !c.activity && c.location === 'market' && !c.hidden, 'Only the available seller at the market can withdraw this order.');
c.inventory[o.item] += o.remaining; o.remaining = 0; o.closed = true;
});
}
view(account) {
this.tick(); const s = this.state, c = this.character(s, account), a = s.accounts[account];
const events = s.events.filter(e => e.audience.includes(c.id));
const visibleIds = new Set([c.id, ...events.map(e => e.actor), ...Object.values(s.characters).filter(o => o.alive && !o.hidden && o.location === c.location && !o.activity?.destination && !c.activity?.destination).map(o => o.id)]);
const characters = Object.values(s.characters).filter(o => visibleIds.has(o.id)).map(o => {
const present = o.alive && !o.hidden && o.location === c.location && !o.activity?.destination && !c.activity?.destination;
return { id: o.id, name: o.name, bio: o.bio, alive: o.alive, ...(o.id === c.id || present ? { location: o.location, activity: o.activity, hidden: o.hidden } : {}) };
});
return {
now: this.now(), clock: worldClock(this.now(), s.epoch),
self: { id: c.id, name: c.name, bio: c.bio, location: c.location, activity: c.activity, hidden: c.hidden, inventory: c.inventory, balance: a.balance },
places: Object.entries(PLACES).map(([key, p]) => ({ id: key, ...p, ...(key === c.location && !c.activity?.destination ? { occupants: characters.filter(o => o.location === key && (o.id === c.id || !o.hidden)).map(o => o.id), ...(key === 'crossing' ? { bridge: s.bridge } : {}), ...(key === 'wood' ? { timber: s.timber } : {}) } : {}) })),
characters,
creatures: c.knowledge.includes('stag') ? [{ id: 'stag', title: 'Moon-antler stag', text: 'A quiet woodland creature with pale branching antlers. You observed it in Alderwood. This is a past sighting, not live tracking.', place: 'wood' }] : [],
events: events.map(({ audience, ...e }) => e),
orders: c.location === 'market' && !c.activity?.destination ? s.orders.filter(o => !o.closed).map(o => ({ id: o.id, item: o.item, remaining: o.remaining, price: o.price, mine: o.seller === c.id })) : [],
transactions: s.journal.filter(t => t.entries.some(e => e.account === account)).map(t => ({ id: t.id, at: t.at, amount: t.entries.find(e => e.account === account).amount, memo: t.memo })),
};
}
}