diff --git a/README.md b/README.md index a52509df..703a0588 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,7 @@ Personal site hosted with GitHub Pages at **https://ascoding11.github.io**, the - In-game leaderboards: every game page that loads stats.js gets a "Leaderboard" button that opens that game's boards in a panel over the page (the same boards, checks and data as the Leaderboards section of the Back Room page, which is unchanged). stats.js adds the button (`boardButton`) and, the first time it is pressed, loads `/namefilter.js` if the page hasn't and `leaderboard.js` with `data-game=""`: its game mode builds the usual section inside a dialog (`.lbd-modal`, with its own colours and type since game pages have none of the hub's CSS variables), fixed to that game, signed in through `BackRoomStats.conn()` (the connection stats.js already publishes with) instead of party.js, read when the panel opens, with the view remembered per game (`lb:view:`). Close, Escape or a press outside closes it; keys and presses inside stay inside. Where the button goes, so it never sits over play: in a game with a `#menu`, inside that menu as its last item, and while that menu is showing but its button is scrolled out of view (most menus are taller than the screen), a copy (`#brlb-pin`) is pinned bottom right and goes as soon as the real one scrolls into view, the menu is hidden or faded out, or the panel opens; on a page with no `#menu` and no canvas (the puzzles), at the end of the page; on a page with a canvas and no `#menu`, a small round button fixed bottom left that hides while the pointer is locked and for 8 s after any key or press. A game's stats.js tag can override it: `data-board="off"`, a corner (`tl`, `tr`, `bl`, `br`; 2048 uses `bl`), or `data-board-in=""` to put it inside a chosen element. A new game with a `#menu` needs nothing. The button is added inside frames too (the home page, phone page and party layer all open games in an iframe, which is how most people play); only the hidden stats sidecar frame has no stats.js of its own. - `e63334287a3deaa3/elo.js`: ranked ratings (Elo), one per game, for the online games that end with a winner: Boostball, Rumble Karts, Backrooms 1v1–4v4, Driftfall, Slipstream, Turbo Trail, Tumble Trials, Chromaflage, Odd One Out, Puffer Party, Deepword's Brawl, Lokop, Sky Duel and Hush Pools. Shell Crackers keeps its own older rating (`shellcr-rank`, `rooms/sc-ratings`) and doesn't load this file; the maths here is the same as its. Each game loads it next to stats.js (``) and calls `BackRoomElo.report({ id, won, opp: [{ u: uid, s }, { bot: 1, s }] })` once where its online match or round ends (search each game for `BackRoomElo`): `opp` is everyone you played against, not teammates, and `s` is your result against that one opponent (1 beat them or your team won, 0 lost, 0.5 drew), so team games give every opponent the same `s`, races and free-for-alls go by finishing place, Driftfall counts everyone already out as beaten and everyone still alive as a loss, Tumble Trials rates once per show (when you go out or the final ends), and in Chromaflage a seeker beats each hider that was found while a hider beats the seekers by staying hidden. Hush Pools is co-op, so it has no opponents in that sense: when an online party escapes, each player is compared with each teammate by what they did for the party (`runScore`: 10 a rescue, 4 a valve opened or the keypad solved, minus 6 for each time they went down), and the one with the higher score "beats" the other (equal is a draw). The change is the usual Elo one (K 36 for the first 10 matches, then 24), averaged over the opponents and multiplied by the number of real opponents (×1 for one, 25% more for each extra, at most ×3); bots count as rated 1000, and a match with no real opponent isn't rated, so practice and bot-only rooms never move a rating. Everyone starts at 1000 and stays in 100–3000. `id` stops a match being rated twice (results screens can be drawn more than once). Storage: this browser's `elo:` (`{ r, g, wn, pk, uid }`) and the Realtime Database at `rooms/elo-/players/` (`n, c, x, z, h, ts` as the shared rules need, plus `r, g, wn, pk`), written by the player's own browser; on load the account's saved rating wins, and opponents' ratings are read from their nodes when a match is reported. So, like every Back Room stat, it is self-reported and not cheat-proof. It never signs in or makes a Firebase app itself (it uses the game's), and every call swallows its own errors, so it can't stop a game. After a rated match a small pill at the top shows the new rating and the change. stats.js reads `elo:` into the game's `elo` stat (the list of folders is next to `READ`), and leaderboard.js has an Elo board first for each of these games (for Slipstream, after its lap and record boards); as with Shell Crackers, the board keeps the best value it has seen, so it shows a player's highest rating. To rate another game: add the script tag and one `report` call, add its folder to the list in stats.js, and add the Elo row to its entry in leaderboard.js. - `e63334287a3deaa3/netsmooth.js`: smooth movement for other players in the online games. Updates over school Wi-Fi and Firebase arrive late and in bursts, so a game that moves someone to their newest update makes them lurch and stall, and one that shows them a fixed time in the past freezes them whenever an update is later than that. Each remote player gets a `NetSmooth.lag()`, which measures how late their updates really arrive and shows them just far enough in the past that the next one is almost always already here (about a tenth of a second on good Wi-Fi, more on bad, never more than 0.45 s), easing that delay so the timeline never jumps; `NetSmooth.sample()` draws them between the two updates around that moment and carries them on for up to 0.3 s if an update is late. Used by Shell Crackers, Backrooms 1v1–4v4, Hail Mary, Coil, Quarry, Chromaflage, Odd One Out, Spire, Turbo Trail, Escapade, Updraft, Driftfall, Blockstorm, Lanternhold (teammates' pointers), Sky Duel and Putterby. Kartwheel, Slipstream, Boostball, Rumble Karts and Tumble Trials keep their own approach: cars, karts and racers are projected forward to the present from their speed, which matters more there than perfectly even motion. Settings were tuned with a simulation of good, school and bad Wi-Fi: compared with chasing the newest update, other players stall about a fifth as often and almost never lurch, for roughly a tenth of a second more delay. +- `e63334287a3deaa3/watchers.js` and spectating (Back Room). Shell Crackers, Backrooms 1v1–4v4 and Boostball can be watched without playing: the game opened as `/?watch=1#-` (the Watch buttons on the Back Room page, or a watch link: the home page or phone page with `?watch=1#sc-…`, `#br-…` or `#bb-…`) goes straight into that room as a spectator. The Watch buttons: playingnow.js adds Watch next to Join on Playing now rows for the games in its `WATCH` list, and `BackRoomPlaying.watch(uid)` gives the Online panel's rows (social.js) a Watch button next to Join; both open `/?watch=1#` in the game layer. The home page's and phone page's invite code pass `?watch=1` through for `sc-`, `br-` and `bb-` rooms only. social.js doesn't treat a game opened to watch as the game you're in, so watching sets no Online status and no Join entry for others. A spectator writes nothing inside the game room (no player node, round, events, rating or stats; stats.js and elo.js aren't loaded for it), so it never counts as a player, never hosts and never affects a match, the Leaderboards or Elo, and a full room can still be watched. It gets a Spectating banner, the players' names, a scoreboard, a Leave button (Back closes the game layer), a follow camera that steps through the players and a free camera. **The "N watching" count** is the only thing a spectator stores: `BackRoomWatchers.join` writes its own node `rooms/-_watch/players/` (`n`, `c`, `x`, `z`, `h`, `ts` as the rules require, `x`/`z`/`h` always 0, plus `r`, the room code without its prefix), refreshed every 10 s and removed on leaving or disconnecting; `BackRoomWatchers.count` reads that list and counts fresh nodes (under 30 s old) for one room. The underscore can't be typed into a room code, so no game room can have that name. **Shell Crackers** (`WATCH` / `Spec` in its script): Q / E or ← → (◀ ▶ on a phone) step through the eggs, F or Free cam (or dragging the view) flies a free camera (WASD, Space / Shift, drag to look; the move stick on a phone), Tab or Scores shows the scoreboard, Esc or Leave leaves. Its own egg stays inactive, so it never moves a capture-the-flag flag, starts or ends a match, or takes hits; the end card says who won and the next match shows when the players start it. Players see "N watching" in the line under the scores. **Backrooms 1v1–4v4** (`WATCH` in its script): it uses the game's own way of watching a match you're not in (the follow camera on any standing player, either team), straight into the room with no name or menu; Q / E or ← → (Prev / Next on a phone) or a click switch player, F (Free cam) flies through walls (WASD, Space / Shift, drag to look; the move stick on a phone), Tab (Scores) shows the teams panel, Esc or Leave leaves. Its `Net.uid` is a stand-in (`~watch`) no node has, so it never takes a player's node for its own, is never elected host and never asks for or is counted in a forfeit; it also reads the host's late-joiner piece list (`bs`) meant for anyone, so it sees what has been built. Players see "N watching" next to the room count in the lobby and under the scores in play. **Boostball** (`WATCH` / `spec` in its script): the camera is the game's own chase camera on the car being watched (bots too), or the overview behind the goal (Ball view, the last stop when stepping through); Q / E or ← → (◀ ▶) switch, F (Free) flies the camera (WASD, Space / Shift, drag to look; the move stick on a phone), the Scoreboard key (Tab) or Scores shows the table, Y toggles ball cam for this visit only, Esc or Leave leaves. Its `Net.uid` is a stand-in (`~watch`) and its join time is Infinity, so it is never the host or the ball's owner and never runs the ball, goals or the match clock; the end card names the winning team. Players see "N watching" after the team names under the clock. - `e63334287a3deaa3/autores.js`: automatic resolution for the 3D games, so they stay smooth on school laptops. Every three.js game except Quarry (which has its own version) loads it right after `three.min.js`. It watches the frame rate, and when frames drop below about 45 a second it makes every three.js renderer on the page draw at a lower resolution, a tenth at a time, down to half; when frames stay smooth it steps back up (more slowly towards a resolution that was too slow before, so it doesn't keep flipping). It multiplies whatever `setPixelRatio` the game asks for, so a game's own graphics setting still counts. The scale each game settles on is remembered in the browser (`localStorage` key `autores:`), so the next visit starts there. No game code calls it; it wraps `THREE.WebGLRenderer`. `AutoRes.scale` shows the current scale and `AutoRes.off()` turns it off for a visit. - `e63334287a3deaa3/account-nudge.js`: the sign-in nudge and account save (Back Room). Loaded on the Back Room page and the phone page (one ` - + + @@ -328,6 +348,17 @@
+ + + + @@ -583,6 +627,11 @@

Champion egg!

'use strict'; // Spanish (lang.js + es.js): words put together here go through TX; fixed page text is translated by lang.js itself. const TX=window.BackRoomLang?BackRoomLang.t:(s,v)=>String(s).replace(/\{(\w+)\}/g,(m,n)=>v&&v[n]!=null?v[n]:m); +// Spectating: ?watch=1#sc- (the Watch buttons on the Back Room page) watches that room without playing. A spectator +// writes nothing to the database: the shared rules only let a browser write rooms//players/, and every egg +// counts a node there as a player, so there is no node, no heartbeat, no round, no event, no rating and no stats.js. +const WATCH_ROOM=new URLSearchParams(location.search).get('watch')==='1'&&(/^#sc-([a-z0-9-]{1,17})$/.exec(location.hash)||[])[1]||''; +const WATCH=!!WATCH_ROOM; // ===================================================================== // Firebase (same project and Realtime Database rules as Rumble Karts). // Online rooms live under rooms/sc-, so the existing rules cover them. @@ -2429,7 +2478,7 @@

Champion egg!

} function ksFeed(e,id){ const me=e===player; - if(id==='candle')infoFeed(me?TX('Candler lit: rivals show through walls for {n} s',{n:KS_CANDLE}):TX('{n} lit a Candler: you show through walls',{n:e.name})); + if(id==='candle')infoFeed(me?TX('Candler lit: rivals show through walls for {n} s',{n:KS_CANDLE}):WATCH?TX('{n} lit a Candler',{n:e.name}):TX('{n} lit a Candler: you show through walls',{n:e.name})); else if(id==='fry')infoFeed(me?TX('The Big Fry is coming: {n} s',{n:KS_FRY}):TX('{n} called The Big Fry!',{n:e.name})); else if(id==='launcher')infoFeed(me?TX('Yolk Launcher: {n} rockets',{n:KS_ROCKETS}):TX('{n} has a Yolk Launcher',{n:e.name})); else if(me)infoFeed(id==='quick'?TX('Quick Hands: faster reloads and swaps for {n} s',{n:KS_QUICK_T}):TX('Thick Shell: less damage for {n} s',{n:KS_SHELL_T})); @@ -2636,6 +2685,7 @@

Champion egg!

// back through the node's listener (takeRound -> ctfSync); the same move isn't sent again for 0.7 s. const ctfBusy={}; function ctfDo(a){ + if(WATCH)return; // a spectator never moves a flag (the players' own browsers do, including the late returns) if(!online){const n=ctfReduce(ctfS,a);if(n)ctfSync(n);return} const key=a.a+a.k+(a.by||''),t=performance.now();if(ctfBusy[key]>t||!Net.refs||Net.matchId==null)return;ctfBusy[key]=t+700; const id=Net.matchId; @@ -2706,6 +2756,7 @@

Champion egg!

player.team=n[0]Net.uid)mover=false} ctfOdd=n[player.team]-n[1-player.team]>=2&&mover&&player.carry==null?ctfOdd+1:0; @@ -2772,7 +2823,7 @@

Champion egg!

for(let k=0;k<2;k++){const id='fm'+k,F=ctfS.f[k]; if(F.st===1&&F.by===player.id){setHid(id,true);continue} setHid(id,false); - ctfPos(k,_cf);const d=Math.round(Math.hypot(_cf.x-player.pos.x,_cf.z-player.pos.z));_cf.y+=F.st===1?2.9:2.7; + ctfPos(k,_cf);const fr=WATCH?camera.position:player.pos,d=Math.round(Math.hypot(_cf.x-fr.x,_cf.z-fr.z));_cf.y+=F.st===1?2.9:2.7; _cf.project(camera);const behind=_cf.z>1;let x=(_cf.x*.5+.5)*Wd,y=(-_cf.y*.5+.5)*Ht; let dx=x-cx,dy=y-cy;if(behind){dx=-dx;dy=-dy} const off=behind||xR||yB; @@ -3127,6 +3178,7 @@

Champion egg!

// Leaving an online match partway through counts as finishing last against the real players there. function leaveCheck(){if(state==='playing'&&mode==='online')applyRating(standings(),true)} function toMenu(){ + if(WATCH){specLeave();return} leaveCheck(); Net.leave();if(document.pointerLockElement)document.exitPointerLock(); $('hud').hidden=true;$('pause').hidden=true;$('end').hidden=true;$('menu').hidden=false; @@ -3143,20 +3195,25 @@

Champion egg!

const myRank=list.findIndex(x=>x.me)+1; $('endTitle').textContent=myRank===1?TX('Champion egg!'):TX('{n} place',{n:ordinal(myRank)}); const lead=list[0],mp=mapInfo().name; - $('endSub').textContent=myRank===1?TX('Most cracks in {map} with {k}.',{map:mp,k:lead.k}):TX('{w} won {map} with {k}.',{w:lead.name,map:mp,k:lead.k}); - if(RULES.ladder&&!mapCtf){const N=RULES.ladder.length,done=lead.g>=N; + if(lead)$('endSub').textContent=myRank===1?TX('Most cracks in {map} with {k}.',{map:mp,k:lead.k}):TX('{w} won {map} with {k}.',{w:lead.name,map:mp,k:lead.k}); + if(RULES.ladder&&!mapCtf&&lead){const N=RULES.ladder.length,done=lead.g>=N; $('endSub').textContent=done?TX(myRank===1?'You finished the ladder on {map} with the {g}.':'{w} finished the ladder on {map} with the {g}.',{w:lead.name,map:mp,g:WEAPONS[RULES.ladder[N-1]].name}): TX(myRank===1?'Time! You were furthest up the ladder: gun {n} of {m}.':'Time! {w} was furthest up the ladder: gun {n} of {m}.',{w:lead.name,n:lead.g+1,m:N})} + // (a spectator has no team of its own: player.team is only the followed egg's, so it is told which team won) if(mapCtf){const a=ctfS.s[0],b=ctfS.s[1],w=a===b?-1:a>b?0:1; - $('endTitle').textContent=w<0?TX('A draw'):w===player.team?TX('Your team wins!'):TX('{t} team wins',{t:TX(TEAM[w].n)}); + $('endTitle').textContent=w<0?TX('A draw'):w===player.team&&!WATCH?TX('Your team wins!'):TX('{t} team wins',{t:TX(TEAM[w].n)}); $('endSub').textContent=TX('Capture the flag on {map}: {a} {x} – {y} {b}.',{map:mp,a:TX(TEAM[0].n),x:a,y:b,b:TX(TEAM[1].n)})} if(fw){ - if(mapCtf)$('endTitle').textContent=fryTeam===player.team?TX('Your team wins!'):TX('{t} team wins',{t:TX(TEAM[fryTeam].n)}); - $('endSub').textContent=fw===player.id?TX('You called The Big Fry on {map}.',{map:mp}):TX('{w} called The Big Fry on {map}.',{w:fwName||list[0].name,map:mp})} + if(mapCtf)$('endTitle').textContent=fryTeam===player.team&&!WATCH?TX('Your team wins!'):TX('{t} team wins',{t:TX(TEAM[fryTeam].n)}); + $('endSub').textContent=fw===player.id?TX('You called The Big Fry on {map}.',{map:mp}):TX('{w} called The Big Fry on {map}.',{w:fwName||(lead?lead.name:TX('Someone')),map:mp})} + // a spectator: who won, nothing about a place of its own; the players' browsers start the next match. (myRank is 0 + // for a spectator, so the lines above already name the leader.) + if(WATCH&&!mapCtf){$('endTitle').textContent=lead?TX('{n} wins!',{n:lead.name}):TX('Match over'); + if(!lead)$('endSub').textContent=TX('Nobody cracked anyone on {map}.',{map:mp})} fillTable($('endTable'),list); showEndRank(applyRating(list,false)); $('hud').hidden=true;$('pause').hidden=true;$('end').hidden=false; - $('again').disabled=false;$('again').textContent=TX(online?'Next match now':'Play again'); + $('again').disabled=false;$('again').textContent=TX(online?'Next match now':'Play again');$('again').hidden=WATCH;if(WATCH)$('toMenu').textContent=TX('Leave'); endTimer=online?12:0;$('endMsg').textContent=''; voteStart();renderRulesUI(); showAd('adEnd'); @@ -3199,7 +3256,7 @@

Champion egg!

function saveRank(){store.set('rank',JSON.stringify(rank));pushRank();renderRank()} // Ratings live next to the game rooms (rooms/sc-ratings/players/), which the existing database rules allow. function pushRank(){ - if(!Net.ready||!Net.db||!rank.g)return; + if(WATCH||!Net.ready||!Net.db||!rank.g)return; Net.db.ref('rooms/sc-ratings/players/'+Net.uid).set({n:myName,c:myColor,x:0,z:0,h:0,ts:Math.round(Net.now()),r:Math.round(rank.r),g:rank.g,wn:rank.wn,pk:Math.round(rank.pk)}).catch(()=>{}); } // Called once the database is reachable: the account's saved rating wins; a brand-new account keeps this browser's. @@ -3227,7 +3284,7 @@

Champion egg!

return{delta:Math.round(K*w*sum/opp.length),humans,w,place:myPos+1,of:list.length}; } function applyRating(list,leftEarly){ - if(ratedThis||mode==='training'||mapCtf||RULES!==GMODES[0])return null; // the training range, capture the flag and the other modes never touch the rating + if(WATCH||ratedThis||mode==='training'||mapCtf||RULES!==GMODES[0])return null; // a spectator, the training range, capture the flag and the other modes never touch the rating const online_=mode==='online',played=clock-matchJoinClock; const {humans}=rankedField(list); if(online_&&humans<1)return null; // alone in a room: nothing to rate @@ -3284,6 +3341,7 @@

Champion egg!

} function showEndRank(ch){ const box=$('endRank');box.textContent=''; + if(WATCH){box.hidden=true;return} // a spectator has no rating if(!ch){box.hidden=false;const m=document.createElement('span');m.textContent=mapCtf?TX('Capture the flag is unranked: your rating stays as it was.'):RULES!==GMODES[0]?TX('{m} is unranked: your rating stays as it was.',{m:TX(RULES.n)}):mode==='online'?TX('Unranked: no other real players finished this match.'):TX('Unranked: you joined too late in the match to count.');box.appendChild(m);return} box.hidden=false; const big=document.createElement('span');big.className='big';big.textContent=ch.before+' → '+ch.after; @@ -3359,7 +3417,13 @@

Champion egg!

const w=WEAPONS[player.wkey]; // clock and score const rem=Math.max(0,matchEnds-nowMs()),s=Math.ceil(rem/1000);setT('clock',Math.floor(s/60)+':'+String(s%60).padStart(2,'0')); - if(mapCtf)ctfHud();else if(RULES.ladder)ggHud();else{ + if(WATCH&&mapCtf){const t=specTarget();if(t)player.team=t.team} // the followed egg's team shows first + if(mapCtf)ctfHud();else if(WATCH){const t=specTarget(),l=standingsNow()[0]; // spectating: the followed egg and the leader + if(RULES.ladder){const N=RULES.ladder.length,g=t&&t.net?Math.min(clamp(+t.net.gg|0,0,N),N-1):0; // Gun Game: their places on the ladder + setT('myK',t?(g+1)+'/'+N:'–');setT('myL',t?t.name+' · '+WEAPONS[RULES.ladder[g]].name:'Free camera');setT('leadK',l?Math.min(l.g+1,N)+'/'+N:'–')} + else{setT('myK',t&&t.net?String(+t.net.k||0):'–');setT('myL',t?t.name:'Free camera');setT('leadK',l?String(l.k):'–')} + setT('leadN',l?'Leader · '+l.name:'No eggs yet')} + else if(RULES.ladder)ggHud();else{ setT('myK',String(player.kills)); let lead=null,lk=-1;for(const r of standingsNow()){if(r.me)continue;if(r.k>lk){lk=r.k;lead=r}} setT('leadK',lead?String(lead.k):'–');setT('leadN',lead?lead.name:TX('No rivals yet'));} @@ -3380,7 +3444,7 @@

Champion egg!

$('nextW').textContent=TX('{g} (Gun Game, {a} of {b})',{g:WEAPONS[L[g]].name,a:g+1,b:N})} } setT('magN',player.reloadT>0?'…':String(player.ammo[player.wkey])); - const ksShow=(mode==='practice'||mode==='online')&&!RULES.ladder;setHid('ks',!ksShow); // (no streak rewards in Gun Game) + const ksShow=(mode==='practice'||mode==='online')&&!RULES.ladder&&!WATCH;setHid('ks',!ksShow); // (no streak rewards in Gun Game, and a spectator has no streak) if(ksShow)ksHud();else setHid('tKs',true); if(mode==='training'){const S=Range.stats;setT('tsAcc',S.shots?Math.round(100*S.hits/S.shots)+'%':'–');setT('tsHits',S.hits+'/'+S.shots);setT('tsHead',String(S.heads));setT('tsCrack',String(player.kills));setT('tsPop',String(S.pops));setT('tsLast',S.lastT>0?S.last:'')} if(player.reloadT>0&&player.alive){setHid('rel',false);$('rel').firstChild.style.width=(100*(1-player.reloadT/(player.reloadD||w.reload)))+'%'}else setHid('rel',true); @@ -3403,7 +3467,9 @@

Champion egg!

// network line let nl=''; if(online){const others=ents.filter(e=>e.remote&&e.active).length;if(Net.matchId==null&&Net.roundErr)nl=TX('The database wouldn\'t start this room\'s match ({e})',{e:Net.roundErr.code||Net.roundErr.message});else if(!others)nl=TX(Net.isPublic?'Waiting for other eggs to join this lobby…':'Waiting for friends · Esc for the invite link')} + if(WATCH)nl=''; // the spectator's own line (#specMsg) says when the room is empty if(mapCtf&&!nl&&player.carry!=null)nl=TX(ctfS.f[player.team].st===0?'You have the flag: run it home':'You have the flag, but yours must be home to score'); + if(!WATCH&&online&&Net.watchN)nl=(nl?nl+' · ':'')+TX('{n} watching',{n:Net.watchN}); // spectators (../watchers.js), never counted as eggs setT('netline',nl); setHid('lockHint',!!document.pointerLockElement||paused); if(touchUI)$('tAim').classList.toggle('on',!!tAct.aim); @@ -3414,14 +3480,14 @@

Champion egg!

} // scoreboard const showBoard=held('board');setHid('board',!showBoard); - if(showBoard){fillTable($('boardTable'),standings());$('boardTitle').textContent=mode==='training'?TX('{m} · unranked, nothing is saved',{m:mapName()}):mapCtf?TX('{m} · {a} {x} – {y} {b} · first to {n} captures',{m:mapName(),a:TX(TEAM[0].n),x:ctfS.s[0],y:ctfS.s[1],b:TX(TEAM[1].n),n:CTF_CAPS}):mapName()+' · '+(RULES.ladder?goalLine():TX('first to {n}',{n:target}))+' · '+liveRankInfo()} + if(showBoard){fillTable($('boardTable'),standings());$('boardTitle').textContent=WATCH?mapName()+' · '+TX('spectating')+(mapCtf?' · '+TX(TEAM[0].n)+' '+ctfS.s[0]+' – '+ctfS.s[1]+' '+TX(TEAM[1].n):' · '+(RULES.ladder?goalLine():TX('first to {n}',{n:target}))):mode==='training'?TX('{m} · unranked, nothing is saved',{m:mapName()}):mapCtf?TX('{m} · {a} {x} – {y} {b} · first to {n} captures',{m:mapName(),a:TX(TEAM[0].n),x:ctfS.s[0],y:ctfS.s[1],b:TX(TEAM[1].n),n:CTF_CAPS}):mapName()+' · '+(RULES.ladder?goalLine():TX('first to {n}',{n:target}))+' · '+liveRankInfo()} } // ===================================================================== // Input // ===================================================================== function requestLock(){ - if(touchUI)return; + if(touchUI||WATCH)return; try{const r=view.requestPointerLock();if(r&&r.catch)r.catch(()=>{})}catch(e){} } document.addEventListener('pointerlockchange',()=>{ @@ -3581,6 +3647,108 @@

Champion egg!

if(w.auto?held('fire'):clickQueued>0){if(tryFire(p)){clickQueued=0;const fl=vmGun&&vmGun.userData.flash;if(fl){fl.visible=true;fl.userData.t=.045;fl.material.rotation=Math.random()*6;const fs=.36+Math.random()*.14;fl.scale.set(fs,fs,1)}}} } +// ===================================================================== +// Spectating (?watch=1#sc-; WATCH above) +// ===================================================================== +// A spectator has no egg: `player` stays inactive (never drawn, hit, counted or listed), the room is read through +// Net.watchRoom, and the match, map, flags and feed follow the round node exactly as in a player's browser. The camera +// follows one live egg from behind (Q / E or the arrow keys, or Prev / Next, step through them) or flies free (F, Free cam, +// or just drag the view): WASD and Space / Shift on a keyboard, the move stick on a touch screen, drag to look. +const Spec={uid:null,free:false,snap:true,pos:new V3(SPAN/2,24,SPAN/2),yaw:0,pitch:-.5,cam:new V3(),k:{},round:null,err:''}; +const _sd=new V3(),_sw=new V3(),_se=new V3(); +// the eggs worth watching: everyone in this match, in a steady order (by name, then id) so Next always means the same egg +function specList(){return [...remotes.values()].filter(e=>e.active).sort((a,b)=>a.nameb.name?1:a.idx.alive)||l[0]||null;Spec.uid=e?e.id:null;Spec.snap=true} + return e; +} +function specCycle(d){ + const l=specList();if(!l.length)return; + let i=l.findIndex(e=>e.id===Spec.uid);i=i<0?(d>0?0:l.length-1):(i+d+l.length)%l.length; + Spec.free=false;Spec.uid=l[i].id;Spec.snap=true; +} +function specFree(on){ + if(on===Spec.free)return;Spec.free=on; + if(on){camera.getWorldDirection(_sd);Spec.yaw=Math.atan2(-_sd.x,-_sd.z);Spec.pitch=Math.asin(clamp(_sd.y,-1,1));Spec.pos.copy(camera.position)} + else Spec.snap=true; +} +function specCam(dt){ + if(camera.fov!==78){camera.fov=78;camera.updateProjectionMatrix()} + const e=specTarget(); + if(e){ + // over the shoulder: 4.2 m behind and a little above the egg's eyes, pulled in where a block is in the way + eyeOf(e,_se);const pitch=clamp(e.pitch,-1,1);dirOf(e.yaw,pitch*.5,_sd); + _sw.copy(_sd).negate();_sw.y+=.5;_sw.normalize(); + const dist=Math.max(.4,rayWorld(_se,_sw,4.2)-.3);_sw.multiplyScalar(dist).add(_se); + if(Spec.snap){Spec.cam.copy(_sw);Spec.snap=false}else Spec.cam.lerp(_sw,1-Math.exp(-dt*14)); + camera.position.copy(Spec.cam);dirOf(e.yaw,pitch,_sd);camera.lookAt(_se.x+_sd.x*10,_se.y+_sd.y*10,_se.z+_sd.z*10);return; + } + if(!Spec.free){ // nobody to follow yet: a slow turn over the map until someone is + orbit+=dt*.06;const r=SPAN*.6,c=SPAN/2;camera.position.set(c+Math.cos(orbit)*r,30,c+Math.sin(orbit)*r);camera.lookAt(c,2,c);return} + // free camera: a ghost (no collision), kept inside the map + const K=Spec.k,f=(K.KeyW?1:0)-(K.KeyS?1:0)+(tMove.on?-tMove.y:0),r=(K.KeyD?1:0)-(K.KeyA?1:0)+(tMove.on?tMove.x:0),u=(K.Space?1:0)-(K.ShiftLeft||K.ShiftRight?1:0),sp=14*dt; + dirOf(Spec.yaw,Spec.pitch,_sd);Spec.pos.addScaledVector(_sd,f*sp);Spec.pos.x+=Math.cos(Spec.yaw)*r*sp;Spec.pos.z-=Math.sin(Spec.yaw)*r*sp;Spec.pos.y+=u*sp; + Spec.pos.set(clamp(Spec.pos.x,1,SPAN-1),clamp(Spec.pos.y,.6,60),clamp(Spec.pos.z,1,SPAN-1)); + camera.position.copy(Spec.pos);camera.rotation.set(Spec.pitch,Spec.yaw,0); +} +// The spectator's own readouts, every frame (setT only touches the page when a value changes). +function specUi(){ + const room=WATCH_ROOM,t=state==='playing'||state==='end'?specTarget():null,n=specList().length; + setT('specRoom','Spectating · '+(/^(ctf-)?pub-\d$/.test(room)?'public lobby '+room.replace(/^ctf-/,''):'room '+room)+(Net.watchN>1?' · '+Net.watchN+' watching':'')); + setT('specWho',state==='menu'?'':Spec.free?'Free camera':t?'Following '+t.name+(mapCtf?' · '+TEAM[t.team].n:'')+(t.alive?'':' · cracked'):''); + let m=''; + if(Spec.err)m=Spec.err;else if(!Net.ready)m='Connecting…'; + else if(state==='menu')m=Spec.round===false?'Nobody is playing in this room right now. Waiting for a match to start…':'Waiting for the room’s match…'; + else if(!n)m='Nobody is in this match right now. Waiting for players…'; + setT('specMsg',m); + setT('specKeys',touchUI?'':'Q / E or ← → switch player · F free camera · Tab scores · Esc leave'+(Spec.free?' · WASD fly · drag to look · Space / Shift up and down':'')); + $('sPrev').disabled=$('sNext').disabled=n<(Spec.free?1:2); + $('sFree').classList.toggle('on',Spec.free);$('sBoard').classList.toggle('on',!!tAct.board); + document.body.classList.toggle('freecam',Spec.free&&state!=='menu');document.body.classList.toggle('ended',state==='end'); +} +// Leave: inside the Back Room's game layer (an iframe) Back closes it; opened on its own, this goes to the game's menu. +function specLeave(){ + Net.leave(); + try{if(window.parent!==window){history.back();setTimeout(()=>{location.href=location.pathname},800);return}}catch(e){} + location.href=location.pathname; +} +async function startWatch(){ + document.body.classList.add('watching');$('spec').hidden=false;$('menu').hidden=true;$('hud').classList.add('watch'); + state='menu';mode='online';online=false;player.id='watch';player.active=false;player.alive=false; + clearBots();clearRemotes();resetFx();ctfOn=/^ctf-/.test(WATCH_ROOM);buildMap(Math.floor(Math.random()*MAPS.length));matchEnds=Date.now()+1e9; + try{await Net.watchRoom('sc-'+WATCH_ROOM)}catch(err){Spec.err=(err&&err.message)||String(err)} +} +if(WATCH){ + document.addEventListener('keydown',e=>{ + if(e.target&&e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return; // typing in the chat + const c=e.code; + if(c==='Escape'){e.preventDefault();specLeave();return} + if(/^(Key[WASD]|Space|Shift(Left|Right))$/.test(c)){Spec.k[c]=true;if(c==='Space')e.preventDefault();return} + if(e.repeat)return; + if(c==='KeyQ'||c==='ArrowLeft'){e.preventDefault();specCycle(-1)} + else if(c==='KeyE'||c==='ArrowRight'){e.preventDefault();specCycle(1)} + else if(c==='KeyF')specFree(!Spec.free); + }); + document.addEventListener('keyup',e=>{Spec.k[e.code]=false}); + addEventListener('blur',()=>{for(const k in Spec.k)Spec.k[k]=false}); + // Dragging the view looks around: on the canvas with a mouse, on the touch look layer with a finger. Dragging while + // following someone switches to the free camera from where the view is. + const drag=new Map(); + const down=e=>{if(state==='menu')return;drag.set(e.pointerId,[e.clientX,e.clientY,0]);try{e.currentTarget.setPointerCapture(e.pointerId)}catch(_){}}; + const move=e=>{const q=drag.get(e.pointerId);if(!q)return;const dx=e.clientX-q[0],dy=e.clientY-q[1];q[0]=e.clientX;q[1]=e.clientY;q[2]+=Math.abs(dx)+Math.abs(dy); + if(!Spec.free&&q[2]>8)specFree(true); + if(Spec.free){const k=(e.pointerType==='touch'?.0042:.0026)*sens;Spec.yaw-=dx*k;Spec.pitch=clamp(Spec.pitch-dy*k,-1.45,1.45)}}; + const up=e=>drag.delete(e.pointerId); + for(const el of [view,$('tLook')]){el.addEventListener('pointerdown',down);el.addEventListener('pointermove',move);el.addEventListener('pointerup',up);el.addEventListener('pointercancel',up)} + $('sPrev').addEventListener('click',()=>specCycle(-1)); + $('sNext').addEventListener('click',()=>specCycle(1)); + $('sFree').addEventListener('click',()=>specFree(!Spec.free)); + $('sBoard').addEventListener('click',()=>{tAct.board=!tAct.board}); + $('sLeave').addEventListener('click',specLeave); +} + // ===================================================================== // Online (Firebase Realtime Database) // ===================================================================== @@ -3604,7 +3772,7 @@

