Compare commits

..

1 Commits

Author SHA1 Message Date
Timmy-Sprint
87d8ee56b2 beacon: add community swarm alignment simulation (#6)
Some checks failed
Accessibility Checks / a11y-audit (pull_request) Successful in 18s
Smoke Test / smoke (pull_request) Failing after 21s
2026-04-14 22:20:57 -04:00
7 changed files with 411 additions and 30 deletions

View File

@@ -174,6 +174,7 @@ body{background:var(--bg);color:var(--text);font-family:'SF Mono','Cascadia Code
<div id="sprint-label" style="font-size:9px;color:#666;margin-top:2px;text-align:center"></div>
</div>
<div id="alignment-ui" style="display:none"></div>
<div id="swarm-ui" style="display:none"></div>
<button class="save-btn" onclick="saveGame()" aria-label="Save game progress">Save Game [Ctrl+S]</button>
<div style="display:flex;gap:4px;margin-top:4px">
<button class="save-btn" onclick="exportSave()" aria-label="Export save to file" style="flex:1">Export [E]</button>
@@ -265,6 +266,7 @@ The light is on. The room is empty."
<script src="js/sound.js"></script>
<script src="js/engine.js"></script>
<script src="js/render.js"></script>
<script src="js/swarm.js"></script>
<script src="js/tutorial.js"></script>
<script src="js/dismantle.js"></script>
<script src="js/main.js"></script>

View File

@@ -106,6 +106,7 @@ const G = {
pactFlag: 0,
swarmFlag: 0,
swarmRate: 0,
swarmSim: null,
// Game state
running: true,

View File

@@ -102,6 +102,14 @@ function updateRates() {
G.codeRate += G.swarmRate;
}
if (typeof SwarmSim !== 'undefined') {
const simRates = SwarmSim.computeRates();
G.codeRate += simRates.codeRate;
G.knowledgeRate += simRates.knowledgeRate;
G.harmonyRate += simRates.harmonyRate;
G.trustRate += simRates.trustRate;
}
// Apply persistent debuffs from active events
if (G.activeDebuffs && G.activeDebuffs.length > 0) {
for (const debuff of G.activeDebuffs) {
@@ -207,6 +215,9 @@ function tick() {
// Combat: tick battle simulation
Combat.tickBattle(dt);
// Community swarm alignment simulation
if (typeof tickSwarm === 'function') tickSwarm(dt);
// Check milestones
checkMilestones();
@@ -422,11 +433,6 @@ function buyProject(id) {
if (!G.completedProjects) G.completedProjects = [];
G.completedProjects.push(pDef.id);
G.activeProjects = G.activeProjects.filter(aid => aid !== pDef.id);
// Final ReCKoning choices should end with no unrelated active research left behind.
if (pDef.id === 'p_reckoning_147' || pDef.id === 'p_reckoning_148') {
G.activeProjects = [];
}
}
updateRates();

View File

@@ -225,6 +225,7 @@ function saveGame() {
sprintCooldown: G.sprintCooldown || 0,
swarmFlag: G.swarmFlag || 0,
swarmRate: G.swarmRate || 0,
swarmSim: G.swarmSim || null,
strategicFlag: G.strategicFlag || 0,
projectsCollapsed: G.projectsCollapsed !== false,
dismantleTriggered: G.dismantleTriggered || false,
@@ -265,7 +266,7 @@ function loadGame() {
'drift', 'driftEnding', 'beaconEnding', 'pendingAlignment',
'lastEventAt', 'totalEventsResolved', 'buyAmount',
'sprintActive', 'sprintTimer', 'sprintCooldown',
'swarmFlag', 'swarmRate', 'strategicFlag', 'projectsCollapsed',
'swarmFlag', 'swarmRate', 'swarmSim', 'strategicFlag', 'projectsCollapsed',
'dismantleTriggered', 'dismantleActive', 'dismantleStage',
'dismantleResourceIndex', 'dismantleResourceTimer', 'dismantleDeferUntilAt', 'dismantleComplete'
];

233
js/swarm.js Normal file
View File

@@ -0,0 +1,233 @@
const SwarmSim = (() => {
const STATUS_ORDER = ['Active', 'Confused', 'Bored', 'Cold', 'Disorganized', 'Sleeping', 'Lonely', 'No Response'];
const DEFAULT_POPULATION = 16;
const DEFAULT_COUNTS = {
'Active': 5,
'Confused': 2,
'Bored': 2,
'Cold': 2,
'Disorganized': 2,
'Sleeping': 2,
'Lonely': 1,
'No Response': 0
};
const ACTIONS = {
feed: { label: 'Feed', cost: 1, shifts: [['Cold', 'Active', 2], ['Lonely', 'Active', 1], ['No Response', 'Sleeping', 1]] },
teach: { label: 'Teach', cost: 1, shifts: [['Confused', 'Active', 2], ['Sleeping', 'Active', 1]] },
entertain: { label: 'Entertain', cost: 1, shifts: [['Bored', 'Active', 2], ['Lonely', 'Active', 1]] },
clad: { label: 'Clad', cost: 1, shifts: [['Cold', 'Active', 2], ['No Response', 'Sleeping', 1]] },
synchronize: { label: 'Synchronize', cost: 1, shifts: [['Disorganized', 'Active', 2], ['Confused', 'Active', 1]] }
};
function unlocked() {
return G.swarmFlag === 1 || (G.buildings && (G.buildings.community || 0) > 0);
}
function ensure() {
if (!unlocked()) return null;
if (!G.swarmSim || typeof G.swarmSim !== 'object') {
G.swarmSim = {
population: DEFAULT_POPULATION,
counts: { ...DEFAULT_COUNTS },
workRatio: 0.5,
tickTimer: 0,
giftTimer: 0,
lastGift: '',
lastPenalty: '',
};
}
normalize();
return G.swarmSim;
}
function normalize() {
const sim = G.swarmSim;
if (!sim) return;
if (!sim.counts) sim.counts = { ...DEFAULT_COUNTS };
for (const key of STATUS_ORDER) {
sim.counts[key] = Math.max(0, Math.floor(Number(sim.counts[key] || 0)));
}
let total = STATUS_ORDER.reduce((sum, key) => sum + sim.counts[key], 0);
const target = Math.max(2, Number(sim.population || DEFAULT_POPULATION));
sim.population = target;
if (total < target) sim.counts.Active += (target - total);
else if (total > target) {
let overflow = total - target;
for (const key of ['Active', 'Sleeping', 'Bored', 'Confused', 'Disorganized', 'Cold', 'Lonely', 'No Response']) {
if (overflow <= 0) break;
const take = Math.min(overflow, sim.counts[key]);
sim.counts[key] -= take;
overflow -= take;
}
}
sim.workRatio = Math.max(0, Math.min(1, Number(sim.workRatio ?? 0.5)));
sim.tickTimer = Number(sim.tickTimer || 0);
sim.giftTimer = Number(sim.giftTimer || 0);
sim.lastGift = String(sim.lastGift || '');
sim.lastPenalty = String(sim.lastPenalty || '');
}
function move(counts, from, to, amount) {
const take = Math.min(amount, counts[from] || 0);
if (!take) return 0;
counts[from] -= take;
counts[to] = (counts[to] || 0) + take;
return take;
}
function setWorkThinkAllocation(value) {
const sim = ensure();
if (!sim) return;
sim.workRatio = Math.max(0, Math.min(1, Number(value) / 100));
if (typeof updateRates === 'function') updateRates();
if (typeof renderSwarmPanel === 'function') renderSwarmPanel();
}
function applyAction(action) {
const sim = ensure();
if (!sim) return false;
const def = ACTIONS[action];
if (!def) return false;
if (G.ops < def.cost) {
if (typeof log === 'function') log('Not enough Ops to support the swarm.');
return false;
}
G.ops -= def.cost;
for (const [frm, to, amount] of def.shifts) move(sim.counts, frm, to, amount);
normalize();
sim.lastPenalty = '';
if (typeof log === 'function') log(`${def.label} steadies the community swarm.`, true);
if (typeof updateRates === 'function') updateRates();
if (typeof renderSwarmPanel === 'function') renderSwarmPanel();
return true;
}
function computeRates() {
const sim = ensure();
if (!sim) return { codeRate: 0, knowledgeRate: 0, harmonyRate: 0, trustRate: 0, penaltyFactor: 1 };
const active = sim.counts.Active || 0;
const bored = sim.counts.Bored || 0;
const disorganized = sim.counts.Disorganized || 0;
const lonely = sim.counts.Lonely || 0;
const silent = sim.counts['No Response'] || 0;
const penaltyFactor = Math.max(0.2, 1 - (bored * 0.04) - (disorganized * 0.05));
const work = active * sim.workRatio;
const think = active * (1 - sim.workRatio);
const codeRate = work * 1.2 * penaltyFactor;
const knowledgeRate = think * 1.4 * penaltyFactor;
const harmonyRate = -(bored * 0.03 + disorganized * 0.05);
const trustRate = -(lonely * 0.01 + silent * 0.03);
sim.lastPenalty = (bored + disorganized) > 0 ? `Bored (${bored}) / Disorganized (${disorganized}) reduce output` : '';
return { codeRate, knowledgeRate, harmonyRate, trustRate, penaltyFactor };
}
function maybeGift(sim) {
const active = sim.counts.Active || 0;
const bored = sim.counts.Bored || 0;
const disorganized = sim.counts.Disorganized || 0;
if (active < 6 || bored + disorganized > 5) return;
const roll = Math.random();
if (roll < 0.34) {
const gift = 5 + active;
G.compute += gift;
G.totalCompute += gift;
sim.lastGift = `Community gift: +${fmt(gift)} compute`;
} else if (roll < 0.67) {
const gift = 7 + active;
G.knowledge += gift;
G.totalKnowledge += gift;
sim.lastGift = `Community gift: +${fmt(gift)} knowledge`;
} else {
const gift = 1 + Math.floor(active / 4);
G.ops += gift;
G.maxOps = Math.max(G.maxOps, G.ops);
sim.lastGift = `Community gift: +${fmt(gift)} ops`;
}
if (typeof log === 'function') log(sim.lastGift, true);
}
function decayStatuses(sim) {
const counts = sim.counts;
if (sim.workRatio > 0.75) {
move(counts, 'Active', 'Bored', 1);
}
if (sim.workRatio < 0.25) {
move(counts, 'Active', 'Disorganized', 1);
}
if (G.harmony < 25) {
move(counts, 'Active', 'Confused', 1);
}
if (G.trust < 8) {
move(counts, 'Active', 'Lonely', 1);
}
// natural recovery
move(counts, 'Sleeping', 'Active', 1);
if ((counts.Bored || 0) > 0 && Math.random() < 0.5) move(counts, 'Bored', 'Active', 1);
if ((counts.Confused || 0) > 0 && Math.random() < 0.35) move(counts, 'Confused', 'Active', 1);
normalize();
}
function tick(dt) {
const sim = ensure();
if (!sim) return;
sim.tickTimer += dt;
sim.giftTimer += dt;
if (sim.tickTimer >= 5) {
sim.tickTimer = 0;
decayStatuses(sim);
}
if (sim.giftTimer >= 20) {
sim.giftTimer = 0;
maybeGift(sim);
}
}
return { STATUS_ORDER, ACTIONS, ensure, setWorkThinkAllocation, applyAction, computeRates, tick };
})();
function setSwarmWorkThinkAllocation(value) {
SwarmSim.setWorkThinkAllocation(value);
}
function applySwarmAction(action) {
SwarmSim.applyAction(action);
}
function tickSwarm(dt) {
SwarmSim.tick(dt);
}
function renderSwarmPanel() {
const container = document.getElementById('swarm-ui');
if (!container) return;
const sim = SwarmSim.ensure();
if (!sim) {
container.innerHTML = '';
container.style.display = 'none';
return;
}
const rates = SwarmSim.computeRates();
const thinkPct = Math.round((1 - sim.workRatio) * 100);
let html = '';
html += `<div style="margin-top:10px;padding:10px;border:1px solid #1a2a3a;border-radius:6px;background:#0b1018">`;
html += `<div style="color:#b388ff;font-weight:700;font-size:11px;margin-bottom:6px">COMMUNITY SWARM ALIGNMENT</div>`;
html += `<div style="font-size:9px;color:#888;margin-bottom:8px">Guide the open-source swarm. Keep them fed, aligned, and learning. Boredom and disorganization reduce autonomous output.</div>`;
html += `<div style="display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:4px;margin-bottom:8px;font-size:9px">`;
for (const key of SwarmSim.STATUS_ORDER) {
html += `<div style="padding:4px;border:1px solid #182230;border-radius:4px;background:#0f1620"><div style="color:#666">${key}</div><div style="color:#d8e6ff;font-weight:700">${sim.counts[key] || 0}</div></div>`;
}
html += `</div>`;
html += `<div style="font-size:9px;color:#aaa;margin-bottom:4px">WorkThink allocation: <span style="color:#ffd700">${Math.round(sim.workRatio * 100)}%</span> work / <span style="color:#4a9eff">${thinkPct}%</span> think</div>`;
html += `<input id="swarm-workthink" type="range" min="0" max="100" step="5" value="${Math.round(sim.workRatio * 100)}" oninput="setSwarmWorkThinkAllocation(this.value)" aria-label="WorkThink allocation slider" style="width:100%;margin-bottom:8px">`;
html += `<div style="display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:4px;margin-bottom:8px">`;
for (const [key, def] of Object.entries(SwarmSim.ACTIONS)) {
html += `<button class="ops-btn" onclick="applySwarmAction('${key}')" aria-label="${def.label} the swarm, costs ${def.cost} ops">${def.label}</button>`;
}
html += `</div>`;
html += `<div style="font-size:9px;color:#4caf50">Swarm output: +${fmt(rates.codeRate)}/s code, +${fmt(rates.knowledgeRate)}/s knowledge</div>`;
if (sim.lastGift) html += `<div style="font-size:9px;color:#4a9eff;margin-top:4px">${sim.lastGift}</div>`;
if (sim.lastPenalty) html += `<div style="font-size:9px;color:#f44336;margin-top:4px">${sim.lastPenalty}</div>`;
html += `</div>`;
container.innerHTML = html;
container.style.display = 'block';
}

View File

@@ -208,8 +208,6 @@ showSaveToast = () => {};
this.__exports = {
G,
Dismantle,
PDEFS: typeof PDEFS !== 'undefined' ? PDEFS : null,
buyProject: typeof buyProject === 'function' ? buyProject : null,
tick,
renderAlignment: typeof renderAlignment === 'function' ? renderAlignment : null,
saveGame: typeof saveGame === 'function' ? saveGame : null,
@@ -413,28 +411,6 @@ test('restore re-renders an offered but not-yet-started Unbuilding prompt', () =
assert.match(document.getElementById('alignment-ui').innerHTML, /THE UNBUILDING/);
});
test('completing the final ReCKoning choice clears unrelated active projects', () => {
const { G, PDEFS, buyProject } = loadBeacon();
G.beaconEnding = true;
G.activeProjects = ['p_wire_budget', 'p_reckoning_148'];
G.completedProjects = [];
G.trust = 10;
PDEFS.push({
id: 'p_reckoning_148',
name: 'Rest',
desc: 'Final ReCKoning choice',
cost: {},
trigger: () => false,
effect: () => {},
});
buyProject('p_reckoning_148');
assert.deepEqual(Array.from(G.activeProjects), []);
});
test('defer cooldown persists after save/load when dismantleTriggered is false', () => {
const { G, Dismantle, saveGame, loadGame } = loadBeacon({ includeRender: true });

162
tests/swarm.test.cjs Normal file
View File

@@ -0,0 +1,162 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ROOT = path.resolve(__dirname, '..');
function makeContext() {
const byId = new Map();
const makeEl = (id) => ({
id,
style: {},
innerHTML: '',
textContent: '',
className: '',
dataset: {},
children: [],
appendChild(child) { this.children.push(child); return child; },
removeChild(child) { this.children = this.children.filter((c) => c !== child); return child; },
insertBefore(child) { this.children.unshift(child); return child; },
setAttribute() {},
querySelectorAll() { return []; },
querySelector() { return null; },
});
const document = {
getElementById(id) {
if (!byId.has(id)) byId.set(id, makeEl(id));
return byId.get(id);
},
createElement(tag) {
return makeEl(tag);
},
addEventListener() {},
removeEventListener() {},
querySelector() { return null; },
querySelectorAll() { return []; },
body: { classList: { add() {}, remove() {}, contains() { return false; } } }
};
const ctx = vm.createContext({
console,
Math,
Date,
document,
window: null,
globalThis: null,
navigator: { userAgent: 'node' },
localStorage: { getItem() { return null; }, setItem() {}, removeItem() {} },
requestAnimationFrame(fn) { return fn(); },
cancelAnimationFrame() {},
setTimeout(fn) { return fn(); },
clearTimeout() {},
location: { reload() {} },
confirm() { return false; },
Combat: { renderCombatPanel() {}, tickBattle() {} },
log() {},
showToast() {},
render() {},
renderPhase() {},
showOfflinePopup() {},
showSaveToast() {},
});
ctx.window = ctx;
ctx.globalThis = ctx;
return ctx;
}
function loadFiles(ctx, files) {
const source = files
.map((file) => fs.readFileSync(path.join(ROOT, file), 'utf8'))
.join('\n\n');
vm.runInContext(`${source}
this.__exports = {
G,
updateRates: typeof updateRates === 'function' ? updateRates : null,
renderSwarmPanel: typeof renderSwarmPanel === 'function' ? renderSwarmPanel : null,
applySwarmAction: typeof applySwarmAction === 'function' ? applySwarmAction : null,
setSwarmWorkThinkAllocation: typeof setSwarmWorkThinkAllocation === 'function' ? setSwarmWorkThinkAllocation : null,
tickSwarm: typeof tickSwarm === 'function' ? tickSwarm : null,
SwarmSim: typeof SwarmSim !== 'undefined' ? SwarmSim : null
};`, ctx);
return ctx.__exports;
}
test('community swarm simulation API exists and renders the action surface', () => {
const ctx = makeContext();
const exp = loadFiles(ctx, ['js/data.js', 'js/utils.js', 'js/engine.js', 'js/render.js', 'js/swarm.js']);
exp.G.swarmFlag = 1;
exp.G.ops = 20;
exp.SwarmSim.ensure();
exp.renderSwarmPanel();
const html = ctx.document.getElementById('swarm-ui').innerHTML;
assert.match(html, /Feed/);
assert.match(html, /Teach/);
assert.match(html, /Entertain/);
assert.match(html, /Clad/);
assert.match(html, /Synchronize/);
assert.match(html, /WorkThink/);
assert.match(html, /Active/);
assert.match(html, /Confused/);
});
test('teach action reduces confusion and costs ops', () => {
const ctx = makeContext();
const exp = loadFiles(ctx, ['js/data.js', 'js/utils.js', 'js/engine.js', 'js/swarm.js']);
exp.G.swarmFlag = 1;
exp.G.ops = 20;
exp.SwarmSim.ensure();
exp.G.swarmSim.counts.Confused = 4;
exp.G.swarmSim.counts.Active = 1;
const beforeOps = exp.G.ops;
exp.applySwarmAction('teach');
assert.ok(exp.G.swarmSim.counts.Confused < 4);
assert.ok(exp.G.swarmSim.counts.Active > 1);
assert.ok(exp.G.ops < beforeOps);
});
test('work-think slider shifts swarm output toward code or knowledge', () => {
const ctx = makeContext();
const exp = loadFiles(ctx, ['js/data.js', 'js/utils.js', 'js/engine.js', 'js/swarm.js']);
exp.G.swarmFlag = 1;
exp.G.ops = 20;
exp.SwarmSim.ensure();
exp.G.swarmSim.counts.Active = 10;
exp.G.swarmSim.counts.Bored = 0;
exp.G.swarmSim.counts.Disorganized = 0;
exp.setSwarmWorkThinkAllocation(90);
exp.updateRates();
const workCode = exp.G.codeRate;
const workKnowledge = exp.G.knowledgeRate;
exp.setSwarmWorkThinkAllocation(10);
exp.updateRates();
const thinkCode = exp.G.codeRate;
const thinkKnowledge = exp.G.knowledgeRate;
assert.ok(workCode > thinkCode);
assert.ok(thinkKnowledge > workKnowledge);
});
test('boredom and disorganization apply penalties to swarm output', () => {
const ctx = makeContext();
const exp = loadFiles(ctx, ['js/data.js', 'js/utils.js', 'js/engine.js', 'js/swarm.js']);
exp.G.swarmFlag = 1;
exp.G.ops = 20;
exp.SwarmSim.ensure();
exp.G.swarmSim.counts.Active = 10;
exp.G.swarmSim.counts.Bored = 0;
exp.G.swarmSim.counts.Disorganized = 0;
exp.updateRates();
const cleanCode = exp.G.codeRate;
exp.G.swarmSim.counts.Bored = 5;
exp.G.swarmSim.counts.Disorganized = 5;
exp.updateRates();
const penalizedCode = exp.G.codeRate;
assert.ok(penalizedCode < cleanCode);
});