Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

6.0 KB
Raw Blame
import {assert,clone,canonical,projectData} from './project.mjs';
function freeze(o){if(o&&typeof o==='object'){Object.values(o).forEach(freeze);Object.freeze(o);}return o;}
function finiteJSON(x,label){const seen=new Set();function visit(v){if(typeof v==='number')assert(Number.isFinite(v),label+' has a non-finite number.');else if(v&&typeof v==='object'){assert(!seen.has(v),label+' contains a cycle.');seen.add(v);assert(Array.isArray(v)||Object.getPrototypeOf(v)===Object.prototype,label+' must be plain JSON.');Object.values(v).forEach(visit);seen.delete(v);}else assert(v===null||['string','boolean'].includes(typeof v),label+' must be plain JSON.');}visit(x);assert(JSON.stringify(x).length<1000000,label+' exceeds 1 MB.');return x;}
export function rng(seed){let n=2166136261;for(const c of String(seed)){n^=c.codePointAt(0);n=Math.imul(n,16777619);}return()=>{n+=0x6D2B79F5;let t=n;t=Math.imul(t^t>>>15,t|1);t^=t+Math.imul(t^t>>>7,t|61);return((t^t>>>14)>>>0)/4294967296;};}
export function context(seed,step){return Object.freeze({random:stream=>rng(seed+'|'+step+'|'+String(stream)),shuffle:(items,stream)=>{const a=clone(items),r=rng(seed+'|'+step+'|'+stream);for(let i=a.length-1;i>0;i--){const j=Math.floor(r()*(i+1));[a[i],a[j]]=[a[j],a[i]];}return a;}});}
export class Game {
  constructor(project,rules,seed='first-game'){
    for(const name of ['initial','legal','apply','observe','outcome','validate'])assert(typeof rules[name]==='function','Rules must export '+name+'().');
    assert(typeof seed==='string'&&seed.length<=128,'Use a seed of at most 128 characters.');
    this.project=freeze(projectData(project));this.rules=rules;this.seed=seed;this.actions=[];this.states=[];
    const s=rules.initial(this.project,context(seed,0));this.check(s);this.states.push(clone(s));this.verifyTurn();
  }
  get state(){return freeze(clone(this.states.at(-1)));}
  check(s){finiteJSON(s,'Game state');assert(Number.isInteger(s.player)&&s.player>=0&&s.player<this.project.players,'State must identify the current player.');const valid=this.rules.validate(freeze(clone(s)),this.project);assert(valid===true,typeof valid==='string'?valid:'Rule validation failed.');}
  outcome(){const end=this.rules.outcome(this.state,this.project);assert(end===null||(end&&typeof end==='object'&&typeof end.title==='string'&&Array.isArray(end.winners)&&end.winners.every(n=>Number.isInteger(n)&&n>=0&&n<this.project.players)),'Outcome must be null or {title,winners,...}.');return end===null?null:finiteJSON(end,'Outcome');}
  legal(){const a=this.rules.legal(this.state,this.project);assert(Array.isArray(a)&&a.length<=500,'Rules must offer at most 500 legal actions.');finiteJSON(a,'Legal actions');const ids=new Set();for(const x of a){assert(x&&typeof x.id==='string'&&x.id.length<=180&&!ids.has(x.id)&&typeof x.label==='string'&&x.label.length<=200,'Legal actions need unique ids and readable labels.');ids.add(x.id);}return clone(a);}
  verifyTurn(){const end=this.outcome(),a=this.legal();assert(end!==null||a.length>0,'Dead end: the game has no legal action and no outcome.');assert(end===null||a.length===0,'Finished games must not offer actions.');return{end,a};}
  view(){const {end,a}=this.verifyTurn(),view=this.rules.observe(this.state,this.state.player,this.project);finiteJSON(view,'Observation');assert(view&&typeof view.title==='string'&&Array.isArray(view.zones)&&Array.isArray(view.scores),'Observation needs title, zones and scores.');return{view,actions:a,outcome:end,player:this.state.player,step:this.actions.length,seed:this.seed};}
  step(id){assert(this.actions.length<2000,'This playtest reached the 2,000-turn limit. Save its replay and revise the rules.');const a=this.legal().find(x=>x.id===id);assert(a&&!this.outcome(),'That action is not legal now.');const previous=this.state,next=this.rules.apply(previous,freeze(clone(a)),this.project,context(this.seed,this.actions.length+1));this.check(next);assert(canonical(previous)!==canonical(next),'An action must change the game state.');this.states.push(clone(next));this.actions.push(id);try{this.verifyTurn();}catch(e){this.states.pop();this.actions.pop();throw e;}return this.view();}
  undo(){if(this.actions.length){this.states.pop();this.actions.pop();}return this.view();}
  replay(){return{spec:1,seed:this.seed,actions:clone(this.actions),state:canonical(this.state)};}
  restore(replay){assert(replay?.spec===1&&Array.isArray(replay.actions)&&replay.actions.length<=2000,'Use a version 1 replay within 2,000 turns.');assert(replay.seed===this.seed,'Replay seed differs.');for(const a of replay.actions)this.step(a);assert(canonical(this.state)===replay.state,'Replay state does not match its actions and rules.');return this.view();}
}
export function simulate(project,rules,{count=50,start=0,policy='uniform',maxTurns=400}={}){
  assert(Number.isInteger(count)&&count>=1&&count<=200,'Simulate 1–200 games.');assert(Number.isInteger(maxTurns)&&maxTurns>=1&&maxTurns<=2000,'Use a 1–2,000 turn cap.');assert(['uniform','authored'].includes(policy),'Select uniform or authored policy.');if(policy==='authored')assert(typeof rules.bot==='function','This rules module has no authored policy.');
  const games=[];for(let i=0;i<count;i++){const seed='playtest-'+(start+i);try{const g=new Game(project,rules,seed),choose=rng(seed+'|policy');while(!g.outcome()&&g.actions.length<maxTurns){const v=g.view();const id=policy==='uniform'?v.actions[Math.floor(choose()*v.actions.length)].id:rules.bot(freeze(clone(v.view)),freeze(clone(v.actions)),{random:choose});g.step(id);}games.push({seed,turns:g.actions.length,outcome:g.outcome(),capped:!g.outcome(),replay:g.replay()});}catch(e){games.push({seed,error:e.message});}}
  const wins=Array(project.players).fill(0);for(const g of games)for(const n of g.outcome?.winners??[])wins[n]++;
  return{spec:1,policy,count,start,maxTurns,wins,completed:games.filter(g=>g.outcome).length,capped:games.filter(g=>g.capped).length,errors:games.filter(g=>g.error).length,meanTurns:games.reduce((n,g)=>n+(g.turns??0),0)/count,scope:'Outcomes under the named policy and seeds. These simulations do not establish fun, fairness or human play balance.',games};
}