Champion egg!

// The room's host: the egg that has been in the room longest (jt in its node, the time it joined; an older copy of the // game sends none and is never host). The host picks the next match's rules and settles the map vote. hostUid(){let bu=this.uid,bj=this.joinT;for(const [u,e] of remotes){const q=e.net;if(!q||!e.active)continue;const j=+q.jt;if(!(j>0))continue;if(jc&&c.id===id?Object.assign({},c,{ngm:i}):undefined,undefined,false).catch(()=>{})}, nextGm(){const c=this.cur;return c&&c.id===this.matchId&&c.ngm!=null?gmOf({gm:c.ngm}):this.gm}, @@ -3625,7 +3793,7 @@

Champion egg!

await new Promise(res=>{setTimeout(res,3000);this.db.ref('.info/serverTimeOffset').once('value',s=>{this.offset=s.val()||0;res()})}); this.db.ref('.info/serverTimeOffset').on('value',s=>{this.offset=s.val()||0}); this.ready=true; - syncRank(); + if(!WATCH)syncRank(); // a spectator's rating is never read or written }, stateOf(){ const p=player; @@ -3669,6 +3837,7 @@

Champion egg!

r.players.on('child_removed',s=>{const e=remotes.get(s.key);if(e){infoFeed(TX('{n} left',{n:e.name}));removeEntity(e);remotes.delete(s.key)}}); r.events.on('child_added',s=>{const e=s.val();if(!e||typeof e.t!=='number'||e.t1500)this.seen.delete(this.seen.values().next().value);handleEvent(e)}); r.round.on('value',s=>this.takeRound(s.val())); + this.watchOn(room); clearInterval(this.pubTimer); // About 12 updates a second while something changes (position, aim, health, shots); when nothing has, a // heartbeat a second keeps the node fresh (others drop an egg they haven't heard from for 9 s). @@ -3687,9 +3856,28 @@

Champion egg!

const t0=performance.now(); await new Promise(res=>{const k=setInterval(()=>{if(!this.refs||this.matchId!=null||performance.now()-t0>8000){clearInterval(k);res()}},100)}); }, + // Spectating: the same listeners as joinRoom, read only. No node of our own (refs.me is null), so we're no egg, no count + // and no host for anyone; our own uid isn't skipped, since a spectator has no node there (and a test browser shares one + // uid between its tabs). The round is taken exactly as a player's browser takes it (takeRound, onMatch), never written. + async watchRoom(room){ + await this.init(); + const roomRef=this.db.ref('rooms/'+room); + this.room=room;this.isPublic=/^sc-(ctf-)?pub-\d$/.test(room);this.ctfRoom=/^sc-ctf-/.test(room);this.matchId=null;this.cur=null;this.seen.clear(); + this.refs={room:roomRef,players:roomRef.child('players'),events:roomRef.child('events'),round:roomRef.child('round'),me:null}; + online=true;this.joinT=this.now(); + const r=this.refs,up=s=>onRemoteState(s.key,s.val()); + r.players.on('child_added',up);r.players.on('child_changed',up); + r.players.on('child_removed',s=>{const e=remotes.get(s.key);if(e){infoFeed(e.name+' left');removeEntity(e);remotes.delete(s.key)}}); + r.events.on('child_added',s=>{const e=s.val();if(!e||typeof e.t!=='number'||e.t1500)this.seen.delete(this.seen.values().next().value);handleEvent(e)}); + r.round.on('value',s=>{Spec.round=s.exists();this.takeRound(s.val())}); + this.watchOn(room); + clearInterval(this.pruneTimer); + this.pruneTimer=setInterval(()=>{const t=performance.now();for(const [k,e] of remotes)if(t-e.seen>9000){removeEntity(e);remotes.delete(k)}},2000); + }, // Start the room's match if there is none, or the last one ended more than 20 s ago; otherwise keep it. // nm: how many of the maps every egg in the room can build (the map is picked from the first nm). claimRound(sm,nm){ + if(WATCH)return; this.roundErr=null;this.joining=true;const refs=this.refs;nm=clamp(nm|0||MAPS.length,1,MAPS.length); refs.round.transaction(cur=>{const n=this.now();if(cur&&typeof cur.ends==='number'&&typeof cur.id==='number'&&n{this.roundErr=err}).then(()=>{if(this.refs!==refs)return;this.joining=false;if(this.cur)this.takeRound(this.cur)}); @@ -3702,7 +3890,7 @@

Champion egg!

// The last egg out removes the match (dropRound); one that hadn't seen us yet can do that while we're still here. // Put back the match we're playing (only if nobody has started another), so a later joiner doesn't start a new one. const keep=this.cur; - if(keep&&this.matchId===keep.id&&!this.joining&&this.now()c==null?keep:undefined,undefined,false).catch(()=>{}); + if(!WATCH&&keep&&this.matchId===keep.id&&!this.joining&&this.now()c==null?keep:undefined,undefined,false).catch(()=>{}); return; } if(typeof v!=='object'||typeof v.id!=='number')return; @@ -3747,7 +3935,7 @@

Champion egg!

// A round to switch to: a new match, or the same match on a map other than the one built here. isNewRound(v){return !!v&&typeof v.id==='number'&&(v.id!==this.matchId||mapOf(v)!==mapIdx||smOf(v)!==mapSm)}, send(e){ - if(!online||!this.refs)return; + if(WATCH||!online||!this.refs)return; const ref=this.refs.events.push();this.seen.add(ref.key); const data=JSON.parse(JSON.stringify(e));data.by=this.uid;data.m=this.wm();data.t=firebase.database.ServerValue.TIMESTAMP; ref.set(data).catch(()=>{}); @@ -3755,7 +3943,7 @@

Champion egg!

}, // pickMap: the map vote's result (otherwise the next map in turn). The rules carry over, or become the host's ngm. rematch(pickMap){ - if(!online||!this.refs)return;const id=this.matchId; + if(WATCH||!online||!this.refs)return;const id=this.matchId; // a missing match (the last egg out took it, see dropRound) starts a fresh one too, always numbered past this // browser's own match so its listener (which ignores the match it already has) picks it up // the next match is a small arena if 4 or fewer eggs are here now (and all of them can build one) @@ -3769,10 +3957,19 @@

Champion egg!

// The last egg out takes the room's match with it, so a code nobody uses again doesn't keep a stale node. Only when // no other egg is here, and only the match this browser saw; an egg that was mid-join re-creates one (its own join // transaction, or rematch). - dropRound(r){const id=this.matchId;if(id==null||remotes.size)return;r.round.transaction(cur=>cur==null||cur.id===id?null:undefined).catch(()=>{})}, + dropRound(r){const id=this.matchId;if(WATCH||id==null||remotes.size)return;r.round.transaction(cur=>cur==null||cur.id===id?null:undefined).catch(()=>{})}, + // "N watching" (../watchers.js): spectators list themselves in rooms/sc-_watch, never in the room; everyone in the + // room (players and spectators) counts the ones watching it. + watchN:0,unMe:null,unN:null, + watchOn(room){ + this.watchOff();const W=window.BackRoomWatchers;if(!W||!this.db)return;const code=room.replace(/^sc-/,''),now=()=>this.now(); + if(WATCH)this.unMe=W.join(this.db,this.uid,'sc',code,now); + this.unN=W.count(this.db,'sc',code,now,n=>{this.watchN=n}); + }, + watchOff(){if(this.unMe)this.unMe();if(this.unN)this.unN();this.unMe=this.unN=null;this.watchN=0}, leave(){ - clearInterval(this.pubTimer);clearInterval(this.pruneTimer); - if(this.refs){const r=this.refs;try{r.players.off();r.events.off();r.round.off();r.me.onDisconnect().cancel();r.me.remove();this.dropRound(r)}catch(e){}} + clearInterval(this.pubTimer);clearInterval(this.pruneTimer);this.watchOff(); + if(this.refs){const r=this.refs;try{r.players.off();r.events.off();r.round.off();if(r.me){r.me.onDisconnect().cancel();r.me.remove();this.dropRound(r)}}catch(e){}} this.refs=null;this.room=null;this.ctfRoom=false;this.gm=0;this.matchId=null;this.cur=null;this.joining=false;clearTimeout(this.waitT);online=false;player.id='me'; clearRemotes(); } @@ -3805,7 +4002,7 @@

