Agent mode: an AI agent plays in the player's own tab, with the agent's clock or a running one
The MCP server gains a second session, --browser: the game in the player's tab, reached through the agent relay npm run dev hosts at /agent (loopback unless --host; Host and Origin checked, no token). The player turns it on in Settings → Agent API, a section only the development page has, and picks the clock: a pace of 30 s to 5 min a day that nobody can pause, or the agent's own. Headless gets the running clock too (--clock realtime --pace MS) and both get a wait tool. All of it lives in src/agent/ (development page only). The game offers HOOKS, UI.clockLocked, setSpeed() and runClock(dt), the frame's day block moved out unchanged, and nothing more: the page players get grows by under 1 KB gzipped and runs exactly as before.
This commit is contained in:
parent
2526dd458d
commit
7438fd1065
53 changed files with 1827 additions and 170 deletions
|
|
@ -1,8 +1,9 @@
|
|||
/* ================= AGENT API: argument domains =================
|
||||
The agent facade (window.TUBES, this folder) is how tools play the game: the MCP server (scripts/mcp.js) calls it in
|
||||
its own jsdom page. It is part of the development page only (<!-- @include-dev agent -->): the page players get has
|
||||
none of it, so nothing in src/game/ may name anything defined here. Nothing here runs until a tool calls it: these
|
||||
files only define tables and functions.
|
||||
its own jsdom page, or in the player's tab through the agent relay (80-relay.js). It is part of the development page
|
||||
only (<!-- @include-dev agent -->): the page players get has none of it, so nothing in src/game/ may name anything
|
||||
defined here; the game offers HOOKS instead. Nothing here runs until a tool calls it or the player switches agent
|
||||
mode on: these files define tables and functions, and 99-start.js wires agent mode in.
|
||||
A domain is what an argument may be: an id in a catalog table, a key, an index, a small fixed list, or a check. */
|
||||
const API_DOMAINS={
|
||||
// Tables from the catalog: an id in a list, a key in an object, or an index into a list.
|
||||
|
|
|
|||
|
|
@ -510,7 +510,8 @@ const API_BOUND={
|
|||
|
||||
/* Starting, retrying and leaving scenarios, puzzles and architect runs, and the screens a player dismisses. They run
|
||||
as their buttons run them; new_game, load_save and export_save are the other half of the session, and exist only in
|
||||
the MCP server's own page (scripts/lib/mcp-headless.js). */
|
||||
the MCP server's own page (scripts/lib/mcp-headless.js). In the player's tab the player owns the game, so the ones
|
||||
that replace or leave it are refused there (API_PLAYER_OWNS). */
|
||||
const API_SESSION={
|
||||
startScn:{args:[['id','scnId']],doc:'Start a scenario (ids from catalog SCN), replacing the current game.'},
|
||||
startWeekly:{args:[],doc:'Start this week\'s weekly scenario, replacing the current game. The week follows the real date.'},
|
||||
|
|
@ -523,11 +524,14 @@ const API_SESSION={
|
|||
pitchSkip:{args:[],doc:'Skip the opening pitch; a game waiting behind it starts.'},
|
||||
tutSkip:{args:[],doc:'Skip the tutorial coaching.'},
|
||||
};
|
||||
// Session actions that would replace or leave the game in the player's tab: refused over the relay.
|
||||
const API_OWN_WHY='the game in this tab is the player\'s: only the player starts, loads or leaves one';
|
||||
const API_PLAYER_OWNS={startScn:1,startWeekly:1,pzStart:1,pzWeekly:1,pzArStart:1,pzRetry:1,pzLeave:1};
|
||||
|
||||
/* Actions no tool runs, by reason: files, storage slots, settings and the title screen are not the game's, and time
|
||||
moves only through advance (or the page's own clock). */
|
||||
const API_WHY={
|
||||
time:'use advance to move time',start:'use new_game',files:'use load_save or export_save',
|
||||
time:'use advance to move time, or wait when the clock runs on its own',start:'use new_game',files:'use load_save or export_save',
|
||||
slots:'saved networks in browser storage are not part of this game',prefs:'device and player settings are not part of the game',
|
||||
browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)',
|
||||
};
|
||||
|
|
|
|||
|
|
@ -143,3 +143,12 @@ const API_RESULTS_DOC={
|
|||
cityBlocked:{type:'map',doc:'Set up per city by the traffic computation; nothing fills it at present.'},
|
||||
ddosHot:{type:'map',doc:'Cities whose ports a flood is filling, for the map\'s pulse. Keyed by city id.'},
|
||||
};
|
||||
|
||||
/* The dice rather than the board: in the player's tab (over the relay) state never returns these, and schema says why.
|
||||
The MCP server's own page returns them, for debugging. */
|
||||
const API_WITHHELD={
|
||||
rng:'the seed: it predicts every future random draw',
|
||||
nextFail:'the day the next failure fires',
|
||||
nextEvent:'the day the next world event fires',
|
||||
'scn.nextDdos':'the day of the next scripted attack in a scenario',
|
||||
};
|
||||
|
|
|
|||
|
|
@ -183,19 +183,20 @@ function apiArgDoc([name,dom,req]){
|
|||
else{const v=apiDomValues(dom);if(Array.isArray(v))a.values=v;else if(v&&v.from!==undefined)a.range=v;}
|
||||
return a;}
|
||||
function apiSchema(section){
|
||||
const cmd=s=>({args:(s.args||[]).map(apiArgDoc),doc:s.doc});
|
||||
const cmd=s=>({args:(s.args||[]).map(apiArgDoc),doc:s.doc}),relay=API_CTX.relay;
|
||||
const doc={
|
||||
mode:apiMode(),
|
||||
clock:apiClockDoc(),
|
||||
commands:Object.fromEntries(Object.entries(API_CMD).map(([n,s])=>[n,{...cmd(s),dryRun:!!s.quote,
|
||||
...(s.decides?{decides:true}:{}),...(s.confirm?{confirm:s.confirm}:{}),...(s.open?{opens:s.open}:{}),...(s.reads?{report:true}:{})}])),
|
||||
view:Object.fromEntries(Object.entries(API_VIEW).map(([n,s])=>[n,cmd(s)])),
|
||||
session:Object.fromEntries(Object.entries(API_SESSION).map(([n,s])=>[n,cmd(s)])),
|
||||
session:Object.fromEntries(Object.entries(API_SESSION).map(([n,s])=>[n,{...cmd(s),...(relay&&API_PLAYER_OWNS[n]?{refused:API_OWN_WHY}:{})}])),
|
||||
drafts:API_BOUND,
|
||||
denied:Object.fromEntries(Object.keys(API_DENY).sort().map(n=>[n,apiDenied(n)])),
|
||||
domains:Object.fromEntries(Object.entries(API_DOMAINS).map(([n,d])=>{const v=apiDomValues(n);
|
||||
return [n,{kind:d.kind==='fn'?'custom':d.kind,...(d.table?{from:d.table}:{}),
|
||||
...(!d.table&&Array.isArray(v)?{values:v}:v&&v.from!==undefined?{range:v}:v&&v.of?{of:v.of}:{})}];})),
|
||||
state:API_STATE_DOC,
|
||||
state:relay?Object.fromEntries(Object.entries(API_STATE_DOC).map(([k,d])=>[k,API_WITHHELD[k]?{...d,withheld:API_WITHHELD[k]}:d])):API_STATE_DOC,
|
||||
results:API_RESULTS_DOC,
|
||||
};
|
||||
if(section===undefined||section===null||section==='')return doc;
|
||||
|
|
@ -208,7 +209,19 @@ function apiCatalog(name){
|
|||
if(name in API_MADE)return apiJson(API_MADE[name]());
|
||||
if(name in API_TABLES)return apiJson(API_TABLES[name]);
|
||||
apiFail(`No table "${name}". Call catalog without a name for the list.`);}
|
||||
function apiState(path){if(!S)return null;const v=apiJson(apiPath(S,path));return v===undefined?null:v;}
|
||||
// In the player's tab the dice are held back: a withheld field, or one inside the subtree asked for, is left out.
|
||||
function apiState(path){
|
||||
if(!S)return null;
|
||||
const p=path===undefined||path===null?'':String(path),v=apiJson(apiPath(S,p));
|
||||
if(v===undefined)return null;
|
||||
if(!API_CTX.relay)return v;
|
||||
for(const w of Object.keys(API_WITHHELD)){
|
||||
if(w===p||p.startsWith(w+'.'))return null;
|
||||
if(p&&!w.startsWith(p+'.'))continue;
|
||||
const ks=(p?w.slice(p.length+1):w).split('.');let o=v;
|
||||
for(let i=0;i<ks.length-1&&o&&typeof o==='object';i++)o=o[ks[i]];
|
||||
if(o&&typeof o==='object')delete o[ks[ks.length-1]];}
|
||||
return v;}
|
||||
function apiResults(path){const v=apiJson(apiPath(R,path));return v===undefined?null:v;}
|
||||
function apiUi(){const o={};for(const k of Object.keys(UI))if(!API_UI_HIDDEN[k])o[k]=apiJson(UI[k]);return o;}
|
||||
function apiActions(){
|
||||
|
|
|
|||
|
|
@ -4,15 +4,19 @@
|
|||
const API_ROOT={modal:'modal',bank:'bankBox',dash:'dash',panel:'panel',left:'leftBody',puzzle:'pzBox'};
|
||||
const apiShown=w=>{const el=$(API_ROOT[w]);return !!el&&!el.hidden;};
|
||||
const apiModalOpen=()=>apiShown('modal');
|
||||
// A window the player opened by hand (API_MODAL.hand, 75-mode.js) is theirs: a tool reads it but never answers,
|
||||
// closes or replaces it, and it is never a question the game is waiting on.
|
||||
const apiPlayerWin=()=>apiModalOpen()&&API_MODAL.hand;
|
||||
// The buttons of the last screen a tool read, for click. Set by apiScreen.
|
||||
let API_LAST=[];
|
||||
function apiControls(root){
|
||||
function apiControls(root,player){
|
||||
const out=[];
|
||||
for(const b of root.querySelectorAll('[data-act],select[data-chg]')){
|
||||
const o=b.dataset.act?{label:apiText(b,200).replace(/\n/g,' ')||b.getAttribute('aria-label')||b.dataset.act,act:b.dataset.act,args:apiParse(b.dataset.args),disabled:!!b.disabled}
|
||||
// A list the game acts on when its value changes (the change handler in 96-map/95-clicks.js): click it with a value.
|
||||
:{label:b.getAttribute('aria-label')||(b.closest('label')&&apiText(b.closest('label'),120).split('\n')[0])||b.dataset.chg,
|
||||
select:b.dataset.chg,value:b.value,options:[...b.options].map(o=>({value:o.value,label:o.textContent.trim()})),disabled:!!b.disabled};
|
||||
if(player)o.player=true;
|
||||
out.push(o);}
|
||||
return out;}
|
||||
function apiScreen(where,offset=0){
|
||||
|
|
@ -20,12 +24,12 @@ function apiScreen(where,offset=0){
|
|||
if(where!==undefined&&!API_ROOT[where])apiFail(`where is one of ${Object.keys(API_ROOT).join(', ')}.`);
|
||||
const open=Object.keys(API_ROOT).filter(w=>w!=='left'&&apiShown(w));
|
||||
const w=where||['modal','bank','dash','panel','puzzle'].find(apiShown)||'panel';
|
||||
const root=$(API_ROOT[w]);
|
||||
API_LAST=root?apiControls(root):[];
|
||||
const root=$(API_ROOT[w]),player=w==='modal'&&apiPlayerWin();
|
||||
API_LAST=root?apiControls(root,player):[];
|
||||
const all=root?apiFullText(root):'',from=Math.max(0,Math.floor(+offset)||0),more=all.length-from-API_MAX_TEXT;
|
||||
const out={where:w,open,selected:UI.sel,tab:UI.tab};
|
||||
if(w==='left')out.leftTab=UI.left||'goals';
|
||||
if(w==='modal')out.question=!!apiDecision();
|
||||
if(w==='modal'){out.question=!!apiDecision();if(player)out.playerWindow='the player opened this window: read it, but its buttons are theirs to press';}
|
||||
out.text=all.slice(from,from+API_MAX_TEXT);
|
||||
if(from)out.textFrom=from;
|
||||
if(more>0)out.textMore=`${more} more characters: call screen with where "${w}" and offset ${from+API_MAX_TEXT}`;
|
||||
|
|
@ -39,14 +43,24 @@ function apiScreen(where,offset=0){
|
|||
commands wait until it is answered or closed, as clicks outside an open window do in the game. */
|
||||
let API_SHEET=null;
|
||||
const apiCard=()=>$('modalCard').firstChild;
|
||||
const apiMarkSheet=()=>{API_SHEET=apiModalOpen()?apiCard():null;};
|
||||
const apiMarkSheet=()=>{API_SHEET=apiModalOpen()&&!apiPlayerWin()?apiCard():null;};
|
||||
const apiIsSheet=()=>apiModalOpen()&&!!API_SHEET&&apiCard()===API_SHEET;
|
||||
function apiDecision(){
|
||||
if(!apiModalOpen()||apiIsSheet())return null;
|
||||
if(!apiModalOpen()||apiIsSheet()||apiPlayerWin())return null;
|
||||
const b=[...$('modal').querySelectorAll('[data-act]')].filter(x=>x.dataset.act!=='closeModal'&&API_CMD[x.dataset.act]);
|
||||
if(!b.length)return null;
|
||||
return {text:apiText($('modal'),1500),options:b.map(x=>({command:x.dataset.act,args:apiParse(x.dataset.args),label:apiText(x,120).replace(/\n/g,' ')}))};}
|
||||
|
||||
/* A player's window stays where it is: its very nodes are set aside while a tool's command runs, and put back after,
|
||||
so typed text survives. Only a question the game asks in answer to the tool's move takes the screen, as it would
|
||||
after a click. */
|
||||
function apiHold(){const m=$('modal'),c=$('modalCard');
|
||||
return {nodes:[...c.childNodes],cls:m.className,aria:c.getAttribute('aria-modal'),setOpen:UI.setOpen,pending:UI.pending};}
|
||||
function apiRestore(h){const m=$('modal'),c=$('modalCard');
|
||||
if(!m.hidden&&m.className===h.cls&&c.childNodes.length===h.nodes.length&&h.nodes.every((n,i)=>c.childNodes[i]===n)){API_MODAL.hand=true;return;}
|
||||
m.className=h.cls;if(h.aria!==null)c.setAttribute('aria-modal',h.aria);c.replaceChildren(...h.nodes);
|
||||
if(m.hidden)markLayer();m.hidden=false;UI.setOpen=h.setOpen;UI.pending=h.pending;API_MODAL.hand=true;API_SHEET=null;}
|
||||
|
||||
function apiPanel({city:c,link,network:q,tab,left}={}){
|
||||
if(left!==undefined){if(!['goals','deals','noc','nets'].includes(left))apiFail('left is one of goals, deals, noc, nets.');ACT.leftTab({t:left});return apiScreen('left');}
|
||||
if(c)UI.sel={type:'city',id:apiCityOf(c).id};
|
||||
|
|
@ -58,6 +72,7 @@ function apiPanel({city:c,link,network:q,tab,left}={}){
|
|||
function apiOpenLink(a,b){
|
||||
const x=apiCityOf(a).id,y=apiCityOf(b).id;
|
||||
if(!S.pops[x])apiFail(`A link starts at one of your POPs: ${apiMyPops()}.`);
|
||||
if(apiPlayerWin())apiFail('The player has a window open, and the link window would replace it. Use act buildLink, orderDf or orderCable, or wait until it is closed.');
|
||||
apiTake();
|
||||
openLinkModal(x,y);
|
||||
apiMarkSheet();
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ function apiMeter(){const real=window.spend;let paid=0;window.spend=c=>{const ok
|
|||
/* typed: through the command table (bind the UI, type into fields, pass the confirmation); otherwise as a button click
|
||||
does it, with the button's own arguments. */
|
||||
function apiDispatch(name,kind,spec,args,typed){
|
||||
const mine=apiIsSheet()||(typed&&kind==='game'&&!!spec.open);
|
||||
const mine=apiIsSheet()||(typed&&kind==='game'&&!!spec.open),held=apiPlayerWin()?apiHold():null;
|
||||
apiTake();
|
||||
const ref=S,cash=S?S.cash:0,f0=apiFp(spec&&spec.watch,args),paid=apiMeter();
|
||||
let threw=null,report;
|
||||
|
|
@ -49,19 +49,25 @@ function apiDispatch(name,kind,spec,args,typed){
|
|||
const a=spec.pass?spec.pass(args):args;
|
||||
ACT[name](a);
|
||||
if(spec.confirm==='double')ACT[name](a);
|
||||
if(spec.reads==='modal'&&apiModalOpen()){report=apiText($('modal'));closeModal();}
|
||||
if(spec.reads==='modal'&&apiModalOpen()&&!apiPlayerWin()){report=apiText($('modal'));closeModal();}
|
||||
}else ACT[name](args);
|
||||
}catch(e){threw=e;}
|
||||
const charged=paid();
|
||||
if(held&&(threw||!apiDecision())){
|
||||
// The tool's own sheet is read before the player's window goes back over it.
|
||||
const shot=!threw&&apiModalOpen()&&!apiPlayerWin()?apiScreen('modal'):null;
|
||||
apiRestore(held);
|
||||
if(shot)shot.note='The player has a window open, so this one was shown to you and closed again.';
|
||||
held.shot=shot;}
|
||||
if(threw){apiTake();apiFail(`${name} failed: ${threw&&threw.message||threw}`);}
|
||||
if(!apiModalOpen())API_SHEET=null;
|
||||
if(!apiModalOpen()||apiPlayerWin())API_SHEET=null;
|
||||
else if(mine||kind!=='game')apiMarkSheet();
|
||||
else API_SHEET=null;
|
||||
const said=apiTake(),d=apiDecision();
|
||||
const outcome=d?'decision':S!==ref||apiFp(spec&&spec.watch,args)!==f0||report!==undefined?'applied'
|
||||
:said.some(t=>t.kind==='bad')?'rejected':kind==='view'||kind==='draft'?'shown':'no_effect';
|
||||
return {action:name,outcome,toasts:apiToastLines(said),charged,cashChange:Math.round((S?S.cash:0)-cash),
|
||||
...(report!==undefined?{report}:{}),...(d?{decision:d}:{}),screen:apiScreen()};}
|
||||
...(report!==undefined?{report}:{}),...(d?{decision:d}:{}),screen:held&&held.shot||apiScreen()};}
|
||||
// While the game waits for an answer, game commands other than its options report the question instead.
|
||||
function apiWaiting(name){
|
||||
const d=apiDecision();
|
||||
|
|
@ -82,10 +88,11 @@ function apiQuote(name,spec,args){
|
|||
}catch(e){apiFail(`${name}: the price could not be worked out: ${e&&e.message||e}`);}finally{Math.random=dice;for(const k of Object.keys(ui0))UI[k]=ui0[k];}
|
||||
return {action:name,outcome:'quote',quote:{setup:0,monthly:0,...q,blocked:(q.blocked||[]).map(b=>apiText(String(b),400))},consistent:apiFp(spec.watch,args)===f0,
|
||||
...(spec.quote?{}:{note:'This command has no price of its own: it costs nothing up front.'})};}
|
||||
// Checks shared by act and click: what no tool runs.
|
||||
// Checks shared by act and click: what no tool runs, and what only the player runs in their own tab.
|
||||
function apiAllowed(name,what){
|
||||
const no=apiDenied(name);
|
||||
if(no)apiFail(`${name} is not available here: ${no}.`);
|
||||
if(API_CTX.relay&&API_PLAYER_OWNS[name])apiFail(`${name} is not available here: ${API_OWN_WHY}.`);
|
||||
const kind=apiKind(name);
|
||||
if(!kind||typeof ACT[name]!=='function')apiFail(what);
|
||||
return kind;}
|
||||
|
|
@ -107,6 +114,7 @@ function apiClick(n,value){
|
|||
const b=API_LAST[n];
|
||||
if(!b)apiFail(`No button ${n} on the last screen. Call screen first.`);
|
||||
if(b.disabled)apiFail(`"${b.label}" is greyed out.`);
|
||||
if(b.player&&apiPlayerWin())apiFail(`"${b.label}" is in a window the player opened: it is theirs to press.`);
|
||||
const name=b.select||b.act,args=b.select?{v:value===undefined?undefined:String(value)}:b.args;
|
||||
if(b.select&&!b.options.some(o=>o.value===args.v))apiFail(`"${b.label}" is a list: click it with a value, one of ${b.options.map(o=>JSON.stringify(o.value)).join(', ')}.`);
|
||||
const kind=apiAllowed(name,`"${b.label}" runs ${name}, which is not an action.`);
|
||||
|
|
|
|||
|
|
@ -1,8 +1,21 @@
|
|||
/* ================= AGENT API: time =================
|
||||
The agent's clock: nothing moves until a tool asks for days with advance, one dayTick() per simulated day. */
|
||||
const apiClockDoc=()=>'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.';
|
||||
Two clocks, in the MCP server's own page and in the player's tab alike. The agent's clock: nothing moves until a tool
|
||||
asks for days with advance. A running clock: days pass at a fixed pace whatever the tool does, and the tool can only
|
||||
wait and react. In the player's tab the player picks one in Settings (apiAgentMs(), 0 for the agent's clock); the MCP
|
||||
server's own page is told by the server (API_CLK). */
|
||||
let API_CLK={mode:'agent',paceMs:0,running:false};
|
||||
const apiClockNow=()=>API_CTX.relay?(apiAgentMs()>0?{mode:'realtime',paceMs:apiAgentMs(),running:!!UI.speed}:{mode:'agent',paceMs:0,running:false}):API_CLK;
|
||||
function apiMode(){const c=apiClockNow();
|
||||
return {backend:API_CTX.relay?'browser':'headless',clock:c.mode,...(c.mode==='realtime'?{paceMs:c.paceMs}:{}),
|
||||
...(API_CTX.relay?{withheld:API_WITHHELD,playerOwns:Object.keys(API_PLAYER_OWNS)}:{})};}
|
||||
function apiClockDoc(){const c=apiClockNow();
|
||||
return c.mode==='agent'?'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.'
|
||||
:`The clock runs on its own: one simulated day every ${apiR1(c.paceMs/1000)} s of real time, behind open windows too, and no tool can stop it${API_CTX.relay?' (it holds while no tool is connected)':''}. advance is not available; wait returns once days have passed.`;}
|
||||
function apiClock(){const c=apiClockNow();
|
||||
return {mode:c.mode,paceMs:c.paceMs||undefined,running:c.mode==='realtime'?!!c.running:false,
|
||||
day:S?S.day:null,date:S?dateStr(S.day):null,cash:S?S.cash:null,lost:!!(S&&S.lost),incidents:S?S.inc.map(i=>i.id):[],question:!!apiDecision()};}
|
||||
|
||||
// What happened since a moment (the start of an advance): the log, new incidents, cash.
|
||||
// What happened since a moment (the start of an advance, or a clock reading before wait): the log, new incidents, cash.
|
||||
// The log keeps what mattered; toasts that only repeat a log line are left out.
|
||||
function apiSince({day=0,cash=0,inc=[]}={},toasts=[]){
|
||||
const seen=new Set(inc),entries=(S.log||[]).filter(e=>e.d>day).slice(-60),logged=entries.map(e=>apiNorm(apiText(e.t,400)));
|
||||
|
|
@ -15,7 +28,9 @@ function apiSince({day=0,cash=0,inc=[]}={},toasts=[]){
|
|||
|
||||
function apiAdvanceStart(days){
|
||||
if(!S)apiFail('No game is running.');
|
||||
if(apiModalOpen())apiFail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.');
|
||||
const c=apiClockNow();
|
||||
if(c.mode!=='agent')apiFail(`The clock runs on its own here, one day every ${apiR1(c.paceMs/1000)} s: use wait to let days pass.`);
|
||||
if(apiModalOpen()&&!apiPlayerWin())apiFail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.');
|
||||
API_SHEET=null;
|
||||
apiTake();
|
||||
return {days:Math.max(1,Math.min(3650,Math.floor(+days)||1)),start:S.day,cash:S.cash,inc:S.inc.map(i=>i.id),times:[],ran:0,stop:null};}
|
||||
|
|
@ -26,7 +41,7 @@ function apiAdvanceDay(a){
|
|||
const t=performance.now();
|
||||
dayTick();
|
||||
a.times.push({day:S.day,ms:apiR1(performance.now()-t)});a.ran++;
|
||||
if(apiModalOpen()){a.stop='a window opened';return false;}
|
||||
if(apiModalOpen()&&!apiPlayerWin()){a.stop='a window opened';return false;}
|
||||
return a.ran<a.days;}
|
||||
function apiAdvanceEnd(a){
|
||||
renderAll();
|
||||
|
|
@ -36,3 +51,17 @@ function apiAdvanceEnd(a){
|
|||
timing:{totalMs:apiR1(total),perDayMs:apiR1(total/(a.ran||1)),slowestDays:a.times.slice().sort((x,y)=>y.ms-x.ms).slice(0,5).map(x=>({date:dateStr(x.day),ms:x.ms}))},
|
||||
...(out.decision?{decision:out.decision,screen:out.screen}:{})};}
|
||||
function apiAdvance(days){const a=apiAdvanceStart(days);while(apiAdvanceDay(a));return apiAdvanceEnd(a);}
|
||||
/* In the player's tab the days run where the player can watch them: a frame's worth of days, then the page draws.
|
||||
A hidden tab draws nothing (and its timers are throttled), so there they run straight through. A day the route
|
||||
worker is still routing finishes first. */
|
||||
const apiSleep=ms=>new Promise(r=>setTimeout(r,ms));
|
||||
async function apiAdvanceLive(days){
|
||||
const a=apiAdvanceStart(days);let t=performance.now();
|
||||
for(;;){
|
||||
while(RW.job)await apiSleep(20);
|
||||
if(!apiAdvanceDay(a))break;
|
||||
if(document.visibilityState!=='hidden'&&performance.now()-t>30){renderHUD();UI.panelsDue=true;await apiSleep(0);t=performance.now();}}
|
||||
return apiAdvanceEnd(a);}
|
||||
|
||||
// One day of a running clock in the MCP server's own page (the server keeps the time); the player's tab runs its own loop.
|
||||
function apiTick(){if(!S||S.lost||pzOn()||!rule('clock'))return false;dayTick();renderAll();return true;}
|
||||
|
|
|
|||
86
src/agent/75-mode.js
Normal file
86
src/agent/75-mode.js
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
/* ================= AGENT MODE: the player's switch and clock =================
|
||||
In the player's own tab (the development page, served locally), the player can let an agent drive: the page dials
|
||||
the agent relay (80-relay.js) and answers tool calls through TUBES.call. While it does, the clock is not the
|
||||
player's (UI.clockLocked): either a fixed pace, one simulated day every 30 s to 5 min, that nobody can pause and
|
||||
that holds while no tool is connected; or the agent's clock, which stands still until the agent asks for days.
|
||||
The game itself knows none of this: it calls HOOKS (50-state.js), which this file fills in, and reads
|
||||
UI.clockLocked. Settings of its own, in their own storage key, so the game's preferences stay as they are. */
|
||||
const API_AGENT_MS=[0,30000,60000,120000,300000],API_AGENT_KEY='sot-agent';
|
||||
const API_AGENT_PREFS=(()=>{let j={};try{j=JSON.parse(localStorage.getItem(API_AGENT_KEY)||'{}')||{};}catch(e){}
|
||||
return {on:j.on===true,ms:API_AGENT_MS.includes(j.ms)?j.ms:60000};})();
|
||||
/* Only where a relay can be: plain http (an https page cannot open ws://) to an address, never a DNS name, which the
|
||||
relay refuses (DNS rebinding). The public site is https and a name, so it never shows the switch. The test
|
||||
harness's made-up origin opts in, and a test page loaded from the public address does not. */
|
||||
const apiAgentLocal=(p,h)=>p==='http:'&&(h==='localhost'||/\.localhost$/.test(h)||/^\[[0-9a-f:.]+\]$/i.test(h)||/^\d{1,3}(\.\d{1,3}){3}$/.test(h));
|
||||
const API_AGENT_OK=apiAgentLocal(location.protocol,location.hostname)||!!window.__TUBES_TEST__&&location.hostname==='tests.invalid';
|
||||
const apiAgentMs=()=>API_AGENT_PREFS.ms;
|
||||
const apiMsLabel=ms=>ms>=60000?tr('settings.n_min',{n:Math.round(ms/60000)}):tr('settings.n_sec',{n:Math.round(ms/1000)});
|
||||
const apiAgentMsLabel=()=>apiAgentMs()>0?apiMsLabel(apiAgentMs()):tr('settings.agent_s_clock');
|
||||
|
||||
/* The speed a locked clock runs at: the pace while a tool is connected, else held (0); always 0 on the agent's clock,
|
||||
where only advance moves days; and only in a game with a clock (the rule the pause buttons follow). */
|
||||
function apiAgentSpeed(){const r=API_RELAY;return r.on&&r.tools>0&&apiAgentMs()>0&&S&&rule('clock')?DAY_MS/apiAgentMs():0;}
|
||||
|
||||
// k: 'on' (true/false) or 'ms' (one of API_AGENT_MS). Anything else is ignored, never coerced.
|
||||
function apiAgentSet(k,v){
|
||||
if(k==='on')API_AGENT_PREFS.on=v===true||v==='1'||v===1;
|
||||
else if(k==='ms'){if(!API_AGENT_MS.includes(+v))return;API_AGENT_PREFS.ms=+v;}
|
||||
else return;
|
||||
try{localStorage.setItem(API_AGENT_KEY,JSON.stringify(API_AGENT_PREFS));}catch(e){}
|
||||
apiAgentSync();}
|
||||
|
||||
/* Locks or frees the clock to match the switch, and keeps the speed where it belongs. Switching on leaves the save's
|
||||
speed alone (save() does not overwrite it while the clock is locked), so switching off puts back the one the player
|
||||
left the game at. Safe to run any number of times. */
|
||||
function apiAgentSync(){
|
||||
const on=!RW_IN&&API_AGENT_OK&&API_AGENT_PREFS.on;
|
||||
if(on!==UI.clockLocked){
|
||||
if(on&&S&&[0,0.5,1,2,4,8].includes(UI.speed))S.uiSpeed=UI.speed;
|
||||
UI.clockLocked=on;
|
||||
if(!on)UI.speed=S&&[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:(UI.lastSpeed||1);}
|
||||
if(on)UI.speed=apiAgentSpeed();
|
||||
apiRelaySync();
|
||||
apiTickerSync();
|
||||
renderHUD();renderTabbar();}
|
||||
|
||||
/* What the game draws for a locked clock: the badge in the HUD in place of the speed buttons, and on phones the two
|
||||
tab bar slots of play and speed, disabled, the second one reading the pace. */
|
||||
function apiAgentHud(){
|
||||
const p=$('spPace');if(!p)return;
|
||||
p.hidden=!UI.clockLocked;
|
||||
if(UI.clockLocked)p.textContent=apiAgentMs()>0?tr('settings.pace_t_per_day',{t:apiAgentMsLabel()}):apiAgentMsLabel();}
|
||||
function apiAgentTabbar(){
|
||||
return `<button class="play${UI.speed?'':' paused'}" disabled aria-label="${UI.speed?tr('common.pause'):tr('common.play')}"><span class="ic" aria-hidden="true">${UI.speed?'❚❚':'▶'}</span>${UI.speed?tr('common.pause'):tr('common.play')}</button>`+
|
||||
`<button class="pace" disabled aria-label="${tr('common.game_speed')}"><span class="ic" aria-hidden="true">${apiAgentMs()>0?apiAgentMsLabel():'🤖'}</span>${tr('common.speed')}</button>`;}
|
||||
|
||||
/* The Settings section. Its buttons are the agent's own (data-agent-set, answered below), not game actions, so no
|
||||
tool can find them on a screen and switch the agent off, or on. */
|
||||
function apiAgentSettings(){
|
||||
if(!API_AGENT_OK)return '';
|
||||
const b=(v,l,on)=>`<button class="b ${on?'pink sm':'ghost sm'}" data-agent-set="${v}">${l}</button>`;
|
||||
const line=(lab,btns,note)=>`<div class="setline"><span>${lab}</span><div class="seg">${btns}</div></div><p class="meta" style="margin:0 0 6px">${note}</p>`;
|
||||
return `<h3 class="sub4">${tr('settings.agent_api')}</h3>`+
|
||||
line(tr('settings.let_an_ai_agent_drive_this_game'),b('on:1',tr('common.on'),API_AGENT_PREFS.on)+b('on:0',tr('common.off'),!API_AGENT_PREFS.on),tr('settings.while_agent_mode_is_on_the'))+
|
||||
line(tr('settings.the_clock_while_an_agent_plays'),API_AGENT_MS.map(m=>b('ms:'+m,m?apiMsLabel(m):tr('settings.the_agent_moves_it'),apiAgentMs()===m)).join(''),tr('settings.a_pace_runs_one_simulated_day'));}
|
||||
function apiAgentClick(e){
|
||||
const el=e.target&&e.target.closest&&e.target.closest('[data-agent-set]');if(!el||el.disabled)return;
|
||||
const [k,v]=String(el.dataset.agentSet).split(':');
|
||||
apiAgentSet(k,k==='on'?v==='1':v);sfx('click');refreshSettings();}
|
||||
|
||||
/* Who opened the window on screen: the player (a click, a key, a picker: window.event is the input being handled), or
|
||||
the game itself (a day, a tool's call inside a relay message). A tool leaves the player's windows alone. */
|
||||
const API_MODAL={hand:false};
|
||||
const apiByHand=()=>{const e=window.event;return !!e&&/^(click|keydown|keyup|pointerup|touchend|change|input|submit)$/.test(e.type);};
|
||||
|
||||
// Wires agent mode into the page: the hooks, the badge and its style, the Settings buttons. Once, at load.
|
||||
function apiAgentStart(){
|
||||
if(RW_IN)return;
|
||||
Object.assign(HOOKS,{speed:apiAgentSpeed,hud:apiAgentHud,tabbar:apiAgentTabbar,settings:apiAgentSettings,modal:open=>{API_MODAL.hand=open&&apiByHand();}});
|
||||
const sp8=$('sp8');
|
||||
if(sp8&&!$('spPace')){const p=document.createElement('span');p.id='spPace';p.hidden=true;sp8.after(p);}
|
||||
const st=document.createElement('style');
|
||||
st.textContent='.speed #spPace[hidden]{display:none}#spPace{border:2.5px solid var(--ink);background:var(--sun);border-radius:9px;height:32px;padding:0 8px;display:flex;align-items:center;font-family:var(--display);font-weight:800;font-size:12.5px;white-space:nowrap}'+
|
||||
'#tabbar button.pace .ic{font-size:13px;line-height:1.25}';
|
||||
document.head.appendChild(st);
|
||||
document.addEventListener('click',apiAgentClick);
|
||||
apiAgentSync();}
|
||||
77
src/agent/80-relay.js
Normal file
77
src/agent/80-relay.js
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
/* ================= AGENT RELAY: the in-page transport =================
|
||||
With agent mode on (75-mode.js), the page dials the agent relay (scripts/agent/relay.js, which npm run dev hosts on
|
||||
its own port) and answers tool calls from connected tools (the MCP server, node scripts/mcp.js --browser) through
|
||||
TUBES.call, so a human follows along on the real UI: toasts fire, panels render, the map moves.
|
||||
|
||||
No endpoint to configure and no token: the relay rides the server that served the page, same port, path
|
||||
API_RELAY_PATH, so the endpoint is where the page already is. The relay refuses a page from any other origin and a
|
||||
Host that is a name, so no website can reach it through the player's browser; who else can reach it is the
|
||||
operator's choice of bind address. No eval ever: a message is JSON with a tool name from TUBES.tools, a fixed list,
|
||||
answered as the relay (ctx.relay): the player's game, clock, windows and settings stay theirs, and the dice stay
|
||||
hidden. Nothing dials or polls while the switch is off.
|
||||
|
||||
API_RELAY_HOST is a var because tests point it at their relay (under __TUBES_TEST__ nothing dials unless the test
|
||||
opts in with __AGENT_RELAY_TEST__): a jsdom page is not loaded from the relay's server. */
|
||||
var API_RELAY_HOST=''; // tests: '127.0.0.1:<port>'; live pages use their own host
|
||||
const API_RELAY={ws:null,on:false,timer:null,tries:0,said:false,tools:0,host:null,queue:null};
|
||||
const API_RELAY_PATH='/agent';
|
||||
const apiRelayUrl=()=>`ws://${API_RELAY_HOST||location.host}${API_RELAY_PATH}`;
|
||||
|
||||
/* The relay reports tool presence on every connect and disconnect: the clock holds while no tool is connected and
|
||||
runs again the moment one arrives. A missing relay (dial failed, retry backoff) holds it too. */
|
||||
function apiRelayPresence(tools){
|
||||
API_RELAY.tools=tools|0;
|
||||
if(!UI.clockLocked||!API_RELAY.on)return;
|
||||
const run=apiAgentSpeed();
|
||||
if(run!==UI.speed){UI.speed=run;renderHUD();}}
|
||||
|
||||
function apiRelaySync(){
|
||||
const want=!RW_IN&&UI.clockLocked&&(!window.__TUBES_TEST__||!!window.__AGENT_RELAY_TEST__);
|
||||
// Nothing to do when the switch and the endpoint stand: tearing a healthy dial down for nothing drops the calls in
|
||||
// flight and holds the clock for no reason.
|
||||
if(API_RELAY_HOST===API_RELAY.host&&API_RELAY.on===want&&(want?!!(API_RELAY.ws||API_RELAY.timer):true))return;
|
||||
clearTimeout(API_RELAY.timer);API_RELAY.timer=null;API_RELAY.tries=0;
|
||||
if(API_RELAY.ws){const w=API_RELAY.ws;API_RELAY.ws=null;try{w.close();}catch(e){}}
|
||||
API_RELAY.on=want;API_RELAY.host=API_RELAY_HOST;
|
||||
apiRelayPresence(0); // off the relay: nobody driving, the clock holds
|
||||
if(want)apiRelayDial();}
|
||||
|
||||
// Dev reloads and relay restarts heal on their own, without a spinning reconnect.
|
||||
function apiRelayRetry(){
|
||||
if(!API_RELAY.on)return;
|
||||
const wait=Math.min(15000,500*Math.pow(2,Math.min(API_RELAY.tries++,5)));
|
||||
API_RELAY.timer=setTimeout(()=>{API_RELAY.timer=null;apiRelayDial();},wait);}
|
||||
|
||||
/* One call, answered in order: calls queue behind each other, so a move sent while days are still running waits for
|
||||
them, as the tool sent it. A promise (days the player watches) is awaited; a throw is the tool's error. */
|
||||
function apiRelayAnswer(ws,m){
|
||||
const dayBefore=S?S.day:null,send=o=>{if(API_RELAY.ws===ws)ws.send(JSON.stringify({kind:'result',id:m.id,dayBefore,dayAfter:S?S.day:null,...o}));};
|
||||
const run=()=>Promise.resolve().then(()=>TUBES.call(m.tool,m.args||{},{relay:true}))
|
||||
.then(value=>send({value}),er=>send({error:String(er&&er.message||er)}));
|
||||
API_RELAY.queue=(API_RELAY.queue||Promise.resolve()).then(run);}
|
||||
|
||||
function apiRelayDial(){
|
||||
if(!API_RELAY.on)return;
|
||||
let ws;
|
||||
try{ws=new WebSocket(apiRelayUrl());}catch(e){return apiRelayRetry();}
|
||||
API_RELAY.ws=ws;
|
||||
ws.onopen=()=>{
|
||||
if(API_RELAY.ws!==ws)return;
|
||||
ws.send(JSON.stringify({kind:'auth',role:'page'}));
|
||||
API_RELAY.tries=0;
|
||||
if(!API_RELAY.said){API_RELAY.said=true;toast(tr('settings.agent_relay_connected'),'good');}};
|
||||
ws.onmessage=e=>{
|
||||
if(API_RELAY.ws!==ws)return;
|
||||
let m;try{m=JSON.parse(e.data);}catch(_){return;}
|
||||
if(!m||typeof m!=='object')return;
|
||||
if(m.kind==='presence'){apiRelayPresence(m.tools);return;}
|
||||
if(m.kind!=='call'||m.id===undefined)return;
|
||||
// A call this page cannot make sense of is answered, never ignored: a silent drop would hang the tool that sent it.
|
||||
if(typeof m.tool!=='string'||!TUBES.tools.includes(m.tool)){ws.send(JSON.stringify({kind:'result',id:m.id,error:`no tool "${m.tool}" here`}));return;}
|
||||
apiRelayAnswer(ws,m);};
|
||||
// Replaced (4000): another tab took the relay, so this one yields instead of fighting it: redialing would just
|
||||
// replace the new tab back, forever. Toggling agent mode dials again.
|
||||
ws.onclose=e=>{if(API_RELAY.ws!==ws)return;API_RELAY.ws=null;
|
||||
apiRelayPresence(0); // off the relay: the clock holds
|
||||
if(e&&e.code===4000)API_RELAY.on=false;else apiRelayRetry();};
|
||||
ws.onerror=()=>{};}
|
||||
24
src/agent/85-ticker.js
Normal file
24
src/agent/85-ticker.js
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
/* ================= AGENT MODE: the clock where frames do not run =================
|
||||
A paced clock runs through the game's own loop (UI.speed is the pace, runClock() the days), but frames stop in a
|
||||
hidden tab, and the frame runs no days behind an open window. Agent mode keeps time in both: a hidden tab is the
|
||||
normal place for an agent to drive while the player does something else, and an agent that deliberates over a
|
||||
window pays for it in days. This ticker covers exactly those moments, under the frame's other conditions, and
|
||||
leaves every other moment to the frame. Hidden-tab timers are throttled (to 1 Hz, after five minutes to once a
|
||||
minute in Chrome), so an unthrottled worker posts the ticks; a plain interval is the fallback without Worker.
|
||||
The agent's clock (pace 0) needs no ticks: its days run when the agent asks. Never under __TUBES_TEST__: tests call
|
||||
apiAgentTick() by hand. */
|
||||
const API_TICKER={on:false,worker:null,interval:null,last:0};
|
||||
// Days for the time since the last tick, if the frame is not running them now.
|
||||
function apiAgentTick(now=performance.now()){
|
||||
const dt=API_TICKER.last?Math.max(0,Math.min(1000,now-API_TICKER.last)):0;API_TICKER.last=now;
|
||||
const behind=document.visibilityState==='hidden'||!$('modal').hidden;
|
||||
if(behind&&UI.clockLocked&&S&&!S.lost&&UI.speed&&!pzOn())runClock(dt);}
|
||||
function apiTickerSync(){
|
||||
const want=UI.clockLocked&&apiAgentMs()>0&&!window.__TUBES_TEST__;
|
||||
if(want===API_TICKER.on)return;API_TICKER.on=want;API_TICKER.last=0;
|
||||
if(!want){if(API_TICKER.worker){try{API_TICKER.worker.terminate();}catch(e){}API_TICKER.worker=null;}
|
||||
if(API_TICKER.interval){clearInterval(API_TICKER.interval);API_TICKER.interval=null;}return;}
|
||||
try{const url=URL.createObjectURL(new Blob(['setInterval(()=>postMessage(0),250)'],{type:'text/javascript'}));
|
||||
API_TICKER.worker=new Worker(url);URL.revokeObjectURL(url);
|
||||
API_TICKER.worker.onmessage=()=>apiAgentTick();}
|
||||
catch(e){API_TICKER.interval=setInterval(()=>apiAgentTick(),250);}}
|
||||
|
|
@ -1,7 +1,10 @@
|
|||
/* ================= AGENT API: the facade =================
|
||||
window.TUBES.call(tool, args) is the whole surface: one tool from API_TOOLS by name, with the MCP tool's own
|
||||
arguments, answered as plain JSON. Nothing here listens, polls or runs on the day loop: toast() is only listened to
|
||||
while a call runs. */
|
||||
arguments, answered as plain JSON (or a promise of it, for days that run where the player can watch). Nothing here
|
||||
listens, polls or runs on the day loop: toast() is only listened to while a call runs.
|
||||
ctx.relay: the call came over the relay into the player's tab (80-relay.js), where the player owns the game, its
|
||||
clock and their windows, and the dice stay hidden. */
|
||||
let API_CTX={relay:false};
|
||||
const API_TOASTS={depth:0,list:[],real:null};
|
||||
function apiTake(){const t=API_TOASTS.list;API_TOASTS.list=[];return t;}
|
||||
const apiToastLines=t=>t.map(x=>(x.kind?x.kind+': ':'')+x.text);
|
||||
|
|
@ -32,12 +35,20 @@ const API_TOOLS={
|
|||
panel:a=>apiPanel(a),
|
||||
click:a=>apiClick(a.button,a.value),
|
||||
open_link:a=>apiOpenLink(a.from,a.to),
|
||||
advance:a=>apiAdvance(a.days),
|
||||
advance:a=>API_CTX.relay?apiAdvanceLive(a.days):apiAdvance(a.days),
|
||||
clock:()=>apiClock(),
|
||||
since:a=>apiSince(a),
|
||||
};
|
||||
function apiCall(tool,args){
|
||||
function apiCall(tool,args,ctx){
|
||||
if(typeof tool!=='string'||!own(API_TOOLS,tool))apiFail(`No tool "${tool}".`);
|
||||
if(!S&&!['schema','catalog','classes','actions'].includes(tool))apiFail('No game is running.');
|
||||
if(!S&&!['schema','catalog','classes','actions','clock'].includes(tool))apiFail('No game is running.');
|
||||
const was=API_CTX;API_CTX={relay:!!(ctx&&ctx.relay)};
|
||||
apiListen(true);
|
||||
try{return API_TOOLS[tool](args&&typeof args==='object'&&!Array.isArray(args)?args:{});}
|
||||
finally{apiListen(false);}}
|
||||
let out;
|
||||
try{out=API_TOOLS[tool](args&&typeof args==='object'&&!Array.isArray(args)?args:{});}
|
||||
catch(e){apiListen(false);throw e;}
|
||||
finally{API_CTX=was;}
|
||||
if(out&&typeof out.then==='function')return out.finally(()=>apiListen(false));
|
||||
apiListen(false);
|
||||
return out;}
|
||||
window.TUBES={version:1,tools:Object.keys(API_TOOLS),call:apiCall};
|
||||
|
|
|
|||
4
src/agent/99-start.js
Normal file
4
src/agent/99-start.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
/* ================= AGENT API: start =================
|
||||
Last, once every file of the facade has loaded: agent mode wires itself in (75-mode.js). Everything before this only
|
||||
defines tables and functions. */
|
||||
apiAgentStart();
|
||||
|
|
@ -1,5 +1,9 @@
|
|||
/* ================= STATE ================= */
|
||||
let S=null, R=emptyR();
|
||||
const UI={sel:null,tab:'cust',left:'goals',speed:1,hover:null,drag:null,snap:null,pending:null,confirm:null,leftOpen:false,muted:false,startCity:'fra',hintOff:false};
|
||||
const UI={sel:null,tab:'cust',left:'goals',speed:1,hover:null,drag:null,snap:null,pending:null,confirm:null,leftOpen:false,muted:false,startCity:'fra',hintOff:false,clockLocked:false};
|
||||
/* Where tools that are not part of the game (the development page's agent, src/agent/) may hook in. Empty in the page
|
||||
players get, and the game only ever calls into it with ?.(), so nothing changes there. clockLocked: the clock is not
|
||||
the player's (an agent drives): no pause, no speed buttons, no auto-pause, and the speed is HOOKS.speed()'s. */
|
||||
const HOOKS={};
|
||||
let uidN=1; const uid=()=>'i'+(Date.now()%1e7).toString(36)+(uidN++);
|
||||
function emptyR(){return {nt:{},cone:{},reachNT:0,teBlack:0,tNet:{},egT:{},netEg:{},l2lat:{},nodeLoad:{},nodeCap:{},div:{},l2:{},gfwLost:0,gfwCross:0,ef:{},egDesc:{},p95:{},peered:0,peerShare:0,load:{},useT:{},useIx:{},usePni:{},useCache:{},cityDem:{},citySrv:{},cityEye:{},latF:{},latFar:{},demTo:{},served:0,demand:0,reach:0,sessions:0,revMo:0,costMo:0,cost:{},rev:{},reachable:{},ddos:[],haul:[],tgtF:{},bbF:{},fsUse:{},ddosHot:{}};}
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,ci
|
|||
if(sc.cash)S.cash=sc.cash;if(sc.setup)sc.setup();
|
||||
for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}}
|
||||
// Every new network starts at ½ speed (#186), whatever the last one ran at: slow enough to look around, but things happen.
|
||||
UI.speed=UI.lastSpeed=rule('clock')?0.5:0;UI.resumeSpeed=null;
|
||||
UI.lastSpeed=rule('clock')?0.5:0;setSpeed(UI.lastSpeed);UI.resumeSpeed=null;
|
||||
track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city);
|
||||
toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal');
|
||||
renderAll();save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle')tutorialStart();}
|
||||
|
|
|
|||
|
|
@ -132,7 +132,7 @@ function pzBegin(def){if(!def)return;pzMkStop();mkStop();
|
|||
if(live)pzFlush();go();}
|
||||
function pzLeave(){pzMkStop();if(S&&S.ar)arStop(true);mkStop();const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false;
|
||||
if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null;
|
||||
if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
|
||||
if(sv){try{S=migrate(sv);compute();UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
|
||||
// It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told.
|
||||
if(UI.slot&&(sv||UI.loadBad)){slotBroke(UI.slot);return;}}
|
||||
renderAll();showTitle();}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
function spend(c){if(S.cash<c){toast(tr('interface.not_enough_cash_wait_for_revenue'),'bad');sfx('err');return false;}S.cash-=c;sfx('build');return true;}
|
||||
const ACT={
|
||||
linkCheck:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||linkDown(l))return;linkCheckModal(l);},
|
||||
speed:({v})=>{v=+v;if(pzOn())return;if(![0,0.5,1,2,4,8].includes(v)||(S&&!rule('clock')&&v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();},
|
||||
speed:({v})=>{v=+v;if(pzOn()||UI.clockLocked)return;if(![0,0.5,1,2,4,8].includes(v)||(S&&!rule('clock')&&v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();},
|
||||
help:()=>showHelp(),
|
||||
dash:()=>{if(!S||pzOn())return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();},
|
||||
dashClose:()=>{$('dash').hidden=true;},
|
||||
|
|
@ -34,8 +34,8 @@ const ACT={
|
|||
meetGo:({city})=>{if(!isCity(city))return;$('dash').hidden=true;ACT.focusCity({city});if(S.pops[city]){UI.tab='peer';renderPanel();}},
|
||||
toggleLeft:()=>{UI.leftOpen=!UI.leftOpen;renderLeft();},
|
||||
phoneTab:({t})=>{if(!['goals','deals','noc','nets'].includes(t))return;if($('modal').classList.contains('link-check'))closeModal();haptic(8);if(UI.leftOpen&&UI.left===t&&!UI.sel){UI.leftOpen=false;}else{UI.left=t;UI.leftOpen=true;UI.sel=null;renderPanel();}$('left').classList.remove('full');renderLeft();},
|
||||
phonePlay:()=>{if(pzOn())return;if(S&&!rule('clock'))return;haptic(10);if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();},
|
||||
phoneSpeed:()=>{if(pzOn())return;if(S&&!rule('clock'))return;haptic(8);const cur=UI.speed||UI.lastSpeed||1,i=SPEEDS.indexOf(cur),n=SPEEDS[(i+1)%SPEEDS.length];UI.speed=n;UI.lastSpeed=n;renderHUD();},
|
||||
phonePlay:()=>{if(pzOn()||UI.clockLocked)return;if(S&&!rule('clock'))return;haptic(10);if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();},
|
||||
phoneSpeed:()=>{if(pzOn()||UI.clockLocked)return;if(S&&!rule('clock'))return;haptic(8);const cur=UI.speed||UI.lastSpeed||1,i=SPEEDS.indexOf(cur),n=SPEEDS[(i+1)%SPEEDS.length];UI.speed=n;UI.lastSpeed=n;renderHUD();},
|
||||
install:()=>{if(installEvt){installEvt.prompt();installEvt.userChoice.finally(()=>{installEvt=null;});return;}
|
||||
openModal(pitchHtml(false));},
|
||||
pitchSkip:()=>{const p=UI.pendGame;UI.pendGame=null;UI.pitched=true;if(p)beginGame(...p);else closeModal();},
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ Object.assign(ACT,{
|
|||
importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();},
|
||||
importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S;
|
||||
// An import is a new network next to the others: the one playing here is saved and kept.
|
||||
try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},
|
||||
try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},
|
||||
menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)} <button class="thb rn" data-act="rename" aria-label="${tr('slots.rename_your_network')}">✏️</button></h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
|
||||
${saveFailing()?`<p class="why">${saveFailMsg()}</p>`:`<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>`}
|
||||
<div class="menu-list">
|
||||
|
|
|
|||
|
|
@ -29,6 +29,6 @@ Object.assign(ACT,{
|
|||
// No game on screen: the map stays empty behind the title.
|
||||
function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();}
|
||||
// Back from the title (or a puzzle) into a loaded network.
|
||||
function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;
|
||||
function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);
|
||||
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
|
||||
closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot;
|
|||
// Half a day (its routing still in the worker) is never saved: the day's end saves instead.
|
||||
if(RW.job&&st===S){UI.saveDue=true;UI.lastSave=performance.now();return;}
|
||||
if(!st||st.lost||st.mode==='puzzle'||!id||SLOT.no.has(id))return;
|
||||
if(st===S){S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};}const f=UI.saveFail,failed=f&&f.s===st;
|
||||
// A locked clock's speed is not the player's: the one they left the game at stays saved.
|
||||
if(st===S){if(!UI.clockLocked)S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};}const f=UI.saveFail,failed=f&&f.s===st;
|
||||
if(!force&&failed&&performance.now()-f.at<f.wait){UI.lastSave=performance.now();return;}
|
||||
UI.lastSave=performance.now();
|
||||
// Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do.
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ const SPEEDS=[0.5,1,2,4,8];
|
|||
function renderTabbar(){const tb=$('tabbar');if(!tb||(pressing&&UI.ticking))return;if(!isPhone()||!S||!UI.started||pzOn()){tb.hidden=true;document.body.classList.toggle('sheet-open',pzOn()&&isPhone()&&!!UI.sel);return;}tb.hidden=false;
|
||||
const open=UI.leftOpen&&!UI.sel,cur=UI.left||'goals',ndone=GOALS.filter(g=>S.done[g.id]!==undefined).length;
|
||||
const tab=(k,ic,l,cnt,red)=>`<button class="${open&&cur===k?'on':''}" data-act="phoneTab" data-args='{"t":"${k}"}' aria-label="${esc(l)}"><span class="ic" aria-hidden="true">${ic}</span>${esc(l)}${cnt?(cnt===' '?`<span class="cnt red dot"></span>`:`<span class="cnt${red?' red':''}">${cnt}</span>`):''}</button>`;
|
||||
const h=(rule('clock')?`<button class="play${UI.speed?'':' paused'}" data-act="phonePlay" aria-label="${UI.speed?tr('common.pause'):tr('common.play')}"><span class="ic" aria-hidden="true">${UI.speed?'❚❚':'▶'}</span>${UI.speed?tr('common.pause'):tr('common.play')}</button>`+
|
||||
// A locked clock's two buttons come from whatever locked it (HOOKS.tabbar), in the same two slots, so the tabs stay put.
|
||||
const h=(rule('clock')?UI.clockLocked&&HOOKS.tabbar?HOOKS.tabbar():`<button class="play${UI.speed?'':' paused'}" data-act="phonePlay" aria-label="${UI.speed?tr('common.pause'):tr('common.play')}"><span class="ic" aria-hidden="true">${UI.speed?'❚❚':'▶'}</span>${UI.speed?tr('common.pause'):tr('common.play')}</button>`+
|
||||
`<button data-act="phoneSpeed" aria-label="${tr('common.game_speed')}"><span class="ic" aria-hidden="true">${UI.speed===0.5?'½':(UI.lastSpeed||UI.speed||1)}×</span>${tr('common.speed')}</button>`:'')+
|
||||
(()=>{const P=scnProg();return tab('goals','🎯',tr('common.goals'),P&&!S.scn.done&&!S.scn.failed?`${Math.round(P.f*100)}%`:`${ndone}/${GOALS.length}`);})()+(()=>{const u=custStats().unhappy;return u?tab('deals','💼',tr('common.deals'),u,true):tab('deals','💼',tr('common.deals'),S.offers.length||'');})()+tab('noc','🚨','NOC',S.inc.length?' ':'',true)+tab('nets','🌐',tr('common.networks'),'');
|
||||
if(h!==UI._tb){UI._tb=h;tb.innerHTML=h;}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@ function fitHud(){const h=$('hud');if(!h)return;h.classList.remove('fit1','fit2'
|
|||
for(const c of ['fit1','fit2','fit3']){if(h.offsetHeight<=row()*1.5)break;h.classList.add(c);}}
|
||||
function renderHUD(){
|
||||
// No clock (puzzles): there is no time to speed up, so the speed buttons go.
|
||||
{const ck=!S||rule('clock');for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',UI.speed===v);b.hidden=!ck;}}}
|
||||
// A locked clock has no buttons: whoever locked it shows what it runs at (HOOKS.hud).
|
||||
{const ck=!S||rule('clock'),lk=UI.clockLocked;for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',!lk&&UI.speed===v);b.hidden=lk||!ck;}}HOOKS.hud?.();}
|
||||
$('muteBtn').style.opacity=UI.muted?.4:1;
|
||||
if(!S)return;
|
||||
if(pzOn()){$('hName').textContent=pzName(pzDef(S.pz.id)||S.pz);$('hAsn').textContent=tr('puzzles.puzzle');renderTabbar();return;}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// Keyboard focus moves into the modal, so Enter or Space can't keep pressing a hidden button behind it.
|
||||
// The link check on phones sits above the tab bar and is not modal, so the tabs stay usable.
|
||||
function openModal(html,cls=''){$('modal').className=cls;$('modalCard').setAttribute('aria-modal',cls==='link-check'&&isPhone()?'false':'true');if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;const a=document.activeElement;if(a&&a!==document.body&&!a.closest('#modal')){a.blur();const m=$('modalCard');m.tabIndex=-1;m.focus({preventScroll:true});}}
|
||||
function closeModal(){if(!$('modal').hidden)markLayer();$('modal').hidden=true;UI.pending=null;}
|
||||
function openModal(html,cls=''){HOOKS.modal?.(true);$('modal').className=cls;$('modalCard').setAttribute('aria-modal',cls==='link-check'&&isPhone()?'false':'true');if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;const a=document.activeElement;if(a&&a!==document.body&&!a.closest('#modal')){a.blur();const m=$('modalCard');m.tabIndex=-1;m.focus({preventScroll:true});}}
|
||||
function closeModal(){if(!$('modal').hidden)markLayer();$('modal').hidden=true;UI.pending=null;HOOKS.modal?.(false);}
|
||||
const NETWORK_NAMES=[
|
||||
'Packet Pals','Shinternet','Post, Telegraph & Tubes','Peering Pressure','Best Effort Telecom',
|
||||
'Mostly Online','Buffering & Sons','Lord of the Pings','The Ping Dynasty',
|
||||
|
|
|
|||
|
|
@ -15,12 +15,14 @@ const pref=k=>typeof PREFS[k]==='boolean'?PREFS[k]:PREF_DEF[k];
|
|||
// Quiet notifications: the player's choice once made, until then on in Best Effort only.
|
||||
const quietOn=()=>typeof PREFS.quiet==='boolean'?PREFS.quiet:rulePreset()==='soft';
|
||||
function setPref(k,v){if(!own(PREF_DEF,k))return;PREFS[k]=!!v;try{localStorage.setItem('sot-prefs',JSON.stringify(PREFS));}catch(e){}}
|
||||
// Stop the clock for something the player must see. Nothing happens if the game is already paused.
|
||||
function autoPause(){if(!S||!UI.speed)return false;UI.resumeSpeed=UI.speed;UI.speed=0;renderHUD();return true;}
|
||||
// Stop the clock for something the player must see. Nothing happens if the game is already paused, or not the player's.
|
||||
function autoPause(){if(!S||!UI.speed||UI.clockLocked)return false;UI.resumeSpeed=UI.speed;UI.speed=0;renderHUD();return true;}
|
||||
// Put the clock back at a speed (a new game, a loaded or resumed one): unless it is locked, then it runs as the lock says.
|
||||
function setSpeed(v){UI.speed=UI.clockLocked&&HOOKS.speed?HOOKS.speed():v;}
|
||||
const resumeAct=()=>({l:tr('common.resume'),act:'speed',args:{v:UI.resumeSpeed||1}});
|
||||
function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`<div class="setline"><span>${lab}</span><div class="seg">${segBtns(act,cur,opts)}</div></div>${note?`<p class="meta" style="margin:0 0 6px">${note}</p>`:''}`;
|
||||
const onoff=k=>[[k+':1',tr('common.on')],[k+':0',tr('common.off')]],cur=k=>k+':'+((k==='quiet'?quietOn():pref(k))?1:0);
|
||||
return `<div style="display:flex;align-items:center"><h2 style="font-size:26px">⚙️ ${tr('common.settings')}</h2><button class="x" data-act="settingsClose" aria-label="${tr('common.close')}">×</button></div><p class="tagline">${tr('settings.saved_on_this_device')}</p>
|
||||
return `<div style="display:flex;align-items:center"><h2 style="font-size:26px">⚙️ ${tr('common.settings')}</h2><button class="x" data-act="settingsClose" aria-label="${tr('common.close')}">×</button></div><p class="tagline">${tr('settings.saved_on_this_device')}</p>${HOOKS.settings?HOOKS.settings():''}
|
||||
<h3 class="sub4">${tr('settings.customers_and_alerts')}</h3>
|
||||
${seg(tr('settings.pause_when_a_customer_is_furious'),'prefSet',cur('pauseFurious'),onoff('pauseFurious'),tr('settings.the_game_stops_so_you_can'))}
|
||||
${seg(tr('settings.warn_when_a_customer_gets_unhappy'),'prefSet',cur('warnUnhappy'),onoff('warnUnhappy'),tr('settings.an_early_heads_up_below_60'))}
|
||||
|
|
|
|||
|
|
@ -40,5 +40,5 @@ cv.addEventListener('pointerup',endPtr);cv.addEventListener('pointercancel',canc
|
|||
const ZMIN=0.35,ZMAX=16;
|
||||
function zoomAt(mx,my,f){const wx=cam.x+(mx-CW/2)/cam.z,wy=cam.y+(my-CH/2)/cam.z;cam.z=clamp(cam.z*f,ZMIN,ZMAX);cam.x=wx-(mx-CW/2)/cam.z;cam.y=wy-(my-CH/2)/cam.z;wrapCam();}
|
||||
cv.addEventListener('wheel',e=>{e.preventDefault();zoomAt(e.clientX,e.clientY,Math.exp(-e.deltaY*0.0015));},{passive:false});
|
||||
addEventListener('keydown',e=>{if(e.key==='Enter'&&e.target.id==='metIn'){ACT.metricSet({id:e.target.dataset.id});return;}if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'&&(!S||rule('clock'))&&!pzOn()){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}});
|
||||
addEventListener('keydown',e=>{if(e.key==='Enter'&&e.target.id==='metIn'){ACT.metricSet({id:e.target.dataset.id});return;}if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'&&(!S||rule('clock'))&&!pzOn()&&!UI.clockLocked){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}});
|
||||
|
||||
|
|
|
|||
|
|
@ -8,15 +8,18 @@ function frame(now){
|
|||
if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save();
|
||||
// The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them.
|
||||
if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}
|
||||
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()){acc+=dt*UI.speed;let n=0;
|
||||
// With the route worker one day is in flight at a time; time does not pile up behind it.
|
||||
if(rwOn()){if(!RW.w)rwStart();if(RW.job)acc=Math.min(acc,DAY_MS);else if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);try{rwDay();}catch(e){tickErr(e);}}}
|
||||
else{while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;}
|
||||
if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}}}
|
||||
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn())runClock(dt);
|
||||
if((UI.speed||pzOn())&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */
|
||||
const t=animOn()?animT:0;
|
||||
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;}
|
||||
}
|
||||
// dt of real time at UI.speed: the days it adds up to. The frame calls it; so may a clock that also runs where frames
|
||||
// do not (src/agent/, a hidden tab), under the frame's own conditions otherwise.
|
||||
function runClock(dt){acc+=dt*UI.speed;let n=0;
|
||||
// With the route worker one day is in flight at a time; time does not pile up behind it.
|
||||
if(rwOn()){if(!RW.w)rwStart();if(RW.job)acc=Math.min(acc,DAY_MS);else if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);try{rwDay();}catch(e){tickErr(e);}}}
|
||||
else{while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;}
|
||||
if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}}}
|
||||
/* On a phone the NOC dashboard (or the bank), scrolled past its top edge, covers the whole map. Drawing the map
|
||||
under it is work nobody sees, so it waits until the map shows again (and no payday money piles up meanwhile). */
|
||||
function mapHidden(){for(const id of ['dashCard','bankCard']){const c=$(id);if(c.parentNode.hidden)continue;
|
||||
|
|
@ -38,7 +41,7 @@ function boot(data){
|
|||
if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();}
|
||||
else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv;
|
||||
let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
|
||||
if(okSave){slotIn(UI.slot,stamp);UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;
|
||||
if(okSave){slotIn(UI.slot,stamp);UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);
|
||||
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
|
||||
renderAll();if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);}
|
||||
if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});}
|
||||
|
|
|
|||
|
|
@ -3850,19 +3850,30 @@
|
|||
"security_and_china.tier_scrubbing_center_online_in_city":"<b>{tier} scrubbing center online in {city}.</b><br>Attacks up to {g} are cleaned, and you can sell DDoS protection.",
|
||||
"security_and_china.tier_scrubbing_unlocks_at_customer":"<b>{tier} scrubbing unlocks at customer level {lv}.</b>",
|
||||
"security_and_china.you_counter_flooded_a_hospital_in":"You counter-flooded a hospital in a country you cannot pronounce.",
|
||||
"settings.a_pace_runs_one_simulated_day":"A pace runs one simulated day every 30 seconds to 5 minutes, and the agent has to keep up. Moved by the agent, the clock stands still until the agent asks for days.",
|
||||
"settings.agent_api":"Agent API",
|
||||
"settings.agent_relay_connected":"Agent relay connected: a tool can now drive this game in this tab.",
|
||||
"settings.agent_s_clock":"Agent's clock",
|
||||
"settings.an_early_heads_up_below_60":"An early heads-up below 60% happiness, long before they are furious.",
|
||||
"settings.auto_follows_your_device_s_reduce":"Auto follows your device’s reduce-motion setting. Off freezes the map: no moving packets, pulses or floating text.",
|
||||
"settings.customers_and_alerts":"Customers and alerts",
|
||||
"settings.display_and_sound":"Display and sound",
|
||||
"settings.for_reporting_layout_bugs_shows_what":"For reporting layout bugs: shows what your screen tells the game.",
|
||||
"settings.let_an_ai_agent_drive_this_game":"Let an AI agent drive this game",
|
||||
"settings.n_min":"{n} min",
|
||||
"settings.n_sec":"{n} s",
|
||||
"settings.only_trouble_and_milestones_pop_up":"Only trouble and milestones pop up; everything else goes quietly into the NOC log. On by default in Best Effort.",
|
||||
"settings.pace_t_per_day":"{t} per simulated day",
|
||||
"settings.pause_on_outages_that_hurt":"Pause on outages that hurt",
|
||||
"settings.pause_when_a_customer_is_furious":"Pause when a customer is furious",
|
||||
"settings.quiet_notifications":"Quiet notifications",
|
||||
"settings.saved_on_this_device":"Saved on this device.",
|
||||
"settings.stops_the_game_when_a_failure":"Stops the game when a failure costs you real traffic, not when it reroutes by itself.",
|
||||
"settings.the_agent_moves_it":"The agent moves it",
|
||||
"settings.the_clock_while_an_agent_plays":"The clock while an agent plays",
|
||||
"settings.the_game_stops_so_you_can":"The game stops so you can fix their service before they cancel. Most useful at high speed.",
|
||||
"settings.warn_when_a_customer_gets_unhappy":"Warn when a customer gets unhappy",
|
||||
"settings.while_agent_mode_is_on_the":"While agent mode is on, the clock is not yours. With a pace it runs by itself and cannot be paused by hand, not even by an open window (yours included), and it waits while no agent is connected. Or the agent moves it, and nothing happens until it asks for days. The page connects to the local agent relay (npm run dev hosts one), so tools like the MCP server can drive this game while you watch.",
|
||||
"share_card.build_the_internet_one_tube_at":"Build the internet, one tube at a time",
|
||||
"share_card.n_in_r_regions":"{n} in {r} regions",
|
||||
"share_card.not_this_time":"not this time",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue