Compare commits

..

1 Commits

Author SHA1 Message Date
Alexander Whitestone
6fe317fc2a feat: strategy engine tournaments for paperclips study (#5)
Some checks failed
Accessibility Checks / a11y-audit (pull_request) Successful in 12s
Smoke Test / smoke (pull_request) Failing after 22s
2026-04-14 23:29:59 -04:00
7 changed files with 356 additions and 572 deletions

View File

@@ -212,7 +212,6 @@ Events Resolved: <span id="st-resolved">0</span>
<div id="strategy-panel" style="margin:0 16px 16px;background:var(--panel);border:1px solid var(--border);border-radius:6px;padding:12px;border-left:3px solid var(--gold)">
<h3>SOVEREIGN GUIDANCE (GOFAI)</h3>
<div id="strategy-recommendation" style="font-size:11px;color:var(--gold);font-style:italic">Analyzing system state...</div>
<div id="strategy-tournament-ui" style="margin-top:10px"></div>
</div>
<div id="combat-panel" style="margin:0 16px 16px;background:var(--panel);border:1px solid var(--border);border-radius:6px;padding:12px;border-left:3px solid var(--red)">
<h3>REASONING BATTLES</h3>

View File

@@ -43,7 +43,6 @@ const G = {
trust: 5,
creativity: 0,
harmony: 50,
yomi: 0,
// Totals
totalCode: 0,
@@ -52,7 +51,6 @@ const G = {
totalUsers: 0,
totalImpact: 0,
totalRescues: 0,
totalYomi: 0,
// Rates (calculated each tick)
codeRate: 0,
@@ -65,7 +63,6 @@ const G = {
trustRate: 0,
creativityRate: 0,
harmonyRate: 0,
yomiKnowledgeRate: 0,
// Buildings (count-based, like Paperclips' clipmakerLevel)
buildings: {
@@ -107,7 +104,6 @@ const G = {
beaconFlag: 0,
memoryFlag: 0,
pactFlag: 0,
strategicFlag: 0,
swarmFlag: 0,
swarmRate: 0,
@@ -119,11 +115,6 @@ const G = {
tick: 0,
saveTimer: 0,
secTimer: 0,
strategyAutoUnlocked: false,
strategyAutoEnabled: false,
strategyTournamentTimer: 0,
strategyTournamentInterval: 30,
strategyLastTournament: null,
// Systems
projects: [],
@@ -177,7 +168,14 @@ const G = {
dismantleResourceIndex: 0,
dismantleResourceTimer: 0,
dismantleDeferUntilAt: 0,
dismantleComplete: false
dismantleComplete: false,
// Strategy Engine / Game Theory tournaments (#5)
strategyPoints: 0,
autoTournamentUnlocked: false,
autoTournamentEnabled: false,
strategyLastRunAt: 0,
strategyLeaderboard: []
};
// === PHASE DEFINITIONS ===
@@ -603,6 +601,18 @@ const PDEFS = [
trigger: () => G.totalKnowledge >= 15000 && G.totalUsers >= 1000,
effect: () => { G.strategicFlag = 1; log('Strategy engine online. The model now thinks about thinking.'); }
},
{
id: 'p_auto_tournament',
name: 'Auto-Tournament Mode',
desc: 'Spend creativity to run repeated strategy tournaments and turn Yomi into knowledge.',
cost: { creativity: 50000 },
trigger: () => G.strategicFlag === 1 && G.creativity >= 50000 && !G.autoTournamentUnlocked,
effect: () => {
G.autoTournamentUnlocked = true;
log('Auto-tournament mode unlocked. The model studies itself through strategic play.');
},
milestone: true
},
// SWARM PROTOCOL — auto-code from buildings
{

View File

@@ -2,7 +2,7 @@ function updateRates() {
// Reset all rates
G.codeRate = 0; G.computeRate = 0; G.knowledgeRate = 0;
G.userRate = 0; G.impactRate = 0; G.rescuesRate = 0; G.opsRate = 0; G.trustRate = 0;
G.creativityRate = 0; G.harmonyRate = 0; G.yomiKnowledgeRate = 0;
G.creativityRate = 0; G.harmonyRate = 0;
// Apply building rates
for (const def of BDEF) {
@@ -29,12 +29,6 @@ function updateRates() {
}
if (G.pactFlag) G.trustRate += 2;
// Yomi turns tournament insight into passive knowledge
if (G.strategicFlag && G.yomi > 0) {
G.yomiKnowledgeRate = Math.sqrt(G.yomi) * 0.25;
G.knowledgeRate += G.yomiKnowledgeRate;
}
// Harmony: each wizard building contributes or detracts
const wizardCount = (G.buildings.bezalel || 0) + (G.buildings.allegro || 0) + (G.buildings.ezra || 0) +
(G.buildings.timmy || 0) + (G.buildings.fenrir || 0) + (G.buildings.bilbo || 0);
@@ -190,11 +184,6 @@ function tick() {
// Sprint ability
tickSprint(dt);
// Strategy tournaments can run on an auto-timer once unlocked
if (window.SSE && typeof window.SSE.tick === 'function') {
window.SSE.tick(dt);
}
// Auto-typer: buildings produce actual clicks, not just passive rate
// Each autocoder level auto-types once per interval, giving visual feedback
if (G.buildings.autocoder > 0) {
@@ -218,6 +207,11 @@ function tick() {
// Combat: tick battle simulation
Combat.tickBattle(dt);
// Strategy engine auto-tournaments
if (window.SSE && typeof window.SSE.tick === 'function') {
window.SSE.tick(dt);
}
// Check milestones
checkMilestones();
@@ -1311,11 +1305,6 @@ function renderProductionBreakdown() {
contributions.push({ name: 'Allegro (idle)', count: 0, rate: -10 * G.buildings.allegro });
}
// Tournament Yomi feeds passive knowledge generation
if (res.key === 'knowledge' && G.yomiKnowledgeRate > 0) {
contributions.push({ name: 'Yomi insights', count: 0, rate: G.yomiKnowledgeRate });
}
// Show delta: total rate minus what we accounted for
const accounted = contributions.reduce((s, c) => s + c.rate, 0);
let delta = totalRate - accounted;

View File

@@ -27,13 +27,10 @@ function renderClickPower() {
}
function renderStrategy() {
if (!window.SSE) return;
window.SSE.update();
const el = document.getElementById('strategy-recommendation');
if (el) el.textContent = window.SSE.getRecommendation();
const panel = document.getElementById('strategy-tournament-ui');
if (panel && typeof window.SSE.getPanelHtml === 'function') {
panel.innerHTML = window.SSE.getPanelHtml();
if (window.SSE) {
window.SSE.update();
const el = document.getElementById('strategy-recommendation');
if (el) el.innerHTML = window.SSE.getPanelHtml();
}
}
@@ -200,9 +197,9 @@ function saveGame() {
const saveData = {
version: 1,
code: G.code, compute: G.compute, knowledge: G.knowledge, users: G.users, impact: G.impact,
ops: G.ops, trust: G.trust, creativity: G.creativity, harmony: G.harmony, yomi: G.yomi || 0,
ops: G.ops, trust: G.trust, creativity: G.creativity, harmony: G.harmony,
totalCode: G.totalCode, totalCompute: G.totalCompute, totalKnowledge: G.totalKnowledge,
totalUsers: G.totalUsers, totalImpact: G.totalImpact, totalYomi: G.totalYomi || 0,
totalUsers: G.totalUsers, totalImpact: G.totalImpact,
buildings: G.buildings,
codeBoost: G.codeBoost, computeBoost: G.computeBoost, knowledgeBoost: G.knowledgeBoost,
userBoost: G.userBoost, impactBoost: G.impactBoost,
@@ -229,11 +226,11 @@ function saveGame() {
swarmFlag: G.swarmFlag || 0,
swarmRate: G.swarmRate || 0,
strategicFlag: G.strategicFlag || 0,
strategyAutoUnlocked: G.strategyAutoUnlocked || false,
strategyAutoEnabled: G.strategyAutoEnabled || false,
strategyTournamentTimer: G.strategyTournamentTimer || 0,
strategyTournamentInterval: G.strategyTournamentInterval || 30,
strategyLastTournament: G.strategyLastTournament || null,
strategyPoints: G.strategyPoints || 0,
autoTournamentUnlocked: G.autoTournamentUnlocked || false,
autoTournamentEnabled: G.autoTournamentEnabled || false,
strategyLastRunAt: G.strategyLastRunAt || 0,
strategyLeaderboard: G.strategyLeaderboard || [],
projectsCollapsed: G.projectsCollapsed !== false,
dismantleTriggered: G.dismantleTriggered || false,
dismantleActive: G.dismantleActive || false,
@@ -262,8 +259,8 @@ function loadGame() {
// Whitelist properties that can be loaded
const whitelist = [
'code', 'compute', 'knowledge', 'users', 'impact', 'ops', 'trust', 'creativity', 'harmony', 'yomi',
'totalCode', 'totalCompute', 'totalKnowledge', 'totalUsers', 'totalImpact', 'totalYomi',
'code', 'compute', 'knowledge', 'users', 'impact', 'ops', 'trust', 'creativity', 'harmony',
'totalCode', 'totalCompute', 'totalKnowledge', 'totalUsers', 'totalImpact',
'buildings', 'codeBoost', 'computeBoost', 'knowledgeBoost', 'userBoost', 'impactBoost',
'milestoneFlag', 'phase', 'deployFlag', 'sovereignFlag', 'beaconFlag',
'memoryFlag', 'pactFlag', 'lazarusFlag', 'mempalaceFlag', 'ciFlag',
@@ -273,8 +270,9 @@ function loadGame() {
'drift', 'driftEnding', 'beaconEnding', 'pendingAlignment',
'lastEventAt', 'totalEventsResolved', 'buyAmount',
'sprintActive', 'sprintTimer', 'sprintCooldown',
'swarmFlag', 'swarmRate', 'strategicFlag', 'strategyAutoUnlocked', 'strategyAutoEnabled',
'strategyTournamentTimer', 'strategyTournamentInterval', 'strategyLastTournament', 'projectsCollapsed',
'swarmFlag', 'swarmRate', 'strategicFlag',
'strategyPoints', 'autoTournamentUnlocked', 'autoTournamentEnabled',
'strategyLastRunAt', 'strategyLeaderboard', 'projectsCollapsed',
'dismantleTriggered', 'dismantleActive', 'dismantleStage',
'dismantleResourceIndex', 'dismantleResourceTimer', 'dismantleDeferUntilAt', 'dismantleComplete'
];

View File

@@ -1,424 +1,257 @@
/**
* Sovereign Strategy Engine (SSE)
* A rule-based GOFAI system for optimal play guidance plus
* Paperclips-inspired game theory tournaments that generate Yomi.
* Game theory tournament runner inspired by Universal Paperclips.
*/
const PAYOFFS = {
CC: [3, 3],
CD: [0, 5],
DC: [5, 0],
DD: [1, 1],
};
const STRATEGY_LIBRARY = {
cooperate: {
id: 'cooperate',
name: 'Always Cooperate',
tier: 0,
move() { return 'C'; },
},
defect: {
id: 'defect',
name: 'Always Defect',
tier: 0,
move() { return 'D'; },
},
random: {
id: 'random',
name: 'Random',
tier: 0,
move() { return Math.random() < 0.5 ? 'C' : 'D'; },
},
tit_for_tat: {
id: 'tit_for_tat',
name: 'Tit for Tat',
tier: 0,
move(selfHistory, oppHistory) {
return oppHistory.length ? oppHistory[oppHistory.length - 1] : 'C';
},
},
generous: {
id: 'generous',
name: 'Generous Tit for Tat',
tier: 1,
move(selfHistory, oppHistory) {
if (!oppHistory.length) return 'C';
return oppHistory[oppHistory.length - 1] === 'D' && Math.random() < 0.3
? 'C'
: oppHistory[oppHistory.length - 1];
},
},
greedy: {
id: 'greedy',
name: 'Greedy',
tier: 1,
move(selfHistory, oppHistory) {
if (!oppHistory.length) return 'D';
const coop = oppHistory.filter((m) => m === 'C').length;
return coop >= oppHistory.length / 2 ? 'D' : 'C';
},
},
grim: {
id: 'grim',
name: 'Grim Trigger',
tier: 2,
move(selfHistory, oppHistory) {
return oppHistory.includes('D') ? 'D' : 'C';
},
},
minimax: {
id: 'minimax',
name: 'Minimax',
tier: 2,
move(selfHistory, oppHistory) {
const oppDefections = oppHistory.filter((m) => m === 'D').length;
const oppCoop = oppHistory.length - oppDefections;
return oppDefections > oppCoop ? 'D' : 'C';
},
},
};
const STRATEGY_RULES = [
{
id: 'use_ops',
priority: 100,
condition: () => G.ops >= G.maxOps * 0.9,
recommendation: () => 'Operations near capacity. Convert Ops to Code or Knowledge now.'
},
{
id: 'resolve_events',
priority: 95,
condition: () => G.activeDebuffs && G.activeDebuffs.length > 0,
recommendation: () => 'System anomalies detected. Resolve active events to restore rates.'
},
{
id: 'activate_sprint',
priority: 90,
condition: () => G.sprintCooldown === 0 && !G.sprintActive && G.codeRate > 10,
recommendation: () => 'Code Sprint available. Activate for 10x production burst.'
},
{
id: 'pact_alignment',
priority: 85,
condition: () => G.pendingAlignment,
recommendation: () => 'Alignment decision pending. Consider the long-term impact of The Pact.'
recommendation: 'Operations near capacity. Convert Ops to Code or Knowledge now.'
},
{
id: 'buy_autocoder',
priority: 80,
condition: () => G.phase === 1 && (G.buildings.autocoder || 0) < 10 && canAffordBuilding('autocoder'),
recommendation: () => 'Prioritize AutoCoders to establish passive code production.'
recommendation: 'Prioritize AutoCoders to establish passive code production.'
},
{
id: 'unlock_auto_tournaments',
priority: 72,
condition: () => G.strategicFlag === 1 && !G.strategyAutoUnlocked && G.creativity >= 50000,
recommendation: () => 'Auto-Tournament mode is affordable. Spend 50k creativity to automate Yomi generation.'
id: 'activate_sprint',
priority: 90,
condition: () => G.sprintCooldown === 0 && !G.sprintActive && G.codeRate > 10,
recommendation: 'Code Sprint available. Activate for 10x production burst.'
},
{
id: 'run_tournament',
priority: 68,
condition: () => G.strategicFlag === 1 && (!G.strategyLastTournament || !G.strategyLastTournament.scoreboard || G.strategyLastTournament.scoreboard.length === 0),
recommendation: () => 'Run a game theory tournament. Tournament Yomi becomes passive knowledge.'
id: 'resolve_events',
priority: 95,
condition: () => G.activeDebuffs && G.activeDebuffs.length > 0,
recommendation: 'System anomalies detected. Resolve active events to restore rates.'
},
{
id: 'pact_alignment',
priority: 85,
condition: () => G.pendingAlignment,
recommendation: 'Alignment decision pending. Consider the long-term impact of The Pact.'
},
{
id: 'strategy_engine',
priority: 70,
condition: () => G.strategicFlag === 1 && !G.autoTournamentUnlocked && G.creativity >= 50000,
recommendation: 'Creativity is high enough to unlock Auto-Tournament Mode. Convert creativity into strategic knowledge.'
},
{
id: 'auto_tournament',
priority: 65,
condition: () => G.autoTournamentUnlocked && !G.autoTournamentEnabled,
recommendation: 'Auto-Tournament Mode is unlocked but idle. Start it to farm Yomi into knowledge.'
},
{
id: 'save_game',
priority: 10,
condition: () => (Date.now() - (G.lastSaveTime || 0)) > 300000,
recommendation: () => 'Unsaved progress detected. Manual save recommended.'
recommendation: 'Unsaved progress detected. Manual save recommended.'
}
];
const TOURNAMENT_PAYOFFS = {
CC: [3, 3],
CD: [0, 5],
DC: [5, 0],
DD: [1, 1]
};
const STRATEGY_TACTICS = [
{
id: 'RANDOM',
label: 'RANDOM',
desc: 'Deterministic pseudo-random mix of cooperation and defection.',
unlock: () => G.strategicFlag === 1,
move(ctx) {
return ((ctx.round * 7 + ctx.selfHistory.length * 3 + ctx.opponentHistory.length) % 2 === 0) ? 'C' : 'D';
}
},
{
id: 'A100',
label: 'A100',
desc: 'Always cooperates.',
unlock: () => G.strategicFlag === 1,
move() {
return 'C';
}
},
{
id: 'B100',
label: 'B100',
desc: 'Always defects.',
unlock: () => G.strategicFlag === 1,
move() {
return 'D';
}
},
{
id: 'GREEDY',
label: 'GREEDY',
desc: 'Presses for short-term gain and exploits soft opponents.',
unlock: () => G.strategicFlag === 1,
move(ctx) {
if (ctx.round < 2) return 'D';
const recent = ctx.opponentHistory.slice(-2);
return recent.every((move) => move === 'D') ? 'C' : 'D';
}
},
{
id: 'GENEROUS',
label: 'GENEROUS',
desc: 'Defaults to cooperation and only retaliates after repeated betrayal.',
unlock: () => G.strategicFlag === 1 && G.trust >= 20,
move(ctx) {
if (ctx.round === 0) return 'C';
const recentDefects = ctx.opponentHistory.slice(-3).filter((move) => move === 'D').length;
return recentDefects >= 2 ? 'D' : 'C';
}
},
{
id: 'TIT_FOR_TAT',
label: 'TIT FOR TAT',
desc: 'Cooperate first, then mirror the opponent.',
unlock: () => G.strategicFlag === 1 && G.totalImpact >= 1000,
move(ctx) {
if (ctx.round === 0) return 'C';
return ctx.opponentLast || 'C';
}
},
{
id: 'BEAT_LAST',
label: 'BEAT LAST',
desc: 'Attempts to counter the opponents last move.',
unlock: () => G.strategicFlag === 1 && G.yomi >= 100,
move(ctx) {
if (ctx.round === 0) return 'D';
return ctx.opponentLast === 'C' ? 'D' : 'C';
}
},
{
id: 'MINIMAX',
label: 'MINIMAX',
desc: 'Optimizes against the opponents worst plausible branch.',
unlock: () => G.strategicFlag === 1 && G.yomi >= 400,
move(ctx) {
if (ctx.round === 0) return 'C';
const coopRate = ctx.opponentHistory.length === 0
? 0.5
: ctx.opponentHistory.filter((move) => move === 'C').length / ctx.opponentHistory.length;
return coopRate >= 0.6 ? 'C' : 'D';
}
}
];
function normalizeMove(move) {
return move === 'D' ? 'D' : 'C';
}
function payoffFor(aMove, bMove) {
return TOURNAMENT_PAYOFFS[aMove + bMove] || TOURNAMENT_PAYOFFS.CC;
}
function makeScoreRow(strategy) {
return {
id: strategy.id,
label: strategy.label,
score: 0,
wins: 0,
matches: 0,
cooperation: 0,
defection: 0
};
}
class StrategyEngine {
constructor() {
this.currentRecommendation = null;
this.matchRounds = 12;
}
getYomiInsightRate() {
if (!G.strategicFlag || !G.yomi) return 0;
return Math.sqrt(G.yomi) * 0.25;
this.lastTournament = null;
this.autoTimer = 0;
this.intervalSeconds = 30;
}
getUnlockedStrategies() {
if (!G.strategicFlag) return [];
return STRATEGY_TACTICS.filter((strategy) => strategy.unlock());
const knowledge = G.totalKnowledge || 0;
return Object.values(STRATEGY_LIBRARY).filter((strategy) => {
if (strategy.tier === 0) return G.strategicFlag === 1;
if (strategy.tier === 1) return G.strategicFlag === 1 && knowledge >= 20000;
return G.strategicFlag === 1 && knowledge >= 50000;
});
}
playMatch(strategyA, strategyB) {
const historyA = [];
const historyB = [];
let scoreA = 0;
let scoreB = 0;
let cooperationMoments = 0;
for (let round = 0; round < this.matchRounds; round++) {
const moveA = normalizeMove(strategyA.move({
round,
selfHistory: historyA.slice(),
opponentHistory: historyB.slice(),
selfLast: historyA[historyA.length - 1] || null,
opponentLast: historyB[historyB.length - 1] || null
}));
const moveB = normalizeMove(strategyB.move({
round,
selfHistory: historyB.slice(),
opponentHistory: historyA.slice(),
selfLast: historyB[historyB.length - 1] || null,
opponentLast: historyA[historyA.length - 1] || null
}));
const [gainA, gainB] = payoffFor(moveA, moveB);
scoreA += gainA;
scoreB += gainB;
if (moveA === 'C') cooperationMoments += 1;
if (moveB === 'C') cooperationMoments += 1;
historyA.push(moveA);
historyB.push(moveB);
}
return {
aId: strategyA.id,
aLabel: strategyA.label,
bId: strategyB.id,
bLabel: strategyB.label,
scoreA,
scoreB,
cooperationMoments,
winner: scoreA === scoreB ? 'DRAW' : (scoreA > scoreB ? strategyA.id : strategyB.id)
};
playRound(a, b, aHistory, bHistory) {
const moveA = a.move(aHistory, bHistory);
const moveB = b.move(bHistory, aHistory);
const [scoreA, scoreB] = PAYOFFS[moveA + moveB] || [0, 0];
aHistory.push(moveA);
bHistory.push(moveB);
return { moveA, moveB, scoreA, scoreB };
}
runTournament(isAutomatic = false) {
runTournament(rounds = 10) {
const unlocked = this.getUnlockedStrategies();
if (unlocked.length < 2) {
return null;
}
const scores = Object.fromEntries(unlocked.map((strategy) => [strategy.id, makeScoreRow(strategy)]));
const matches = [];
const board = unlocked.map((s) => ({ id: s.id, name: s.name, score: 0, wins: 0, matches: 0 }));
for (let i = 0; i < unlocked.length; i++) {
for (let j = i + 1; j < unlocked.length; j++) {
const match = this.playMatch(unlocked[i], unlocked[j]);
matches.push(match);
const rowA = scores[match.aId];
const rowB = scores[match.bId];
rowA.score += match.scoreA;
rowB.score += match.scoreB;
rowA.matches += 1;
rowB.matches += 1;
rowA.cooperation += this.matchRounds - match.scoreA < this.matchRounds ? match.cooperationMoments / 2 : 0;
rowB.cooperation += this.matchRounds - match.scoreB < this.matchRounds ? match.cooperationMoments / 2 : 0;
rowA.defection = rowA.matches * this.matchRounds - rowA.cooperation;
rowB.defection = rowB.matches * this.matchRounds - rowB.cooperation;
if (match.winner === match.aId) rowA.wins += 1;
if (match.winner === match.bId) rowB.wins += 1;
const a = unlocked[i];
const b = unlocked[j];
const aHistory = [];
const bHistory = [];
let aScore = 0;
let bScore = 0;
for (let round = 0; round < rounds; round++) {
const result = this.playRound(a, b, aHistory, bHistory);
aScore += result.scoreA;
bScore += result.scoreB;
}
const aRow = board.find((row) => row.id === a.id);
const bRow = board.find((row) => row.id === b.id);
aRow.score += aScore;
bRow.score += bScore;
aRow.matches += 1;
bRow.matches += 1;
if (aScore > bScore) aRow.wins += 1;
else if (bScore > aScore) bRow.wins += 1;
}
}
const scoreboard = Object.values(scores).sort((a, b) => {
if (b.score !== a.score) return b.score - a.score;
if (b.wins !== a.wins) return b.wins - a.wins;
return a.label.localeCompare(b.label);
});
const strategicDepth = matches.reduce((sum, match) => {
return sum + Math.abs(match.scoreA - match.scoreB) + match.cooperationMoments;
}, 0);
const yomiAward = Math.max(10, Math.round(strategicDepth / Math.max(1, unlocked.length)));
const knowledgeGain = Math.max(25, Math.round(yomiAward * 2));
const leader = scoreboard[0];
G.totalYomi = Math.max(G.totalYomi || 0, G.yomi || 0) + yomiAward;
G.yomi += yomiAward;
G.knowledge += knowledgeGain;
G.totalKnowledge += knowledgeGain;
G.strategyTournamentTimer = 0;
G.strategyLastTournament = {
leader: { id: leader.id, label: leader.label, score: leader.score, wins: leader.wins },
scoreboard: scoreboard.map((row) => ({
id: row.id,
label: row.label,
score: row.score,
wins: row.wins,
matches: row.matches
})),
matchCount: matches.length,
yomiAward,
knowledgeGain,
automatic: Boolean(isAutomatic),
timestamp: Date.now()
};
if (typeof log === 'function') {
log(`Strategy tournament complete. ${leader.label} leads. +${fmt(yomiAward)} Yomi, +${fmt(knowledgeGain)} knowledge.`, true);
}
if (typeof showToast === 'function') {
showToast(`Tournament: ${leader.label} leads (+${fmt(yomiAward)} Yomi)`, 'project', 5000);
}
return G.strategyLastTournament;
board.sort((left, right) => right.score - left.score || right.wins - left.wins);
this.lastTournament = board;
return board;
}
unlockAutoTournament() {
if (!G.strategicFlag) return false;
if (!G.strategyAutoUnlocked) {
if (G.creativity < 50000) {
if (typeof log === 'function') log(`Need ${fmt(50000)} creativity to unlock auto-tournaments.`);
return false;
}
G.creativity -= 50000;
G.strategyAutoUnlocked = true;
G.strategyAutoEnabled = true;
G.strategyTournamentTimer = 0;
if (typeof log === 'function') log('Auto-Tournament mode unlocked. Yomi generation is now automated.', true);
if (typeof showToast === 'function') showToast('Auto-Tournament mode unlocked', 'milestone', 5000);
return true;
}
G.strategyAutoEnabled = !G.strategyAutoEnabled;
if (typeof log === 'function') {
log(`Auto-Tournament mode ${G.strategyAutoEnabled ? 'enabled' : 'disabled'}.`);
}
return true;
toggleAutoTournament() {
if (!G.autoTournamentUnlocked) return false;
G.autoTournamentEnabled = !G.autoTournamentEnabled;
return G.autoTournamentEnabled;
}
tick(dt) {
if (!G.strategicFlag || !G.strategyAutoEnabled) return false;
G.strategyTournamentTimer = (G.strategyTournamentTimer || 0) + dt;
if (G.strategyTournamentTimer < (G.strategyTournamentInterval || 30)) return false;
return this.runTournament(true);
}
getPanelHtml() {
if (!G.strategicFlag) {
return '<div class="dim">Research the Strategy Engine to unlock tournaments, Yomi, and adversarial modeling.</div>';
}
const unlocked = this.getUnlockedStrategies();
const unlockedIds = new Set(unlocked.map((strategy) => strategy.id));
const yomiRate = this.getYomiInsightRate();
const autoLabel = !G.strategyAutoUnlocked
? 'UNLOCK AUTO-TOURNAMENT (50K CREATIVITY)'
: (G.strategyAutoEnabled ? 'DISABLE AUTO-TOURNAMENT' : 'ENABLE AUTO-TOURNAMENT');
const autoHint = !G.strategyAutoUnlocked
? `Creativity: ${fmt(G.creativity)} / ${fmt(50000)}`
: `Runs every ${Math.floor(G.strategyTournamentInterval || 30)}s • Timer ${Math.floor(G.strategyTournamentTimer || 0)}s`;
let chips = '';
for (const strategy of STRATEGY_TACTICS) {
const unlockedNow = unlockedIds.has(strategy.id);
chips += `<span class="milestone-chip${unlockedNow ? ' done' : ''}" style="opacity:${unlockedNow ? '1' : '0.45'}">${strategy.label}</span>`;
}
let scoreboardHtml = '<div class="dim" style="margin-top:8px">Run a tournament to generate Yomi and compare strategies.</div>';
if (G.strategyLastTournament && Array.isArray(G.strategyLastTournament.scoreboard) && G.strategyLastTournament.scoreboard.length > 0) {
const rows = G.strategyLastTournament.scoreboard
.map((row) => `<tr><td style="padding:3px 6px 3px 0;color:#c0c0d0">${row.label}</td><td style="padding:3px 6px;text-align:right;color:#ffd700">${fmt(row.score)}</td><td style="padding:3px 0 3px 6px;text-align:right;color:#4caf50">${row.wins}</td></tr>`)
.join('');
scoreboardHtml = `
<div style="margin-top:10px;padding:8px;border:1px solid var(--border);border-radius:6px;background:#0a0a14">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
<span style="color:#ffd700;font-size:10px;letter-spacing:1px">LAST TOURNAMENT</span>
<span style="font-size:9px;color:#666">${G.strategyLastTournament.automatic ? 'AUTO' : 'MANUAL'}</span>
</div>
<div style="font-size:10px;color:#aaa;margin-bottom:6px">LEADER: <span style="color:#ffd700">${G.strategyLastTournament.leader.label}</span> • +${fmt(G.strategyLastTournament.yomiAward)} Yomi • +${fmt(G.strategyLastTournament.knowledgeGain)} knowledge</div>
<table style="width:100%;font-size:10px;border-collapse:collapse">
<thead>
<tr style="color:#555;text-align:left"><th style="padding:0 6px 4px 0">Strategy</th><th style="padding:0 6px 4px;text-align:right">Score</th><th style="padding:0 0 4px 6px;text-align:right">Wins</th></tr>
</thead>
<tbody>${rows}</tbody>
</table>
</div>`;
}
return `
<div style="margin-top:10px;padding-top:10px;border-top:1px solid var(--border)">
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:6px;margin-bottom:8px">
<div class="res" style="padding:8px">
<div class="r-label">Yomi</div>
<div class="r-val" style="font-size:14px">${fmt(G.yomi || 0)}</div>
<div class="r-rate">+${fmt(yomiRate)}/s knowledge</div>
</div>
<div class="res" style="padding:8px">
<div class="r-label">Unlocked</div>
<div class="r-val" style="font-size:14px">${unlocked.length}/8</div>
<div class="r-rate">${G.strategyAutoEnabled ? 'AUTO MODE' : 'MANUAL'}</div>
</div>
</div>
<div class="action-btn-group">
<button class="ops-btn" onclick="window.SSE.runTournament()" style="border-color:var(--gold);color:var(--gold)" aria-label="Run a strategy tournament to generate Yomi">RUN TOURNAMENT</button>
<button class="ops-btn" onclick="window.SSE.unlockAutoTournament()" style="border-color:var(--purple);color:var(--purple)" aria-label="${autoLabel}">${autoLabel}</button>
</div>
<div style="font-size:9px;color:#666;margin-top:4px">${autoHint}</div>
<div style="font-size:9px;color:#888;margin-top:8px;line-height:1.6">Game theory tournaments generate Yomi. Yomi is reinvested as passive knowledge, turning adversarial modeling into insight.</div>
<div class="milestone-row" style="justify-content:flex-start;margin-top:8px">${chips}</div>
${scoreboardHtml}
</div>`;
if (!G.autoTournamentUnlocked || !G.autoTournamentEnabled) return;
this.autoTimer += dt;
if (this.autoTimer < this.intervalSeconds) return;
this.autoTimer = 0;
const board = this.runTournament(12);
if (!board.length) return;
const top = board[0];
const yomi = Math.max(1, Math.floor(top.score / 10));
G.strategyPoints = (G.strategyPoints || 0) + yomi;
G.knowledge += yomi;
G.totalKnowledge += yomi;
G.strategyLeaderboard = board.slice(0, 4).map((row) => ({ ...row }));
G.strategyLastRunAt = Date.now();
if (typeof log === 'function') log(`Strategy tournament complete. ${top.name} wins. +${yomi} Yomi`, true);
if (typeof showToast === 'function') showToast(`Tournament complete: ${top.name} +${yomi} Yomi`, 'milestone', 4000);
}
update() {
const activeRules = STRATEGY_RULES.filter((rule) => rule.condition());
activeRules.sort((a, b) => b.priority - a.priority);
this.currentRecommendation = activeRules.length > 0
? activeRules[0].recommendation
: 'System stable. Continue writing code.';
if (activeRules.length > 0) {
const top = activeRules[0];
this.currentRecommendation = typeof top.recommendation === 'function'
? top.recommendation()
: top.recommendation;
} else if (G.strategicFlag && G.strategyLastTournament && G.strategyLastTournament.leader) {
this.currentRecommendation = `Tournament leader: ${G.strategyLastTournament.leader.label}. Yomi is currently generating +${fmt(this.getYomiInsightRate())} knowledge/sec.`;
} else {
this.currentRecommendation = 'System stable. Continue writing code.';
if (G.strategicFlag === 1 && (!this.lastTournament || !this.lastTournament.length)) {
const board = this.runTournament(8);
G.strategyLeaderboard = board.slice(0, 4).map((row) => ({ ...row }));
}
}
getRecommendation() {
return this.currentRecommendation || 'System stable. Continue writing code.';
return this.currentRecommendation;
}
getPanelHtml() {
if (G.strategicFlag !== 1) {
return '<div style="font-size:11px;color:#777;font-style:italic">Unlock the Strategy Engine project to run tournaments.</div>';
}
const leaderboard = (G.strategyLeaderboard && G.strategyLeaderboard.length ? G.strategyLeaderboard : this.lastTournament || []).slice(0, 4);
const rows = leaderboard.length
? leaderboard.map((row, index) => `<div style="display:flex;justify-content:space-between;font-size:10px;padding:2px 0"><span>${index + 1}. ${row.name}</span><span>${row.score} pts</span></div>`).join('')
: '<div style="font-size:10px;color:#777">No tournament data yet.</div>';
const autoLabel = G.autoTournamentUnlocked
? (G.autoTournamentEnabled ? 'AUTO-TOURNAMENT: ON' : 'AUTO-TOURNAMENT: OFF')
: 'Auto-Tournament unlocks at 50K creativity';
const buttonHtml = G.autoTournamentUnlocked
? `<button class="ops-btn" onclick="toggleAutoTournament()" style="margin-top:8px;width:100%">${G.autoTournamentEnabled ? 'PAUSE AUTO-TOURNAMENT' : 'START AUTO-TOURNAMENT'}</button>`
: '';
return `
<div style="font-size:11px;color:var(--gold);font-style:italic;margin-bottom:8px">${this.getRecommendation()}</div>
<div style="font-size:10px;color:#9aa;line-height:1.6;margin-bottom:8px">Yomi: ${fmt(G.strategyPoints || 0)}</div>
<div style="font-size:10px;color:#ccc;margin-bottom:6px">Top strategies:</div>
<div style="border-top:1px solid #222;padding-top:4px;margin-bottom:8px">${rows}</div>
<div style="font-size:9px;color:#888">${autoLabel}</div>
${buttonHtml}
`;
}
}
const SSE = new StrategyEngine();
window.SSE = SSE; // Expose to global scope
window.SSE = SSE;
window.toggleAutoTournament = () => SSE.toggleAutoTournament();

View File

@@ -1,162 +0,0 @@
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 loadStrategyHarness() {
const storage = new Map();
const dummyClassList = {
add() {},
remove() {},
toggle() {},
contains() { return false; }
};
const document = {
body: { classList: dummyClassList, appendChild() {}, removeChild() {} },
head: { appendChild() {} },
getElementById() { return null; },
createElement() {
return {
style: {},
classList: dummyClassList,
appendChild() {},
remove() {},
setAttribute() {},
addEventListener() {},
innerHTML: '',
textContent: ''
};
},
addEventListener() {},
removeEventListener() {},
querySelector() { return null; },
querySelectorAll() { return []; }
};
const window = {
document,
addEventListener() {},
removeEventListener() {},
innerWidth: 1280,
innerHeight: 720
};
const context = {
console,
Math,
Date,
document,
window,
performance: { now: () => 0 },
setTimeout() { return 1; },
clearTimeout() {},
localStorage: {
getItem(key) { return storage.has(key) ? storage.get(key) : null; },
setItem(key, value) { storage.set(key, String(value)); },
removeItem(key) { storage.delete(key); }
}
};
vm.createContext(context);
const source = ['js/data.js', 'js/utils.js', 'js/strategy.js']
.map((file) => fs.readFileSync(path.join(ROOT, file), 'utf8'))
.join('\n\n');
vm.runInContext(`${source}
log = () => {};
showToast = () => {};
this.__exports = {
G,
SSE,
StrategyEngine,
STRATEGY_TACTICS: typeof STRATEGY_TACTICS !== 'undefined' ? STRATEGY_TACTICS : null
};`, context);
return { ...context.__exports, context };
}
test('strategy engine progressively unlocks tournament tactics and renders visual scoring', () => {
const { G, SSE } = loadStrategyHarness();
Object.assign(G, {
strategicFlag: 1,
trust: 30,
totalUsers: 1500,
totalKnowledge: 20000,
totalImpact: 1500,
creativity: 60000,
knowledge: 0,
yomi: 0,
totalYomi: 0
});
const early = SSE.getUnlockedStrategies().map((strategy) => strategy.id);
assert.ok(early.includes('RANDOM'));
assert.ok(early.includes('GREEDY'));
assert.ok(early.includes('TIT_FOR_TAT'));
assert.ok(!early.includes('MINIMAX'));
G.yomi = 500;
const late = SSE.getUnlockedStrategies().map((strategy) => strategy.id);
assert.ok(late.includes('BEAT_LAST'));
assert.ok(late.includes('MINIMAX'));
const result = SSE.runTournament();
assert.ok(result, 'expected tournament result');
assert.ok(result.scoreboard.length >= 6, 'expected multi-strategy scoreboard');
assert.ok(G.yomi > 0, 'expected Yomi reward');
assert.ok(G.totalYomi >= G.yomi, 'expected total Yomi tracking');
assert.ok(G.knowledge > 0, 'expected knowledge gain from Yomi');
assert.equal(G.strategyLastTournament.leader.id, result.leader.id);
const html = SSE.getPanelHtml();
assert.match(html, /TOURNAMENT/i);
assert.match(html, /LEADER/i);
assert.match(html, /RANDOM/);
});
test('auto-tournament mode requires 50k creativity to unlock', () => {
const { G, SSE } = loadStrategyHarness();
Object.assign(G, {
strategicFlag: 1,
creativity: 49999
});
assert.equal(SSE.unlockAutoTournament(), false);
assert.equal(G.strategyAutoUnlocked, false);
assert.equal(G.strategyAutoEnabled, false);
G.creativity = 50000;
assert.equal(SSE.unlockAutoTournament(), true);
assert.equal(G.creativity, 0);
assert.equal(G.strategyAutoUnlocked, true);
assert.equal(G.strategyAutoEnabled, true);
});
test('auto tournaments fire on the timer once unlocked', () => {
const { G, SSE } = loadStrategyHarness();
Object.assign(G, {
strategicFlag: 1,
trust: 25,
totalUsers: 1500,
totalKnowledge: 22000,
totalImpact: 1500,
creativity: 50000,
knowledge: 0,
yomi: 0,
totalYomi: 0
});
SSE.unlockAutoTournament();
G.strategyTournamentTimer = G.strategyTournamentInterval - 0.25;
const beforeYomi = G.yomi;
const ran = SSE.tick(1);
assert.equal(Boolean(ran), true);
assert.ok(G.yomi > beforeYomi, 'expected auto tournament Yomi reward');
assert.ok(G.strategyLastTournament, 'expected auto tournament summary');
});

View File

@@ -0,0 +1,117 @@
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 loadStrategy() {
const dataSrc = fs.readFileSync(path.join(ROOT, 'js/data.js'), 'utf8');
const utilsSrc = fs.readFileSync(path.join(ROOT, 'js/utils.js'), 'utf8');
const renderSrc = fs.readFileSync(path.join(ROOT, 'js/render.js'), 'utf8');
const strategySrc = fs.readFileSync(path.join(ROOT, 'js/strategy.js'), 'utf8');
const context = {
console,
Math,
Date,
window: {},
document: {
getElementById() { return null; },
body: { appendChild() {} },
createElement() { return { style: {}, appendChild() {}, remove() {}, setAttribute() {}, innerHTML: '', textContent: '' }; },
querySelector() { return null; },
querySelectorAll() { return []; },
},
showToast() {},
log() {},
canAffordBuilding() { return false; },
localStorage: {
_raw: null,
getItem() { return this._raw; },
setItem(_k, v) { this._raw = v; },
removeItem() { this._raw = null; },
},
EVENTS: [],
updateRates() {},
showOfflinePopup() {},
Combat: { renderCombatPanel() {} },
};
vm.createContext(context);
vm.runInContext(`${dataSrc}\n${utilsSrc}\n${renderSrc}\n${strategySrc}\nthis.__exports = { G, StrategyEngine, STRATEGY_LIBRARY, saveGame: typeof saveGame === 'function' ? saveGame : null, loadGame: typeof loadGame === 'function' ? loadGame : null };`, context);
return context.__exports;
}
test('strategy engine exposes eight game theory strategies', () => {
const { STRATEGY_LIBRARY } = loadStrategy();
assert.deepEqual(Object.keys(STRATEGY_LIBRARY).sort(), [
'cooperate', 'defect', 'generous', 'greedy', 'grim', 'minimax', 'random', 'tit_for_tat'
]);
});
test('strategy engine unlocks strategies progressively by knowledge', () => {
const { G, StrategyEngine } = loadStrategy();
G.strategicFlag = 1;
G.totalKnowledge = 16000;
const sse = new StrategyEngine();
assert.equal(sse.getUnlockedStrategies().length, 4);
G.totalKnowledge = 25000;
assert.equal(sse.getUnlockedStrategies().length, 6);
G.totalKnowledge = 60000;
assert.equal(sse.getUnlockedStrategies().length, 8);
});
test('round-robin tournament produces a sorted leaderboard', () => {
const { G, StrategyEngine } = loadStrategy();
G.strategicFlag = 1;
G.totalKnowledge = 60000;
const sse = new StrategyEngine();
const board = sse.runTournament(6);
assert.ok(board.length >= 8);
for (let i = 1; i < board.length; i++) {
assert.ok(board[i - 1].score >= board[i].score);
}
});
test('auto-tournament mode awards Yomi as knowledge over time', () => {
const { G, StrategyEngine } = loadStrategy();
G.strategicFlag = 1;
G.totalKnowledge = 60000;
G.autoTournamentUnlocked = true;
G.autoTournamentEnabled = true;
G.strategyPoints = 0;
const sse = new StrategyEngine();
sse.tick(31);
assert.ok(G.strategyPoints > 0);
assert.ok(G.totalKnowledge > 60000);
assert.ok(Array.isArray(G.strategyLeaderboard));
assert.ok(G.strategyLeaderboard.length > 0);
});
test('strategy state persists through save/load payload fields', () => {
const { G, saveGame, loadGame } = loadStrategy();
assert.equal(typeof saveGame, 'function');
assert.equal(typeof loadGame, 'function');
G.startedAt = Date.now();
G.strategyPoints = 42;
G.autoTournamentUnlocked = true;
G.autoTournamentEnabled = true;
G.strategyLastRunAt = 123456;
G.strategyLeaderboard = [{ id: 'tit_for_tat', score: 99 }];
saveGame();
G.strategyPoints = 0;
G.autoTournamentUnlocked = false;
G.autoTournamentEnabled = false;
G.strategyLastRunAt = 0;
G.strategyLeaderboard = [];
assert.equal(loadGame(), true);
assert.equal(G.strategyPoints, 42);
assert.equal(G.autoTournamentUnlocked, true);
assert.equal(G.autoTournamentEnabled, true);
assert.equal(G.strategyLastRunAt, 123456);
assert.equal(G.strategyLeaderboard[0].id, 'tit_for_tat');
});