Champion egg!

if(!v||typeof v.x!=='number'||!isFinite(v.x)||!isFinite(v.z))return; let e=remotes.get(uid); if(!e){ - if(Net.now()-(+v.ts||0)>10000||remotes.size>=MAX_ROOM-1)return; + if(Net.now()-(+v.ts||0)>10000||remotes.size>=(WATCH?MAX_ROOM:MAX_ROOM-1))return; const color=/^#[0-9a-f]{6}$/i.test(v.c)?v.c:'#fbf6ea'; e=makeEntity({id:uid,name:cleanName(v.n),color,remote:true});e.alive=!v.d;e.pos.set(v.x,v.y,v.z);e.lastSc=+v.sc||0; remotes.set(uid,e);ents.push(e);if(state==='playing')infoFeed(TX('{n} joined',{n:e.name})); @@ -3846,7 +4043,7 @@

Champion egg!

const ksHeard=new Map(); function handleEvent(ev){ if(Net.matchId==null||ev.m!==Net.wm()||state==='menu')return; - if(ev.type==='hit'&&ev.to===Net.uid){ + if(ev.type==='hit'&&ev.to===Net.uid&&!WATCH){ // (a spectator has no egg to hit) const att=entById(ev.by)||{id:ev.by,name:'Someone',pos:null}; if(mapCtf&&att.team===player.team)return; // never from a team-mate damage(player,clamp(+ev.dmg||0,0,200),att,!!ev.hd,String(ev.w||'')); @@ -3855,7 +4052,7 @@

Champion egg!

const v=entById(ev.by),k=entById(ev.kb); if(v&&v!==player){if(v.alive||v.model&&v.model.g.visible){v.alive=false;deathFx(v,k)}else if(KIT)KIT.cracked(v,k,null)} // its node said so first: the crack effect still plays const victim=v||{name:'Someone'}; - if(ev.kb===Net.uid)creditKill(player,victim,!!ev.hd,String(ev.w||'')); + if(ev.kb===Net.uid&&!WATCH)creditKill(player,victim,!!ev.hd,String(ev.w||'')); else addFeed(k&&ev.kb!==ev.by?k:null,victim,!!ev.hd,String(ev.w||'')); }else if(ev.type==='nade'){ if([ev.x,ev.y,ev.z,ev.vx,ev.vy,ev.vz].every(n=>typeof n==='number'&&isFinite(n)))spawnNade(ev.x,ev.y,ev.z,clamp(ev.vx,-40,40),clamp(ev.vy,-40,40),clamp(ev.vz,-40,40),ev.by); @@ -3872,7 +4069,7 @@

Champion egg!

const o=entById(ev.by);if(!o||!o.remote||!o.active||!KS_BY[ev.k])return; const key=ev.by+'|'+ev.k,now=performance.now();if(now-(ksHeard.get(key)||-1e9)<2000)return;ksHeard.set(key,now);if(ksHeard.size>200)ksHeard.clear(); const late=clamp((Net.now()-ev.t)/1000,0,30); - if(ev.k==='candle'){if(isFoe(o,player))ksFeed(o,'candle')} + if(ev.k==='candle'){if(WATCH||isFoe(o,player))ksFeed(o,'candle')} else if(ev.k==='launcher')ksFeed(o,'launcher'); else if(ev.k==='fry'){if(!fry&&lateChampion egg! for(const e of remotes.values())e.active=inMyMatch(e.net); player.kills=0;player.deaths=0;player.streak=0;player.gg=0;target=TARGET_ONLINE;$('goal').textContent=goalText(); // capture the flag: the flags and score as the match has them, and (on arriving) a team - if(mapCtf){if(first)ctfPick();ctfSync(ctfNorm(v.ctf),true);ctfGone[0]=ctfGone[1]=0;ctfSeen[0]=ctfSeen[1]=false} - if(mapCtf){if(!(wasIn&&sameMap)){respawn(player);sfx('spawn')}} + if(mapCtf){if(first&&!WATCH)ctfPick();ctfSync(ctfNorm(v.ctf),true);ctfGone[0]=ctfGone[1]=0;ctfSeen[0]=ctfSeen[1]=false} + if(WATCH){Spec.snap=true} // a spectator has no egg to hatch; the camera jumps to whoever it follows on the new map + else if(mapCtf){if(!(wasIn&&sameMap)){respawn(player);sfx('spawn')}} else if(!(wasIn&&sameMap)){ const ids=[Net.uid,...remotes.keys()].sort(); const order=spreadOrder(v.id*7+mi); @@ -3898,8 +4096,9 @@

Champion egg!

if(!(wasIn&&sameMap&&!ratedThis&&clock-matchJoinClock<15))startRatedMatch(); if(state!=='playing'){state='playing';showHud();if(!paused)requestLock()} else{$('end').hidden=true} - if(first&&Net.gm!==menuRules)setTimeout(()=>{if(Net.matchId===v.id)infoFeed(TX('This room is playing {m}',{m:TX(RULES.n)}))},2800); - if(mapCtf){banner(MAPS[mapIdx].name.toUpperCase(),rulesPre()+TX('Capture the flag · {w} · first to {n}',{w:Net.isPublic?TX('public lobby'):TX('room {c}',{c:Net.room}),n:CTF_CAPS}),2.6);ctfHello()} + if(first&&!WATCH&&Net.gm!==menuRules)setTimeout(()=>{if(Net.matchId===v.id)infoFeed(TX('This room is playing {m}',{m:TX(RULES.n)}))},2800); + if(WATCH)banner(MAPS[mapIdx].name.toUpperCase(),rulesPre()+TX('Spectating')+' · '+(mapCtf?TX('capture the flag · first to {n}',{n:CTF_CAPS}):goalLine()),2.6); + else if(mapCtf){banner(MAPS[mapIdx].name.toUpperCase(),rulesPre()+TX('Capture the flag · {w} · first to {n}',{w:Net.isPublic?TX('public lobby'):TX('room {c}',{c:Net.room}),n:CTF_CAPS}),2.6);ctfHello()} else banner(MAPS[mapIdx].name.toUpperCase(),rulesPre()+(Net.isPublic?TX('Public lobby'):TX('Room {c}',{c:Net.room}))+' · '+goalLine(),2.6); // after the banner has gone (on a phone held sideways they'd overlap) if(mapSm&&!sameMap){const id=v.id;setTimeout(()=>{if(Net.matchId===id&&mapSm)infoFeed(TX('Small arena for {n} or fewer',{n:SMALL_MAX}))},2800)} @@ -4031,10 +4230,12 @@

Champion egg!

} } if(state==='end'&&online){ - endTimer-=dt;const host=Net.isHost(); + endTimer-=dt; + if(WATCH)$('endMsg').textContent=endTimer>0?TX('Next match in {n}…',{n:Math.ceil(endTimer)}):TX('Waiting for the players to start the next match…'); // a spectator never votes, hosts or starts one + else{const host=Net.isHost(); $('endMsg').textContent=endTimer>0?TX('Vote for the next map · next match in {n}…',{n:Math.ceil(endTimer)}):TX(host||endTimer<-5?'Starting…':'Waiting for the host…'); $('again').disabled=!host||Vote.sent; - if(!Vote.sent&&(host?endTimer<=0:endTimer<=-5)){Vote.sent=true;Net.rematch(voteDecide())} + if(!Vote.sent&&(host?endTimer<=0:endTimer<=-5)){Vote.sent=true;Net.rematch(voteDecide())}} } updateParts(dt);updateShards(dt);updateSplats(dt);updateTracers(dt);updateSparks(dt);updateBooms(dt); for(const c of clouds)c.rotation.y-=.007*dt; @@ -4044,6 +4245,7 @@

Champion egg!

updateCamera(dt); if(state==='playing'&&player.alive)updateViewmodel(dt); updateHud(dt); + if(WATCH)specUi(); render(); } function updateModel(e,dt){ @@ -4059,10 +4261,11 @@

Champion egg!

if(e.spawnShield>0){const p=.25+.25*Math.sin(clock*14);m.mat.emissive.setRGB(p*.6,p*.8,p)}else if(m.emi)m.mat.emissive.copy(m.emi);else m.mat.emissive.setRGB(0,0,0); if(m.flashT>0){m.flashT-=dt;if(m.flashT<=0&&m.flash)m.flash.visible=false} const lit=player.candleT>0&&!e.dummy&&isFoe(player,e);if(lit||m.glow)setGlow(m,lit); // your Candler - m.tag.visible=e.carry!=null||lit||camera.position.distanceTo(e.pos)<45; + m.tag.visible=e.carry!=null||lit||WATCH||camera.position.distanceTo(e.pos)<45; } function updateCamera(dt){ camPitchKick*=Math.exp(-dt*10);shake*=Math.exp(-dt*6); + if(WATCH&&state!=='menu'){specCam(dt);return} if(state==='menu'||mode==='attract'){ orbit+=dt*.06;const r=SPAN*.72,cx=SPAN/2,cz=SPAN/2; camera.position.set(cx+Math.cos(orbit)*r,32+Math.sin(orbit*.7)*5,cz+Math.sin(orbit)*r); @@ -4127,7 +4330,7 @@

Champion egg!

return m; } function renderVote(){ - const box=$('voteRow'),c=voteCounts();$('vote').hidden=!Vote.opts.length;box.textContent=''; + const box=$('voteRow'),c=voteCounts();$('vote').hidden=WATCH||!Vote.opts.length;box.textContent=''; // (a spectator doesn't vote) for(const o of Vote.opts){const b=document.createElement('button');b.type='button';b.className='btn alt vbtn'+(Vote.mine===o?' on':'');b.setAttribute('aria-pressed',String(Vote.mine===o)); const n=document.createElement('span');n.textContent=o<0?'Random':MAPS[o].name;b.appendChild(n); if(online){const k=document.createElement('small');k.textContent=TX(c.get(o)===1?'{n} vote':'{n} votes',{n:c.get(o)});b.appendChild(k)} @@ -4149,6 +4352,7 @@

Champion egg!

else note=mode==='practice'?TX('Now: {m}.',{m:TX(RULES.n)}):''; for(const [s,n] of [['rulesNextP','pauseRulesNote'],['rulesNextE','endRulesNote']]){$(s).value=String(next);$(s).disabled=!!room&&!host;$(n).textContent=note} const show=mode!=='training';$('pauseRulesBox').hidden=!show;$('pauseRulesNote').hidden=!show; + $('endRulesBox').hidden=$('endRulesNote').hidden=WATCH; // a spectator doesn't pick the rules } // ===================================================================== @@ -4231,7 +4435,7 @@

Champion egg!

addEventListener('pagehide',()=>{leaveCheck();Net.leave()}); // An invite opens this page with #sc-: fill in the room and point at the join button. -const inv=/^#sc-([a-z0-9-]{1,17})$/.exec(location.hash); +const inv=!WATCH&&/^#sc-([a-z0-9-]{1,17})$/.exec(location.hash); if(inv){if(/^ctf-/.test(inv[1]))setMode('ctf');$('room').value=inv[1];setMsg('You were invited to room sc-'+inv[1]+'. Press Play in room to join.');$('joinRoom').classList.remove('alt');$('quick').classList.add('alt')} // ---------- the Locker (kit.js; see SC_PUBLIC near the top) ---------- @@ -4255,10 +4459,10 @@

Champion egg!

if(navigator.webdriver)window.__sc={get KIT(){return KIT},lockerOn,kitLoad,get state(){return state},get mode(){return mode},get noRender(){return noRender},set noRender(v){noRender=!!v},player,get ents(){return ents},get map(){return mapIdx},get arena(){return mapSm},get layout(){return mapIdx+(mapSm?"s":"")},findPath,rayWorld,floorBelow,buildMap,MAPS,W,HY,VY,G,GROUND_Y,vox,vget,standV,nodeFor,entHits,get navN(){return navN},get navReach(){return navReach},navAt,get navY(){return navY},get perches(){return perches},spawns:()=>spawns,Net,onRemoteState,handleEvent,onMatch,endMatch,standings,DIFF,WEAPONS,fireShot,damage,throwNade,nades,addFeed,respawn,spawnSplat,keys,setPaused:v=>{paused=v},get rank(){return rank},HUMAN_W,ratingChange,applyRating,get lastRated(){return lastRated},get clock(){return clock},toMenu,loadLeaderboard,renderer,scene,camera,vmScene,vmCam,advance:s=>{noRender=true;try{for(let t=0;t{clearBots();resetFx();buildMap(i);addBots(n)},get ctf(){return{on:mapCtf,S:ctfS,base:ctfBase,spawns:ctfSpawns,posts:ctfPosts,team:player.team}},ctfDo,ctfReduce,ctfNorm,ctfFresh,ctfSync,setMode,KS,useReward,creditKill,GMODES,get rules(){return RULES},ggSet,ggTop,Vote,castVote,voteDecide,setNextRules:i=>pickRules(i),get rockets(){return rockets},get fry(){return fry},TEAM,startPractice,CTF_CAPS,ctfBotMatch:(i,n)=>{clearBots();resetFx();ctfOn=true;buildMap(i);const t=[];for(let k=0;kmapSpawns,los}; + botMatch:(i,n)=>{clearBots();resetFx();buildMap(i);addBots(n)},get ctf(){return{on:mapCtf,S:ctfS,base:ctfBase,spawns:ctfSpawns,posts:ctfPosts,team:player.team}},ctfDo,ctfReduce,ctfNorm,ctfFresh,ctfSync,setMode,KS,useReward,creditKill,GMODES,get rules(){return RULES},ggSet,ggTop,Vote,castVote,voteDecide,setNextRules:i=>pickRules(i),get rockets(){return rockets},get fry(){return fry},TEAM,startPractice,CTF_CAPS,ctfBotMatch:(i,n)=>{clearBots();resetFx();ctfOn=true;buildMap(i);const t=[];for(let k=0;kmapSpawns,los,get spec(){return Spec},specCycle,specFree,specList,get WATCH(){return WATCH}}; renderSwatches();renderWeapons($('weapons'));renderDiff();renderGfx();renderMode();renderRank();renderRulesUI(); -setupAttract();showAd('adMenu'); +if(WATCH)startWatch();else{setupAttract();showAd('adMenu')} requestAnimationFrame(t=>{last=t;frame(t)}); })(); diff --git a/e63334287a3deaa3/social.js b/e63334287a3deaa3/social.js index 3f7d62cb..3a07d212 100644 --- a/e63334287a3deaa3/social.js +++ b/e63334287a3deaa3/social.js @@ -354,6 +354,8 @@ '.onl-p:hover{border-color:var(--ink-2)}' + '.onl-p.me{cursor:default}.onl-p.me:hover{border-color:var(--line)}' + '.onl-jl{position:relative}.onl-jl .onl-p{padding-right:76px}.onl-jlp .onl-p{padding-right:100px}.onl-jlp .onl-jb{padding:4px 9px}.onl-jb{position:absolute;right:8px;top:50%;transform:translateY(-50%);min-height:34px;padding:4px 12px}' + + // Join and Watch stacked on the right of the row, so the name keeps its room + '.onl-jlw .onl-p{padding-right:84px}.onl-jlw .onl-jb{min-height:30px;min-width:68px;padding:2px 9px;top:calc(50% - 16px)}.onl-jlw .onl-jb.onl-wb{top:calc(50% + 16px)}' + '.onl-av{width:30px;height:30px;border-radius:50%;display:grid;place-items:center;font-weight:700;font-size:14px;color:#fff;flex:none}' + '.onl-who{display:grid;min-width:0;line-height:1.25;flex:1;gap:2px}' + '.onl-nm{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600}' + @@ -1155,6 +1157,8 @@ var fr = frs[i]; if (!fr.isConnected || fr.closest('[hidden]') || fr.closest('.onl-dr')) continue; var path = ''; try { path = fr.contentWindow.location.pathname; } catch (e) {} if (!path || path === 'blank') { try { path = new URL(fr.getAttribute('src') || '', location.href).pathname; } catch (e) { continue; } } + // A game opened to watch (?watch=1, the Watch buttons) isn't one we're playing: no status, no Join for others. + if (/[?&]watch=1(&|#|$)/.test(fr.getAttribute('src') || '')) continue; for (var j = 0; j < GAMES.length; j++) { var g = GAMES[j], dir = g.abs || BASE + g.d + '/'; if (path.indexOf(dir) === 0) return { fr: fr, g: g }; @@ -1567,6 +1571,12 @@ var b = btn(s.label, 'onl-jb' + (s.pri ? ' pri' : ''), 'gjoin'); b.setAttribute('data-u', p.uid); b.disabled = !!s.off; b.setAttribute('aria-label', T('{l}: {n} in {g}', { l: T(s.label), n: mask(p.n), g: s.game })); li.className = 'onl-jl'; li.append(b); + // Games with a spectator mode also get Watch next to Join (playingnow.js opens the game read-only in that room). + if (s.watch) { + var w = btn('Watch', 'onl-jb onl-wb', 'gwatch'); w.setAttribute('data-u', p.uid); + w.setAttribute('aria-label', 'Watch ' + mask(p.n) + ' in ' + s.game + ' without playing'); + li.className = 'onl-jl onl-jlw'; li.append(w); + } } // The Find box's words: every one must appear in the person's name, seat ("seat 23b" works too) or status line. function findQ() { return $find.value.trim().toLowerCase().split(/\s+/).filter(Boolean); } @@ -2063,6 +2073,7 @@ else if (a === 'hide') setHidden(!hidden); else if (a === 'joinable') setJoinable(!joinable); else if (a === 'gjoin') { var gu = b.getAttribute('data-u'), J = window.BackRoomPlaying; if (gu && J && J.act) { if (J.act(gu) && b.closest('.onl-dr')) closeDrawer(); } } + else if (a === 'gwatch') { var wu = b.getAttribute('data-u'), JW = window.BackRoomPlaying; if (wu && JW && JW.watch) { if (JW.watch(wu) && b.closest('.onl-dr')) closeDrawer(); } } else if (a === 'dismiss') { if (host) host.remove(); } else if (a === 'reply') { var u0 = host && host.getAttribute('data-u'); if (host) host.remove(); if (u0) openDrawer({ v: 'dm', u: u0 }); } else if (a === 'joinp') { diff --git a/e63334287a3deaa3/watchers.js b/e63334287a3deaa3/watchers.js new file mode 100644 index 00000000..53a76c1d --- /dev/null +++ b/e63334287a3deaa3/watchers.js @@ -0,0 +1,44 @@ +/* + * watchers.js: the "N watching" count for games with a spectator mode (Shell Crackers, Backrooms 1v1, Boostball). + * + * A spectator (the game opened as /?watch=1#-) must never have a node in the game room itself, + * because every node in rooms/-/players counts as a player there. So spectators are listed in one + * room of their own per game, rooms/-_watch/players/ (the underscore can't be typed into a room code, + * so no game room can ever have that name). The node has the fields the shared rules require (n, c, x, z, h, ts; + * x/z/h always 0) plus r, the room being watched. It is refreshed every 10 s and removed on leaving or disconnecting; + * a node not refreshed for 30 s is ignored. Players (and spectators) of a room listen to that list and count the + * fresh nodes whose r is their room. Nothing else is stored and nothing here touches matches, stats or ratings. + * + * BackRoomWatchers.join(db, uid, prefix, room, now) -> stop() a spectator announces itself + * BackRoomWatchers.count(db, prefix, room, now, cb) -> stop() cb(n) whenever the number watching changes + * db: the game's firebase.database(); uid: the signed-in uid; now: the game's server-time clock (ms). + */ +(function () { + 'use strict'; + var BEAT = 10000, LIVE = 30000; + function list(db, pre) { return db.ref('rooms/' + pre + '-_watch/players'); } + window.BackRoomWatchers = { + join: function (db, uid, pre, room, now) { + if (!db || !uid || !room) return function () {}; + var ref = list(db, pre).child(uid), on = true; + var put = function () { if (on) ref.set({ n: 'Spectator', c: '#8a8a8a', x: 0, z: 0, h: 0, ts: Math.round(now()), r: String(room) }).catch(function () {}); }; + try { ref.onDisconnect().remove(); } catch (e) {} + put(); + var t = setInterval(put, BEAT); + // (the onDisconnect stays set: if the page is closed before the remove reaches the database, it still goes) + return function () { on = false; clearInterval(t); try { ref.remove().catch(function () {}); } catch (e) {} }; + }, + count: function (db, pre, room, now, cb) { + if (!db || !room) return function () {}; + var ref = list(db, pre), val = {}, last = -1; + var calc = function () { + var n = 0, t = now(); + for (var k in val) { var v = val[k]; if (v && v.r === room && t - (+v.ts || 0) < LIVE) n++; } + if (n !== last) { last = n; try { cb(n); } catch (e) {} } + }; + var h = ref.on('value', function (s) { val = s.val() || {}; calc(); }, function () {}); + var t = setInterval(calc, 5000); + return function () { clearInterval(t); try { ref.off('value', h); } catch (e) {} if (last > 0) try { cb(0); } catch (e) {} }; + } + }; +})(); diff --git a/index.html b/index.html index 8757761f..6611282b 100644 --- a/index.html +++ b/index.html @@ -140,8 +140,9 @@

Engineering Projects

// An invite link (home page + #room) is held until the code is entered, and the address is tidied right away. // Backrooms 1v1 rooms start with br-, Shell Crackers rooms with sc-, Trivium contests with tv-, Hail Mary rooms with hm-, Coil rooms with cl-, Slipstream rooms with ss-, Boostball rooms with bb-, Quarry worlds with qy-, Kartwheel rooms with kw-, Showdown tables with sd-, Chromaflage rooms with cf-, Spire rooms with tw-, Updraft rooms with up-, Odd One Out rooms with ph-, Tumble Trials rooms with ko-, Deepword rooms with dw-, Turbo Trail races with sr-, Escapade rooms with er-, Puffer Party rooms with pf-, Driftfall rooms with dz-, Lokop rooms with gd-; every other room code is a Rumble Karts room. // Party invites start with pt-: they don't open a game, they join the party in the Back Room's Party panel (party.js). - var m=/^#([a-z0-9-]{1,20})$/.exec(location.hash); - if(m&&m[1]!=='notrack'&&m[1]!=='track'){room=m[1];history.replaceState(null,'',location.pathname+location.search)} + // A watch link (home page + ?watch=1 + #room) opens the same game read-only, as a spectator (Shell Crackers, Backrooms, Boostball). + var m=/^#([a-z0-9-]{1,20})$/.exec(location.hash),watch=/^\?watch=1$/.test(location.search)&&/^#(sc|br|bb)-/.test(location.hash); + if(m&&m[1]!=='notrack'&&m[1]!=='track'){room=m[1];history.replaceState(null,'',location.pathname+(watch?'':location.search))} // A share link (home page + # + the hidden folder's name) opens the hidden page without the code. The folder name // isn't written here: the page only goes there if a folder with that name exists. If it doesn't, it's kept as a room code. if(/^[0-9a-f]{16}$/.test(room)){ @@ -245,7 +246,7 @@

Engineering Projects

// Your school (school.js) fills in the [data-school] box in the Back Room's header, which was copied in above. var sk=document.createElement('script');sk.src=dir+'school.js';document.body.appendChild(sk); var inv=room&&document.querySelector('a[data-invite="'+(/^tv-/.test(room)?'tv':/^br-/.test(room)?'br':/^sc-/.test(room)?'sc':/^hm-/.test(room)?'hm':/^cl-/.test(room)?'cl':/^ss-/.test(room)?'ss':/^bb-/.test(room)?'bb':/^qy-/.test(room)?'qy':/^kw-/.test(room)?'kw':/^sd-/.test(room)?'sd':/^cf-/.test(room)?'cf':/^tw-/.test(room)?'tw':/^up-/.test(room)?'up':/^ph-/.test(room)?'ph':/^ko-/.test(room)?'ko':/^dw-/.test(room)?'dw':/^sr-/.test(room)?'sr':/^er-/.test(room)?'er':/^pf-/.test(room)?'pf':/^dz-/.test(room)?'dz':/^gd-/.test(room)?'gd':/^bs-/.test(room)?'bs':/^lh-/.test(room)?'lh':/^hp-/.test(room)?'hp':/^vq-/.test(room)?'vq':/^qg-/.test(room)?'qg':'')+'"]'); - if(inv){var u=new URL(inv.href,location.href);openGame(u.pathname+'#'+room,'');room=''} + if(inv){var u=new URL(inv.href,location.href);openGame(u.pathname+(watch?'?watch=1':'')+'#'+room,'');room=''} // The What's new strip (news.js, a