Multiplayer for self-hosted copies: sessions, server-side saves, a leaderboard
Off unless the page is built with MP_API set (MP_API=/api/mp npm run build): a plain build has no door, no chip and makes no requests. The session server is scripts/mp-server.js (npm run mp), plain node:http, which can also serve the built site so one process sits behind the reverse proxy; docs/MULTIPLAYER.md has the nginx and Caddy setups. A session has a six-character code, one seed and one rules preset, so every player starts in the same world, and up to twelve players with their own AS numbers. Saves go to the server on a new game day at most every 15 s and when the page hides, ordered by a sequence number (409 on a stale push, and the player picks which one to keep). Tokens live in localStorage, never in the save; the server keeps only their hash. A #mp= link moves a network to another device. The session panel shows the leaderboard, the feed and a short chat; each player's public card (tier, POPs, links, exchanges, transit, peak, customers, score) carries what in-game peering between players will need next. Server limits: body sizes, one upload per player, uploads per address and in total, sessions per hour, wrong-code lockout; addresses counted per IPv6 /64, X-Forwarded-For only with --trust-proxy.
This commit is contained in:
parent
2b48a6ad65
commit
95aa9b6532
39 changed files with 2757 additions and 24 deletions
|
|
@ -22,7 +22,7 @@ function showTitle(){
|
|||
${top?`<div class="btns tcont" style="margin-bottom:6px">${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}</div>`:''}
|
||||
${many?slotsHtml():''}
|
||||
<label class="f" for="nmIn">${tr('title.name_your_network')}</label><div class="network-name"><div class="nmwrap"><input class="t" id="nmIn" maxlength="24" value="${esc(UI.nm)}" autocomplete="off"><button class="reroll" data-act="randomName" aria-label="${tr('common.another_one')}" title="${tr('common.another_one')}">↻</button></div><div class="asnwrap"><span aria-hidden="true">AS</span><input class="t" id="asnIn" inputmode="numeric" maxlength="10" value="${esc(UI.asnTxt==null?'':UI.asnTxt)}" placeholder="${UI.asnSug}" aria-label="${tr('title.as_number')}" autocomplete="off"></div></div>
|
||||
${doorsHtml()}
|
||||
${doorsHtml()}${MP_API?mpDoorHtml():''}
|
||||
<label class="f" id="homeLbl" for="homeSel">${tr('title.pick_your_home_city')}</label>${homePick()}<p class="note" id="homeWhat">${homeWhat()}</p>
|
||||
<div class="btns cta tcta" style="margin-top:16px">${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">${tr('title.source_on_github')}</a> · <a href="${SIGNAL}" target="_blank" rel="noopener">${tr('title.chat_on_signal')}</a> · ${tr('title.cookieless_stats_no_tracking')}</p>`);
|
||||
$('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;});
|
||||
|
|
@ -44,8 +44,10 @@ const DOORS=[['puzzle','🧩',tr('title.puzzles'),tr('title.one_network_one_knot
|
|||
const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scenarios'};
|
||||
// The chosen preset in one line: its joke, then what actually changes.
|
||||
const presetWhat=k=>`${esc(PRESETS[k].d)} <span class="meta">${esc(PRESETS[k].x)}</span>`;
|
||||
// The Normal presets, one toggle each: on the title screen, and for a multiplayer session (48-multiplayer.js).
|
||||
const presetBtns=pr=>`<label class="f">${tr('title.how_much_trouble')}</label><div class="presets">${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return `<button class="preset${k===pr?' on':''}" data-preset="${k}" data-act="presetSet" data-args='{"p":"${k}"}' aria-pressed="${k===pr}"><i aria-hidden="true">${P.i}</i><b>${P.n}</b></button>`;}).join('')}</div><p class="note" id="presetWhat">${presetWhat(pr)}</p>`;
|
||||
function doorsHtml(){const m=UI.mode==='sandbox'?'sandbox':'normal',pr=own(PRESETS,UI.preset)&&NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',ch=own(CHAOS,UI.sbChaos)?UI.sbChaos:'none';
|
||||
return `<label class="f">${tr('title.pick_a_door')}</label><div class="doors">${DOORS.map(([k,i,n,d])=>`<button class="door${k===m?' on':''}" data-door="${k}" data-act="${doorAct[k]}" data-args='${k==='sandbox'||k==='normal'?`{"m":"${k}"}`:'{}'}'><i aria-hidden="true">${i}</i><b>${n}</b><span>${d}</span>${k==='puzzle'&&pzWkNew()||k==='scn'&&wsNew()?`<em class="pznew">${tr('puzzles.new_this_sunday')}</em>`:''}</button>`).join('')}</div>
|
||||
<div id="doorNormal"${m==='normal'?'':' hidden'}><label class="f">${tr('title.how_much_trouble')}</label><div class="presets">${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return `<button class="preset${k===pr?' on':''}" data-preset="${k}" data-act="presetSet" data-args='{"p":"${k}"}' aria-pressed="${k===pr}"><i aria-hidden="true">${P.i}</i><b>${P.n}</b></button>`;}).join('')}</div><p class="note" id="presetWhat">${presetWhat(pr)}</p></div>
|
||||
<div id="doorNormal"${m==='normal'?'':' hidden'}>${presetBtns(pr)}</div>
|
||||
<div id="doorSandbox"${m==='sandbox'?'':' hidden'}><label class="f">${tr('title.chaos_in_your_sandbox')}</label><div class="chaos">${Object.entries(CHAOS).map(([k,C])=>`<button class="chs${k===ch?' on':''}" data-chaos="${k}" data-act="chaosSet" data-args='{"c":"${k}"}'><i aria-hidden="true">${C.i}</i><b>${C.n}</b><span>${C.d}</span></button>`).join('')}</div></div>
|
||||
<p class="note lockn">🔒 ${tr('title.rules_are_picked_once_and_locked')}</p>`;}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ const slotIcon=e=>e.broken?'🩹':e.mode==='scenario'?'🏆':e.mode==='sandbox'?
|
|||
// The network to continue: the most recent one that is not open in another window (or damaged).
|
||||
function slotTop(list){return slotByAt(list).find(e=>!e.broken&&!slotBusy(e.id))||null;}
|
||||
function slotLine(e){if(e.broken)return tr('slots.damaged_export_or_delete');
|
||||
const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier);
|
||||
const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier);if(MP_API&&e.mp)bits.push('🌐 '+mpShow(e.mp.slice(0,6)));
|
||||
return bits.filter(Boolean).join(' · ');}
|
||||
function slotRow(e,top){const busy=slotBusy(e.id),nm=esc(e.name||tr('common.unnamed_network'));
|
||||
const tag=busy?`<span class="tag">${tr('slots.open_in_another_window')}</span>`:top?`<span class="tag">▶ ${tr('slots.continue')}</span>`:'';
|
||||
|
|
|
|||
73
src/game/95-modals/48-multiplayer.js
Normal file
73
src/game/95-modals/48-multiplayer.js
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
/* Multiplayer on screen (89-multiplayer.js has the logic): the title screen's door, the start/join sheet, the session
|
||||
panel (leaderboard, feed and chat, the code to share, the link to another device) and the HUD chip. Only ever drawn
|
||||
when the build stamped MP_API. Everything another player wrote is escaped here. */
|
||||
const MP_FEED_L={join:N_('mp.feed_join'),leave:N_('mp.feed_leave'),t2:N_('mp.feed_t2'),t1:N_('mp.feed_t1'),t1first:N_('mp.feed_t1first')};
|
||||
const mpDoorHtml=()=>`<div class="mpdoor-row"><button class="door mpdoor" data-act="mpDoor"><i aria-hidden="true">🌐</i><b>${tr('mp.multiplayer')}</b><span>${tr('mp.door_d')}</span></button></div>`;
|
||||
function mpStartHtml(){const pr=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall';
|
||||
return `<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">🌐 ${tr('mp.multiplayer')}</div><h2 style="font-size:26px">${tr('mp.play_with_friends')}</h2></div><button class="x" data-act="mpBack" aria-label="${tr('common.close')}">×</button></div>
|
||||
<p class="tagline">${tr('mp.intro')}</p>
|
||||
<label class="f" for="mpName">${tr('title.name_your_network')}</label><input class="t" id="mpName" maxlength="24" value="${esc(UI.nm||'')}" autocomplete="off">
|
||||
<label class="f" id="homeLbl" for="homeSel">${tr('title.pick_your_home_city')}</label>${homePick()}<p class="note" id="homeWhat">${homeWhat()}</p>
|
||||
<div class="mpbox"><h3>${tr('mp.start_a_session')}</h3>${presetBtns(pr)}
|
||||
<label class="f" for="mpTitle">${tr('mp.session_title')}</label><input class="t" id="mpTitle" maxlength="40" autocomplete="off">
|
||||
<div class="btns">${btn(tr('mp.start_a_session'),'mpStart',{},'pink big mpgo')}</div></div>
|
||||
<div class="mpbox"><h3>${tr('mp.join_a_session')}</h3><label class="f" for="mpCode">${tr('mp.code')}</label>
|
||||
<div class="mpjoin"><input class="t" id="mpCode" maxlength="8" placeholder="K7Q-2XD" autocomplete="off" autocapitalize="characters" spellcheck="false">${btn(tr('mp.join'),'mpJoin',{},'big mpgo')}</div>
|
||||
<p class="note">${tr('mp.join_note')}</p></div>
|
||||
<p class="note" id="mpBusy" hidden>${tr('mp.talking')}</p>
|
||||
<div class="btns cta">${btn(tr('common.back'),'mpBack',{},'ghost')}</div>`;}
|
||||
function mpBusy(on){UI.mpBusy=on;document.querySelectorAll('.mpgo').forEach(b=>{b.disabled=on;});const b=$('mpBusy');if(b)b.hidden=!on;}
|
||||
function mpErr(e){const st=e&&e.status;sfx('err');
|
||||
toast(st===404?tr('mp.err_no_session'):st===409?tr('mp.err_full'):st===429?tr('mp.err_slow'):st===503?tr('mp.err_server_full'):st===400?tr('mp.err_refused'):tr('mp.err_offline'),'bad');}
|
||||
const mpNameIn=()=>{const n=$('mpName'),v=String((n&&n.value)||UI.nm||randomNetworkName()).trim().slice(0,24)||randomNetworkName();UI.nm=v;return v;};
|
||||
// The server said yes: the token goes to this browser's storage, the rest into a new game.
|
||||
function mpBegin(j,nm,home,joined){const m=mpJoinOk(j);if(!m){toast(tr('mp.err_offline'),'bad');return;}
|
||||
mpTokSet(m.code,m.pid,m.token);delete m.token;beginGame(nm,home,{mode:'normal',preset:m.preset,mp:{...m,joined}});}
|
||||
// Called by beginGame just before its first save, which then pushes the day-0 save and the card: this player is on the
|
||||
// leaderboard at once, and a link to another device works from the start.
|
||||
function mpStarted(m){mpReset({day:-1,last:-1e9});mpHud();UI.mpLater={joined:!!(m&&m.joined)};}
|
||||
// The code to share, with its buttons. A new Normal game asks for its charter first, on top of everything: the code
|
||||
// waits until it is signed (ACT.charter), or its buttons could not be pressed.
|
||||
function mpStartTell(){const b=UI.mpLater;if(!b||!mpIs())return;if(!$('modal').hidden&&$('modal').className==='charter')return;UI.mpLater=null;
|
||||
const code=mpShow(S.mp.code),acts=[{l:tr('common.share'),act:'mpShare',args:{}},{l:tr('mp.session'),act:'mpOpen',args:{}}];
|
||||
toast(b.joined?tr('mp.joined',{code}):tr('mp.session_live',{code}),'goal',acts);}
|
||||
/* ---------- the session panel ---------- */
|
||||
function mpBoardHtml(){const r=MP.roster;if(MP.gone)return `<p class="why">${tr('mp.not_in_session')}</p>`;
|
||||
// Another device moved on: the toast with the choice is long gone, the choice stays here until it is made.
|
||||
const st=MP.stale?`<p class="why">${tr('mp.moved_on_elsewhere')}</p><div class="btns">${btn(tr('mp.load_newer'),'mpNewer',{},'pink')}${btn(tr('mp.keep_mine'),'mpKeep',{},'')}</div>`:'';
|
||||
if(st)return st;if(!r)return `<p class="note">${tr('mp.loading')}</p>`;const me=S&&S.mp&&S.mp.pid;
|
||||
return mpRank(r.players).map((p,i)=>{const c=p.card,mine=p.pid===me;
|
||||
const meta=c?[`AS${p.asn}`,c.t1?'Tier 1':c.tier==='t2'?'Tier 2':'Tier 3',trn('mp.n_pops',c.pops.length),fmtG(c.peak),trn('mp.n_customers',c.cust)].join(' · '):`AS${p.asn} · ${tr('mp.no_card')}`;
|
||||
return `<div class="mprow${mine?' me':''}"><span class="mprk">${i+1}</span><i class="mpdot" style="background:${p.color}" aria-hidden="true"></i><div class="grow"><b>${esc(p.name)}</b>${mine?` <span class="tag">${tr('mp.you')}</span>`:''}<div class="meta">${meta}</div></div><small class="mpseen">${p.seen?slotAgo(p.seen):''}</small></div>`;}).join('');}
|
||||
function mpFeedHtml(){const r=MP.roster;if(!r)return '';const f=r.feed.slice(-30).reverse();if(!f.length)return `<p class="note">${tr('mp.feed_empty')}</p>`;
|
||||
const col=pid=>{const p=r.players.find(x=>x.pid===pid);return p?p.color:'#888888';};
|
||||
return f.map(x=>{const who=`<b>${esc(x.name)}</b>`,t=x.k==='chat'?`${who}: ${esc(x.text)}`:tr(MP_FEED_L[x.k],{name:who});
|
||||
return `<div class="mpf ${x.k}"><i class="mpdot" style="background:${col(x.pid)}" aria-hidden="true"></i><span class="grow">${t}</span><small>${x.at?slotAgo(x.at):''}</small></div>`;}).join('');}
|
||||
function mpPanelHtml(){const m=S.mp,code=mpShow(m.code),link=mpLink(m);
|
||||
return `<div class="mp-panel" id="mpPanel"><div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">🌐 ${tr('mp.session')} · ${esc(PRESETS[m.preset].n)}</div><h2 style="font-size:26px">${m.title?esc(m.title):tr('mp.session_code',{code})}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
|
||||
<div class="mpcode"><div class="grow"><small>${tr('mp.code')}</small><b>${code}</b></div>${btn(tr('common.share'),'mpShare',{},'pink')}</div>
|
||||
<p class="note">${tr('mp.share_note')}</p>
|
||||
<h3>${tr('mp.leaderboard')}</h3><div class="mpboard" id="mpBoard">${mpBoardHtml()}</div>
|
||||
<h3>${tr('mp.feed')}</h3><div class="mpchat"><input class="t" id="mpSay" maxlength="200" placeholder="${esc(tr('mp.say'))}" aria-label="${esc(tr('mp.say'))}" autocomplete="off">${btn(tr('mp.send'),'mpChat',{},'')}</div><div class="mpfeed" id="mpFeed">${mpFeedHtml()}</div>
|
||||
${link?`<details class="mpmove"><summary>${tr('mp.move_device')}</summary><p class="note">${tr('mp.move_note')}</p><input class="t" id="mpLink" readonly value="${esc(link)}" aria-label="${esc(tr('mp.move_device'))}"><p class="why">${tr('mp.move_warn')}</p><div class="btns">${btn(tr('mp.copy_link'),'mpCopyLink',{},'')}</div></details>`:''}
|
||||
<div class="btns cta">${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${btn(tr('mp.leave'),'mpLeaveAsk',{},'ghost')}</div></div>`;}
|
||||
// The roster moved on: only the leaderboard and the feed are redrawn, so a chat line being typed stays.
|
||||
function mpPanelUpdate(){const b=$('mpBoard'),f=$('mpFeed');if(!b||$('modal').hidden)return;b.innerHTML=mpBoardHtml();if(f)f.innerHTML=mpFeedHtml();}
|
||||
// While the panel is open, the roster every 5 s; it stops by itself once the panel is gone.
|
||||
function mpPoll(){clearInterval(MP.poll);MP.poll=null;if(!mpIs())return;mpRefresh();if(!window.__TUBES_TEST__)MP.poll=setInterval(mpPollTick,MP_POLL);}
|
||||
function mpPollTick(){if($('modal').hidden||!$('mpPanel')||!mpIs()){clearInterval(MP.poll);MP.poll=null;return;}mpRefresh(true);}
|
||||
/* The HUD chip: the session code and where you stand. A phone's top bar has no room for it (the menu has the session):
|
||||
there, and on a tablet whose top bar is still too full (fitHud's last step), where you stand is a badge on the menu
|
||||
button instead. Made the first time a session network is on screen. */
|
||||
function mpHud(){let c=$('hMp');const on=mpIs();
|
||||
if(!c){if(!on)return;c=document.createElement('button');c.className='chip mpchip hide-sm';c.id='hMp';c.dataset.act='mpOpen';
|
||||
c.innerHTML='<span class="lbl" id="hMpCode"></span><span class="val num" id="hMpRank"></span>';const n=$('hNoc');n.parentNode.insertBefore(c,n.nextSibling);
|
||||
const b=document.createElement('span');b.className='badge mpbadge num';b.id='hMpB';b.setAttribute('aria-hidden','true');const mb=document.querySelector('#hud .menubtn');if(mb)mb.appendChild(b);}
|
||||
const b=$('hMpB');c.hidden=!on;if(b)b.hidden=!on;if(!on)return;
|
||||
const r=MP.roster,i=r?mpRank(r.players).findIndex(p=>p.pid===S.mp.pid):-1,rk=i>=0?`#${i+1}/${r.players.length}`:'—';
|
||||
c.setAttribute('aria-label',tr('mp.session'));c.title=tr('mp.session');c.style.borderColor=S.mp.color;
|
||||
$('hMpCode').textContent=mpShow(S.mp.code);$('hMpRank').textContent='🌐 '+rk;if(b)b.textContent=i>=0?`#${i+1}`:'🌐';}
|
||||
// Share text: the phone's share sheet, or the clipboard.
|
||||
function mpSend(t){const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good');
|
||||
if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}
|
||||
try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}}
|
||||
Loading…
Add table
Add a link
Reference in a new issue