feat: productionize paid modes and PvP capture

This commit is contained in:
jwinterm
2026-07-21 20:41:27 -04:00
parent 8fb284f8ed
commit 89398335c7
230 changed files with 31755 additions and 2777 deletions
+15 -3
View File
@@ -48,7 +48,11 @@ const InputHandler = {
// If the message is "enter", always send it to server
// The server will handle queueing logic and timing
if (msg.toLowerCase() === 'enter') {
socket.emit('chat message', msg);
if (typeof SocketHandlers !== 'undefined' && SocketHandlers.emitFairGameStart) {
if (!SocketHandlers.emitFairGameStart('join_queue')) return false;
} else {
socket.emit('chat message', msg);
}
// Don't automatically switch to waiting screen - let the server control screen state
// The server will send appropriate events (payment_created, waiting_status, etc.)
@@ -157,7 +161,11 @@ const InputHandler = {
window.location.hostname === '127.0.0.1' ||
window.location.protocol === 'file:';
socket.emit('chat message', 'enter');
if (typeof SocketHandlers !== 'undefined' && SocketHandlers.emitFairGameStart) {
if (!SocketHandlers.emitFairGameStart('join_queue')) return;
} else {
socket.emit('chat message', 'enter');
}
if (isDebugMode || ScreenManager.canEnterGame()) {
// Check if we should show waiting screen
@@ -217,7 +225,11 @@ const InputHandler = {
}
// Default: attempt immediate start (payment-required modes go through their own flow)
socket.emit('auto_start');
if (typeof SocketHandlers !== 'undefined' && SocketHandlers.emitFairGameStart) {
if (!SocketHandlers.emitFairGameStart('auto_start')) return;
} else {
socket.emit('auto_start');
}
// Check if we should show waiting screen
const addressRequired = typeof SocketHandlers !== 'undefined' && SocketHandlers.payoutAddressRequired();
+255
View File
@@ -0,0 +1,255 @@
(function (root) {
'use strict';
var policy = null;
var policyPromise = null;
var memoryAcceptance = null;
var STORAGE_KEY = 'wowngeon_paid_ack';
var ACCEPTANCE_KEYS = [
'policyVersion',
'ageEligible',
'termsRead',
'riskAccepted',
'testnetUnderstood'
];
function clearAcceptance() {
memoryAcceptance = null;
try { sessionStorage.removeItem(STORAGE_KEY); } catch (_) {}
}
function loadPolicy(options) {
options = options || {};
if (options.force === true) {
policy = null;
policyPromise = null;
}
if (policy) return Promise.resolve(policy);
if (policyPromise) return policyPromise;
var request = fetch('/api/disclosures', {
credentials: 'same-origin',
cache: 'no-store',
headers: { Accept: 'application/json' }
}).then(function (response) {
if (!response.ok) throw new Error('Disclosure endpoint returned ' + response.status);
return response.json();
}).then(function (value) {
if (!value
|| typeof value.policyVersion !== 'string'
|| value.policyVersion.length < 1
|| value.policyVersion.length > 64
|| !value.service) throw new Error('Disclosure response is incomplete');
// A forced refresh can supersede an older request. Only the latest in-flight request
// may publish its result into the cache.
if (policyPromise === request) policy = value;
return value;
}).catch(function (error) {
if (policyPromise === request) policyPromise = null;
throw error;
});
policyPromise = request;
return request;
}
function canonicalAcceptance(value) {
if (!value || !policy || typeof value !== 'object' || Array.isArray(value)) return null;
var keys = Object.keys(value);
if (keys.length !== ACCEPTANCE_KEYS.length
|| keys.some(function (key) { return ACCEPTANCE_KEYS.indexOf(key) === -1; })) return null;
if (typeof value.policyVersion !== 'string'
|| value.policyVersion.length < 1
|| value.policyVersion.length > 64
|| value.policyVersion !== policy.policyVersion) return null;
if (value.ageEligible !== true || value.termsRead !== true || value.riskAccepted !== true) return null;
if (typeof value.testnetUnderstood !== 'boolean'
|| value.testnetUnderstood !== (policy.service.isTestNetwork === true)) return null;
return {
policyVersion: policy.policyVersion,
ageEligible: true,
termsRead: true,
riskAccepted: true,
testnetUnderstood: policy.service.isTestNetwork === true
};
}
function readAcceptance() {
var value = memoryAcceptance;
try { value = JSON.parse(sessionStorage.getItem(STORAGE_KEY) || 'null') || value; } catch (_) {}
var canonical = canonicalAcceptance(value);
if (!canonical) {
clearAcceptance();
return null;
}
memoryAcceptance = canonical;
return canonical;
}
function acknowledgement() {
var accepted = readAcceptance();
return accepted ? Object.assign({}, accepted) : null;
}
function rememberAcceptance() {
memoryAcceptance = {
policyVersion: policy.policyVersion,
ageEligible: true,
termsRead: true,
riskAccepted: true,
testnetUnderstood: policy.service.isTestNetwork === true
};
try { sessionStorage.setItem(STORAGE_KEY, JSON.stringify(memoryAcceptance)); } catch (_) {}
return acknowledgement();
}
function reject(details) {
details = details || {};
var reportedVersion = typeof details.policyVersion === 'string'
&& details.policyVersion.length > 0
&& details.policyVersion.length <= 64
? details.policyVersion
: null;
var changed = reportedVersion && (!policy || reportedVersion !== policy.policyVersion);
clearAcceptance();
if (changed || details.code === 'PAID_ACK_VERSION') {
return loadPolicy({ force: true });
}
return policy ? Promise.resolve(policy) : loadPolicy();
}
function el(tag, className, text) {
var node = document.createElement(tag);
if (className) node.className = className;
if (text != null) node.textContent = text;
return node;
}
function checkbox(id, labelText) {
var label = el('label', 'commerce-check');
var input = document.createElement('input');
input.type = 'checkbox'; input.id = id;
label.appendChild(input);
label.appendChild(el('span', '', labelText));
return { label: label, input: input };
}
function showModal(resolvedPolicy, onAccept) {
var existing = document.getElementById('commerceConsentOverlay');
if (existing) existing.remove();
var overlay = el('div', 'commerce-consent-overlay');
overlay.id = 'commerceConsentOverlay';
overlay.setAttribute('role', 'presentation');
var dialog = el('section', 'commerce-consent-dialog');
dialog.setAttribute('role', 'dialog');
dialog.setAttribute('aria-modal', 'true');
dialog.setAttribute('aria-labelledby', 'commerceConsentTitle');
var title = el('h2', '', 'Review paid-play disclosures');
title.id = 'commerceConsentTitle';
dialog.appendChild(title);
var service = resolvedPolicy.service;
var summary;
if (service.isTestNetwork) {
summary = service.currencyLabel + ' is valueless test-network currency. Never send mainnet ' + service.cryptoType + '.';
} else if (service.paidPrestigeOnly) {
summary = 'This paid mode purchases entry, credits, or products; this server currently offers no cryptocurrency prize.';
} else if (service.anyPayoutsEnabled) {
summary = 'This server has reward-enabled modes. A paid entry can lose its entire entry value; displayed rewards apply only to qualifying outcomes.';
} else {
summary = 'Blockchain payments may be irreversible. Verify the asset, network, amount, and address before sending.';
}
dialog.appendChild(el('p', 'commerce-summary', summary));
var age = checkbox('commerceAge', 'I confirm I am at least ' + resolvedPolicy.minimumAge + ' and may lawfully use this paid mode where I am located.');
var terms = checkbox('commerceTerms', 'I have read the Terms of Use and Privacy Notice, including the anonymous-session and blockchain risks.');
var risk = checkbox('commerceRisk', service.paidPrestigeOnly
? 'I understand this purchase does not currently pay a cryptocurrency prize and a blockchain transfer may be irreversible.'
: 'I understand paid play can lose the entire entry value, and previous outcomes do not predict future results.');
var required = [age.input, terms.input, risk.input];
dialog.appendChild(age.label);
dialog.appendChild(terms.label);
dialog.appendChild(risk.label);
if (service.isTestNetwork) {
var testnet = checkbox('commerceTestnet', 'I understand test coins have no intended monetary value and I will not send mainnet funds.');
required.push(testnet.input);
dialog.appendChild(testnet.label);
}
var links = el('p', 'commerce-links');
[
['Terms', resolvedPolicy.links.terms],
['Privacy', resolvedPolicy.links.privacy],
['Responsible play', resolvedPolicy.links.responsiblePlay]
].forEach(function (entry, index) {
if (index) links.appendChild(document.createTextNode(' · '));
var link = el('a', '', entry[0]);
link.href = entry[1]; link.target = '_blank'; link.rel = 'noopener';
links.appendChild(link);
});
dialog.appendChild(links);
var status = el('p', 'commerce-status', 'All boxes are required. This statement does not verify identity, age, or location.');
status.setAttribute('aria-live', 'polite');
dialog.appendChild(status);
var actions = el('div', 'commerce-actions');
var cancel = el('button', 'commerce-cancel', 'Cancel'); cancel.type = 'button';
var accept = el('button', 'commerce-accept', 'Acknowledge and continue'); accept.type = 'button'; accept.disabled = true;
actions.appendChild(cancel); actions.appendChild(accept); dialog.appendChild(actions);
overlay.appendChild(dialog); document.body.appendChild(overlay);
function update() { accept.disabled = !required.every(function (input) { return input.checked; }); }
required.forEach(function (input) { input.addEventListener('change', update); });
cancel.addEventListener('click', function () { clearAcceptance(); overlay.remove(); });
accept.addEventListener('click', function () {
if (accept.disabled) return;
var ack = rememberAcceptance();
overlay.remove();
onAccept(ack);
});
age.input.focus();
}
function requireAcknowledgement(onAccept) {
loadPolicy().then(function (resolvedPolicy) {
var current = acknowledgement();
if (current) {
onAccept(current);
return;
}
showModal(resolvedPolicy, onAccept);
}).catch(function () {
clearAcceptance();
var existing = document.getElementById('commerceConsentOverlay');
if (existing) existing.remove();
var overlay = el('div', 'commerce-consent-overlay');
overlay.id = 'commerceConsentOverlay';
var dialog = el('section', 'commerce-consent-dialog');
dialog.setAttribute('role', 'alertdialog');
dialog.appendChild(el('h2', '', 'Paid play is unavailable'));
dialog.appendChild(el('p', 'commerce-summary', 'The current disclosures could not be loaded. No payment or paid entry was requested. Try again after the connection recovers.'));
var close = el('button', 'commerce-cancel', 'Close'); close.type = 'button';
close.addEventListener('click', function () { overlay.remove(); });
dialog.appendChild(close); overlay.appendChild(dialog); document.body.appendChild(overlay);
});
}
function attach(payload) {
var result = Object.assign({}, payload || {});
var ack = acknowledgement();
if (ack) result.legalAcknowledgement = ack;
return result;
}
var api = {
acknowledgement: acknowledgement,
attach: attach,
clear: clearAcceptance,
loadPolicy: loadPolicy,
reject: reject,
require: requireAcknowledgement
};
root.CommerceConsent = api;
if (typeof module !== 'undefined' && module.exports) module.exports = api;
})(typeof window !== 'undefined' ? window : globalThis);
File diff suppressed because one or more lines are too long
+9
View File
@@ -0,0 +1,9 @@
# jQuery 3.7.1 provenance
- Upstream: jQuery 3.7.1, OpenJS Foundation, MIT licence (`jquery.org/license`)
- Local source: Ubuntu package `libjs-jquery` version `3.7.1+dfsg+~3.5.33-1build1`
- Source file: `/usr/share/javascript/jquery/jquery.min.js`
- Vendored file SHA-256: `3289f31657004339ed678f16c4e626987e57303f2107577ed4973f6c9e105260`
- Vendored on: 2026-07-21
The application serves this same-origin copy. No runtime CDN or package-registry request is needed.
File diff suppressed because one or more lines are too long
+333 -85
View File
@@ -1,88 +1,285 @@
(function () {
'use strict';
const socket = io({ transports: ['websocket', 'polling'] });
var socketOpts = { transports: ['websocket', 'polling'] };
try {
var resumeToken = localStorage.getItem('wownerogue_token');
if (resumeToken) socketOpts.auth = { resumeToken: resumeToken };
} catch (_) {}
var socket = io(socketOpts);
var RK = window.RK || {};
const els = {
var els = {
economies: document.getElementById('economies'),
status: document.getElementById('status'),
queueBtn: document.getElementById('queueBtn'),
leaveBtn: document.getElementById('leaveBtn'),
queuePanel: document.getElementById('queuePanel'),
racePanel: document.getElementById('racePanel'),
raceMode: document.getElementById('raceMode'),
raceEconomy: document.getElementById('raceEconomy'),
raceTimer: document.getElementById('raceTimer'),
racePlace: document.getElementById('racePlace'),
stage: document.getElementById('stage')
raceResult: document.getElementById('raceResult'),
stage: document.getElementById('stage'),
renderModes: document.getElementById('renderModes'),
modeTitle: document.getElementById('modeTitle'),
modeDescription: document.getElementById('modeDescription'),
modeBadge: document.getElementById('modeBadge'),
rulesetCatalog: document.getElementById('rulesetCatalog'),
economyHelp: document.getElementById('economyHelp'),
objectiveHint: document.getElementById('objectiveHint'),
dpad: document.getElementById('matchDpad')
};
let gameModeInfo = null;
let selectedEconomy = 'free';
let inQueue = false;
let inRace = false;
let mySocketId = null;
let renderer = null;
let mode = 'tiles';
let keyState = {};
var ECONOMIES = {
free: { label: 'Free / Pleb', description: 'No entry cost · separate free board for competitive modes', available: 'FREE ENTRY' },
credits_prestige: { label: 'Prestige', description: 'Spend credits · PvP Prestige board only', available: 'PAID CREDITS' },
crypto_race: { label: 'Stagenet Stakes', description: 'Race-entry ticket · Champions board and the disclosed pot payout', available: 'STAGENET / CRYPTO' }
};
var MatchCopy = window.MatchUiCopy;
function setStatus(msg) {
els.status.textContent = msg;
var gameModeInfo = null;
var activeRuleset = MatchCopy.normalize({ id: 'race' });
var selectedEconomy = 'free';
var inQueue = false;
var inRace = false;
var mySocketId = socket.id || null;
var renderer = null;
var rendererPending = false;
var rendererToken = 0;
var camera = null;
var mode = (RK.loadMode && RK.loadMode('tiles')) || 'tiles';
var keyState = {};
var lastState = null;
var tickMs = 250;
var countdownTimer = null;
var resultTimer = null;
function setStatus(msg) { els.status.textContent = msg; }
function verifyMatchReveal(fairness) {
if (!fairness || !fairness.seed || !/^[0-9a-f]{64}$/i.test(fairness.seedHash || '')) {
return Promise.resolve(null);
}
if (!window.crypto || !window.crypto.subtle || typeof TextEncoder === 'undefined') {
return Promise.resolve(null);
}
return window.crypto.subtle.digest('SHA-256', new TextEncoder().encode(fairness.seed))
.then(function (digest) {
var actual = Array.from(new Uint8Array(digest))
.map(function (byte) { return byte.toString(16).padStart(2, '0'); }).join('');
return actual === String(fairness.seedHash).toLowerCase();
}).catch(function () { return null; });
}
function matchInfo() {
return gameModeInfo && gameModeInfo.modes && gameModeInfo.modes.match;
}
function economyLabel(id) { return (ECONOMIES[id] && ECONOMIES[id].label) || id || 'Match'; }
function normalizedRuleset(raw) {
return MatchCopy.normalize(raw);
}
function applyRuleset(raw) {
activeRuleset = normalizedRuleset(raw);
els.modeTitle.textContent = activeRuleset.label;
els.modeDescription.textContent = activeRuleset.description;
els.modeBadge.textContent = activeRuleset.badge || 'LIVE MATCH';
els.objectiveHint.textContent = 'Arrow keys / WASD · ' + activeRuleset.objective + ' · drag or pinch the camera';
els.economyHelp.textContent = activeRuleset.cooperative
? 'Co-op is a team result and does not create an individual leaderboard winner.'
: 'Free, Prestige, and Champions results remain on separate boards.';
}
function renderRulesets() {
var info = matchInfo() || {};
applyRuleset(info.activeRuleset || { id: info.rulesetId || 'race' });
els.rulesetCatalog.innerHTML = '';
var catalog = Array.isArray(info.rulesets) && info.rulesets.length ? info.rulesets : [activeRuleset];
catalog.forEach(function (raw) {
var r = normalizedRuleset(raw);
var chip = document.createElement('span');
chip.className = 'tag' + (r.id === activeRuleset.id ? ' active' : '');
chip.textContent = r.label;
chip.title = r.id === activeRuleset.id ? 'Active on this server' : 'Available to the operator';
els.rulesetCatalog.appendChild(chip);
});
}
function renderEconomies() {
if (!gameModeInfo || !gameModeInfo.modes || !gameModeInfo.modes.match || !gameModeInfo.modes.match.enabled) {
var info = matchInfo();
if (!info || !info.enabled) {
els.economies.innerHTML = '';
setStatus('Match mode is not enabled on this server.');
setStatus('Multiplayer mode is not enabled on this server.');
els.queueBtn.disabled = true;
return;
}
const available = gameModeInfo.modes.match.economies || {};
const labels = {
free: 'Free',
credits_prestige: 'Prestige Credits',
crypto_race: 'Crypto Race'
};
var available = info.economies || {};
var availableKeys = Object.keys(ECONOMIES).filter(function (key) { return !!available[key]; });
if (!available[selectedEconomy] && availableKeys.length) selectedEconomy = availableKeys[0];
els.economies.innerHTML = '';
Object.keys(labels).forEach(function (key) {
const locked = !available[key];
const el = document.createElement('div');
el.className = 'economy' + (key === selectedEconomy ? ' active' : '') + (locked ? ' locked' : '');
el.textContent = labels[key];
if (!locked) {
el.addEventListener('click', function () {
selectedEconomy = key;
renderEconomies();
});
}
els.economies.appendChild(el);
Object.keys(ECONOMIES).forEach(function (key) {
var def = ECONOMIES[key];
var locked = !available[key];
var button = document.createElement('button');
button.type = 'button';
button.className = 'economy' + (key === selectedEconomy && !locked ? ' active' : '') + (locked ? ' locked' : '');
button.dataset.economy = key;
button.disabled = locked;
button.setAttribute('aria-pressed', key === selectedEconomy && !locked ? 'true' : 'false');
var title = document.createElement('strong'); title.textContent = def.label;
var desc = document.createElement('small'); desc.textContent = def.description;
var avail = document.createElement('small'); avail.className = 'availability'; avail.textContent = locked ? 'NOT ENABLED' : def.available;
button.appendChild(title); button.appendChild(desc); button.appendChild(avail);
if (!locked) button.addEventListener('click', function () {
selectedEconomy = key;
renderEconomies();
});
els.economies.appendChild(button);
});
els.queueBtn.disabled = availableKeys.length === 0;
}
els.queueBtn.disabled = false;
function renderModeButtons() {
if (!els.renderModes || !RK.RENDER_MODES) return;
els.renderModes.innerHTML = '';
RK.RENDER_MODES.forEach(function (meta) {
var availability = RK.modeAvailability
? RK.modeAvailability(meta.id)
: { usable: !RK.canUseMode || RK.canUseMode(meta.id), runtimeAvailable: true };
var usable = availability.usable;
var b = document.createElement('button');
b.type = 'button'; b.textContent = meta.label
+ (!availability.runtimeAvailable ? ' ⛔' : (meta.premium ? ' ★' : ''));
b.className = (meta.id === mode ? 'active ' : '') + (usable ? '' : 'locked');
b.disabled = !usable;
if (!availability.runtimeAvailable) {
b.title = 'Unavailable on this server: optional renderer dependency disabled.';
} else if (!usable) b.title = 'Unlock a compatible render pack with credits.';
b.addEventListener('click', function () { switchRenderMode(meta.id); });
els.renderModes.appendChild(b);
});
}
function defaultZoomForMode(name) { return name === 'iso' ? 0.82 : (name === '3d' ? 1.15 : 1.45); }
function ensureCamera() {
if (!camera && RK.attachCamera) camera = RK.attachCamera(els.stage, { zoom: defaultZoomForMode(mode), min: 0.5, max: 3.2 });
return camera;
}
function destroyRenderer() {
rendererToken++;
rendererPending = false;
if (renderer && renderer.destroy) { try { renderer.destroy(); } catch (_) {} }
renderer = null;
}
function ensureRenderer() {
if (renderer || rendererPending) return;
rendererPending = true;
var token = ++rendererToken;
var done = function (next) {
if (token !== rendererToken) { if (next && next.destroy) next.destroy(); return; }
rendererPending = false;
renderer = next;
ensureCamera();
if (camera) camera.setZoom(defaultZoomForMode(renderer.name || mode));
renderState(lastState);
};
if (RK.createRendererAsync) RK.createRendererAsync(mode, els.stage, { cell: 26 }, done);
else if (RK.createRenderer) done(RK.createRenderer(mode, els.stage, { cell: 26 }));
}
function switchRenderMode(next) {
if (next === mode || (RK.canUseMode && !RK.canUseMode(next))) return;
mode = next;
if (RK.saveMode) RK.saveMode(mode);
renderModeButtons();
destroyRenderer();
if (inRace && lastState) ensureRenderer();
}
function renderState(state) {
if (!state || !renderer) return;
var scene = RK.sceneFromGameState ? RK.sceneFromGameState(state, {
viewerId: mySocketId,
cryptoType: gameModeInfo && gameModeInfo.cryptoType
}) : null;
if (!scene) return;
renderer.render(scene);
if (camera) camera.update(renderer);
}
function clearCountdown() {
if (countdownTimer) clearInterval(countdownTimer);
countdownTimer = null;
}
function showCountdown(data) {
clearCountdown();
var ruleset = MatchCopy.fromPayload(data, activeRuleset);
applyRuleset(ruleset);
var ends = Date.now() + Math.max(0, Number(data.countdownMs) || 0);
function update() {
var left = Math.max(0, ends - Date.now());
var count = data.players ? data.players.length : 0;
setStatus('Match found · ' + count + ' ' + MatchCopy.plural(ruleset, count) + ' · starts in ' + (left / 1000).toFixed(1) + 's');
if (left <= 0) clearCountdown();
}
update();
countdownTimer = setInterval(update, 100);
}
function startRace(data, initialState) {
clearCountdown();
if (resultTimer) clearTimeout(resultTimer);
inQueue = false;
inRace = true;
applyRuleset(MatchCopy.fromPayload({ ruleset: data && data.ruleset, state: initialState }, activeRuleset));
tickMs = Math.max(50, Number(data && data.tickMs) || tickMs || 250);
els.queuePanel.classList.add('hidden');
els.racePanel.classList.remove('hidden');
els.raceResult.classList.add('hidden');
els.raceResult.textContent = '';
els.raceResult.title = '';
els.raceMode.textContent = activeRuleset.label;
els.raceEconomy.textContent = economyLabel((initialState && initialState.economy) || selectedEconomy);
els.raceTimer.textContent = '0.0s';
els.racePlace.textContent = 'Waiting for first move';
renderModeButtons();
lastState = initialState || null;
ensureRenderer();
if (lastState) renderState(lastState);
}
socket.on('connect', function () {
mySocketId = socket.id;
setStatus('Connected. Waiting for server info…');
socket.emit('register_client', { clientId: socket.id, userAgent: navigator.userAgent });
socket.emit('match_reconnect', {});
setStatus(inRace ? 'Reconnected to the arena.' : 'Connected. Loading server modes…');
});
socket.on('session_token', function (data) {
try { if (data && data.token) localStorage.setItem('wownerogue_token', data.token); } catch (_) {}
});
socket.on('session_resumed', function (data) {
try { if (data && data.token) localStorage.setItem('wownerogue_token', data.token); } catch (_) {}
});
socket.on('game_mode_info', function (info) {
gameModeInfo = info;
gameModeInfo = info || {};
if (RK.setEntitlementSnapshot && info && info.entitlements) RK.setEntitlementSnapshot(info.entitlements);
renderRulesets();
renderEconomies();
if (gameModeInfo?.modes?.match?.enabled) {
setStatus('Ready to queue. Choose an economy and click Join Queue.');
renderModeButtons();
if (matchInfo() && matchInfo().enabled && !inQueue && !inRace) {
setStatus('Ready. Choose an entry mode and join the next ' + activeRuleset.label.toLowerCase() + '.');
}
});
socket.on('match_queue_joined', function (res) {
if (res.success) {
els.queueBtn.disabled = false;
if (res && res.success) {
inQueue = true;
els.queueBtn.classList.add('hidden');
els.leaveBtn.classList.remove('hidden');
setStatus('Queued for ' + selectedEconomy + ' (position ' + (res.position || '?') + '). Waiting for next race…');
setStatus('Queued for ' + economyLabel(selectedEconomy) + ' · position ' + (res.position || '?') + ' · waiting for the next block.');
} else {
setStatus('Queue failed: ' + (res.reason || 'unknown'));
setStatus('Queue failed: ' + ((res && (res.reason || res.message)) || 'unknown error'));
}
});
@@ -90,86 +287,137 @@
inQueue = false;
els.queueBtn.classList.remove('hidden');
els.leaveBtn.classList.add('hidden');
setStatus(res.success ? 'Left queue.' : 'Leave failed: ' + (res.reason || 'unknown'));
setStatus(res && res.success ? 'Left the queue. Any held entry was returned.' : 'Could not leave: ' + ((res && res.reason) || 'unknown error'));
});
socket.on('match_joined', function (data) {
setStatus('Race starting! Seed: ' + data.seedHash.slice(0, 12) + '…');
if (!data) return;
selectedEconomy = data.economy || selectedEconomy;
showCountdown(data);
});
socket.on('match_start', function (data) {
inQueue = false;
inRace = true;
els.queuePanel.classList.add('hidden');
els.racePanel.classList.remove('hidden');
els.raceEconomy.textContent = 'Economy: ' + selectedEconomy;
els.raceTimer.textContent = 'Timer: 0s';
els.racePlace.textContent = 'Place: —';
if (!renderer) {
renderer = RK.createRenderer(mode, els.stage, {});
}
socket.on('match_start', function (data) { startRace(data || {}, null); });
socket.on('match_rejoined', function (data) {
if (!data || !data.state) return;
selectedEconomy = data.state.economy || selectedEconomy;
startRace({ tickMs: tickMs }, data.state);
});
socket.on('match_tick', function (data) {
if (!renderer || !data.state) return;
const scene = RK.sceneFromGameState ? RK.sceneFromGameState(data.state, mySocketId) : null;
if (scene) renderer.render(scene);
const me = data.state.players.find(function (p) { return p.you; });
if (me) {
els.racePlace.textContent = 'Place: ' + (me.placement || '—') + (me.alive ? '' : ' 💀');
}
if (!data || !data.state) return;
if (!inRace) startRace({ tickMs: tickMs }, data.state);
lastState = data.state;
ensureRenderer();
renderState(lastState);
var tick = Number(data.tick != null ? data.tick : lastState.tick) || 0;
els.raceTimer.textContent = (tick * tickMs / 1000).toFixed(1) + 's';
els.racePlace.textContent = MatchCopy.liveSummary(lastState, mySocketId, activeRuleset);
});
socket.on('match_end', function (data) {
data = data || {};
inRace = false;
const me = data.players.find(function (p) { return p.id === mySocketId; });
setStatus('Race over! ' + (data.reason || '') + ' — your placement: ' + (me ? me.placement : '—'));
setTimeout(function () {
if (!inRace) return;
var result = MatchCopy.finalResult(data, mySocketId, activeRuleset);
applyRuleset(result.mode);
els.raceResult.textContent = result.text;
if (data.fairness && data.fairness.seed) {
els.raceResult.title = 'Seed: ' + data.fairness.seed
+ '\nCommitment: ' + data.fairness.seedHash
+ '\nSource: ' + (data.fairness.scope || data.fairness.version || 'commitment');
verifyMatchReveal(data.fairness).then(function (valid) {
if (valid === true) els.raceResult.textContent += ' · seed proof ✓';
else if (valid === false) els.raceResult.textContent += ' · seed proof FAILED';
else els.raceResult.textContent += ' · seed revealed';
});
}
els.raceResult.classList.remove('hidden');
resultTimer = setTimeout(function () {
if (inRace) return;
els.racePanel.classList.add('hidden');
els.queuePanel.classList.remove('hidden');
els.raceResult.classList.add('hidden');
els.queueBtn.classList.remove('hidden');
els.leaveBtn.classList.add('hidden');
lastState = null;
destroyRenderer();
setStatus('Ready for another ' + activeRuleset.label.toLowerCase() + '.');
}, 5000);
});
socket.on('match_error', function (err) {
setStatus('Match error: ' + (err.reason || 'unknown'));
socket.on('match_settlement_pending', function () {
// The server deliberately withholds match_end until its authoritative finish transaction
// commits. Keep this player in the arena mapping while the bounded retry runs.
els.raceResult.textContent = 'Result pending durable settlement · retrying safely…';
els.raceResult.classList.remove('hidden');
setStatus('The arena result is not final yet. No final result has been published.');
});
socket.on('match_error', function (err) {
setStatus('Arena error: ' + ((err && (err.message || err.reason)) || 'unknown error'));
});
socket.on('commerce_ack_required', function (err) {
setStatus((err && (err.message || err.error)) || 'Review the paid-play disclosures before joining.');
if (window.CommerceConsent && window.CommerceConsent.require) {
var refreshed = window.CommerceConsent.reject
? window.CommerceConsent.reject(err)
: Promise.resolve();
refreshed.catch(function () { return null; }).then(function () {
window.CommerceConsent.require(function () {
setStatus('Disclosures acknowledged. Retry the paid queue when ready.');
});
});
}
});
socket.on('disconnect', function () {
setStatus('Disconnected. Reconnecting…');
inQueue = false;
inRace = false;
clearCountdown();
if (window.CommerceConsent && window.CommerceConsent.clear) window.CommerceConsent.clear();
setStatus(inRace ? 'Connection lost · attempting to rejoin your match…' : 'Disconnected · reconnecting…');
});
els.queueBtn.addEventListener('click', function () {
if (inQueue || inRace) return;
socket.emit('match_queue', { economy: selectedEconomy, action: 'join' });
function join(acknowledgement) {
els.queueBtn.disabled = true;
setStatus('Joining ' + economyLabel(selectedEconomy) + '…');
var payload = { economy: selectedEconomy, action: 'join' };
if (acknowledgement) payload.legalAcknowledgement = acknowledgement;
socket.emit('match_queue', payload);
setTimeout(function () { if (!inQueue && !inRace) els.queueBtn.disabled = false; }, 1500);
}
if (selectedEconomy !== 'free' && window.CommerceConsent) {
window.CommerceConsent.require(join);
} else {
join(null);
}
});
els.leaveBtn.addEventListener('click', function () {
if (!inQueue) return;
socket.emit('match_queue', { economy: selectedEconomy, action: 'leave' });
});
function sendMove(dx, dy) {
if (!inRace) return;
if (!inRace || !socket.connected) return;
socket.emit('match_move', { dx: dx, dy: dy });
}
function directionMove(dir) {
if (dir === 'up') sendMove(0, -1);
else if (dir === 'down') sendMove(0, 1);
else if (dir === 'left') sendMove(-1, 0);
else if (dir === 'right') sendMove(1, 0);
}
window.addEventListener('keydown', function (e) {
if (keyState[e.key]) return; // already pressed
if (e.target && /INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return;
if (keyState[e.key]) return;
keyState[e.key] = true;
if (['ArrowUp', 'w', 'W'].includes(e.key)) { e.preventDefault(); sendMove(0, -1); }
else if (['ArrowDown', 's', 'S'].includes(e.key)) { e.preventDefault(); sendMove(0, 1); }
else if (['ArrowLeft', 'a', 'A'].includes(e.key)) { e.preventDefault(); sendMove(-1, 0); }
else if (['ArrowRight', 'd', 'D'].includes(e.key)) { e.preventDefault(); sendMove(1, 0); }
if (['ArrowUp', 'w', 'W'].indexOf(e.key) !== -1) { e.preventDefault(); directionMove('up'); }
else if (['ArrowDown', 's', 'S'].indexOf(e.key) !== -1) { e.preventDefault(); directionMove('down'); }
else if (['ArrowLeft', 'a', 'A'].indexOf(e.key) !== -1) { e.preventDefault(); directionMove('left'); }
else if (['ArrowRight', 'd', 'D'].indexOf(e.key) !== -1) { e.preventDefault(); directionMove('right'); }
});
window.addEventListener('keyup', function (e) {
keyState[e.key] = false;
window.addEventListener('keyup', function (e) { keyState[e.key] = false; });
window.addEventListener('blur', function () { keyState = {}; });
if (els.dpad) Array.prototype.forEach.call(els.dpad.querySelectorAll('[data-dir]'), function (b) {
// Native click covers mouse/touch plus Enter and Space activation for keyboard and AT users.
b.addEventListener('click', function () { directionMove(b.dataset.dir); });
});
}());
+28 -13
View File
@@ -52,11 +52,19 @@ const SmirkAuth = {
}
const socketId = window.socket.id;
let sessionToken = '';
try { sessionToken = localStorage.getItem('wownerogue_token') || ''; } catch (_) {}
if (!sessionToken) {
throw new Error('Your game session is still being established. Please retry in a moment.');
}
// Step 1: Get challenge from server
const challengeRes = await fetch('/api/auth/smirk/challenge', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: {
'Content-Type': 'application/json',
'X-Session-Token': sessionToken
},
body: JSON.stringify({ socketId })
});
@@ -73,7 +81,7 @@ const SmirkAuth = {
if (this._supportsNip98()) {
try {
const result = await this._verifyNip98(socketId, challenge);
const result = await this._verifyNip98(socketId, challenge, sessionToken);
verifyData = result.verifyData;
provenPublicKey = result.pubkey;
} catch (nip98Err) {
@@ -86,12 +94,12 @@ const SmirkAuth = {
|| /reject|cancel|denied|declined/i.test((nip98Err && nip98Err.message) || '');
if (userCancelled) throw nip98Err;
console.warn('Smirk NIP-98 failed, trying legacy connect():', nip98Err && nip98Err.message);
const result = await this._verifyLegacy(socketId, challenge);
const result = await this._verifyLegacy(socketId, challenge, sessionToken);
verifyData = result.verifyData;
provenPublicKey = result.pubkey;
}
} else {
const result = await this._verifyLegacy(socketId, challenge);
const result = await this._verifyLegacy(socketId, challenge, sessionToken);
verifyData = result.verifyData;
provenPublicKey = result.pubkey;
}
@@ -140,7 +148,7 @@ const SmirkAuth = {
*
* @returns {Promise<{verifyData: object, pubkey: string|null}>}
*/
async _verifyNip98(socketId, challenge) {
async _verifyNip98(socketId, challenge, sessionToken) {
// Build the NIP-98 HTTP auth event. The wallet fills in pubkey/id/sig.
const evt = {
kind: 27235,
@@ -173,7 +181,10 @@ const SmirkAuth = {
const verifyRes = await fetch('/api/auth/smirk/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: {
'Content-Type': 'application/json',
'X-Session-Token': sessionToken
},
body: JSON.stringify({ socketId, event: signed })
});
@@ -192,7 +203,7 @@ const SmirkAuth = {
*
* @returns {Promise<{verifyData: object, pubkey: string|null}>}
*/
async _verifyLegacy(socketId, challenge) {
async _verifyLegacy(socketId, challenge, sessionToken) {
// Connect to Smirk extension
let keys;
try {
@@ -226,7 +237,10 @@ const SmirkAuth = {
// Verify signature with backend
const verifyRes = await fetch('/api/auth/smirk/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: {
'Content-Type': 'application/json',
'X-Session-Token': sessionToken
},
body: JSON.stringify({
socketId,
challenge,
@@ -374,7 +388,7 @@ const SmirkAuth = {
*/
init() {
// Check if server has Smirk disabled (e.g., for Monero stagenet)
if (typeof SocketHandlers !== 'undefined' && SocketHandlers._smirkEnabled === false) {
if (typeof SocketHandlers === 'undefined' || SocketHandlers._smirkEnabled !== true) {
console.log('Smirk integration disabled by server');
return;
}
@@ -449,12 +463,12 @@ const SmirkAuth = {
$(document).ready(function() {
// Wait for game_mode_info to arrive first (typically within 2 seconds)
// SocketHandlers will call SmirkAuth.init() when it receives game_mode_info
// This fallback is for cases where game_mode_info doesn't include smirkEnabled
// Fail closed: the server must explicitly advertise smirkEnabled=true.
setTimeout(() => {
// Only auto-init if not already initialized by SocketHandlers
// and if SocketHandlers._smirkEnabled is not explicitly false
// and only when the server explicitly enabled it
if (!SmirkAuth._initialized &&
(typeof SocketHandlers === 'undefined' || SocketHandlers._smirkEnabled !== false)) {
typeof SocketHandlers !== 'undefined' && SocketHandlers._smirkEnabled === true) {
SmirkAuth.init();
}
}, 3000);
@@ -464,7 +478,8 @@ $(document).ready(function() {
if (typeof window.socket !== 'undefined') {
window.socket.on('connect', function() {
setTimeout(() => {
if (SmirkAuth.isAvailable() && !SmirkAuth._isLinked) {
if (typeof SocketHandlers !== 'undefined' && SocketHandlers._smirkEnabled === true &&
SmirkAuth.isAvailable() && !SmirkAuth._isLinked) {
SmirkAuth.checkStatus().then(status => {
const btn = $('#smirkLoginBtn');
if (btn.length > 0 && status.linked) {
+165 -22
View File
@@ -18,6 +18,74 @@ const SocketHandlers = {
_directPayoutsEnabled: false,
_paymentsEnabled: false,
_isSmirkExplicitlyEnabled: function(data) {
return !!data && data.smirkEnabled === true;
},
_fairnessOffer: null,
_pendingFairnessAttempt: null,
_randomClientSeed: function() {
try {
if (!window.crypto || typeof window.crypto.getRandomValues !== 'function') return null;
var bytes = new Uint8Array(32);
window.crypto.getRandomValues(bytes);
return Array.prototype.map.call(bytes, function(b) { return b.toString(16).padStart(2, '0'); }).join('');
} catch (e) { return null; }
},
/** Build a start payload only after receiving the server's commitment. */
fairnessAttempt: function(extra) {
var offer = this._fairnessOffer;
if (!offer || !offer.offerId || !/^[0-9a-f]{64}$/i.test(String(offer.commitment || ''))) {
socket.emit('fairness_offer_request');
$('#messages').append($('<li class="status" style="color:#ffcc00;">').text('Preparing a fairness commitment — try again in a moment.'));
if (typeof UI !== 'undefined' && UI.scrollChat) UI.scrollChat();
return null;
}
// Generate the player's contribution only AFTER selecting the published commitment.
var clientSeed = this._randomClientSeed();
if (!clientSeed) {
$('#messages').append($('<li class="error">').text('Secure randomness is unavailable in this browser; the game was not started.'));
return null;
}
var payload = Object.assign({}, extra || {}, {
fairnessOfferId: offer.offerId,
clientSeed: clientSeed
});
this._pendingFairnessAttempt = {
offerId: offer.offerId,
commitment: offer.commitment,
clientSeed: clientSeed
};
return payload;
},
emitFairGameStart: function(eventName, extra, acknowledgementReady) {
var paidIntent = !(extra && extra.free === true);
var existingAcknowledgement = paidIntent
&& typeof CommerceConsent !== 'undefined'
&& CommerceConsent.acknowledgement
? CommerceConsent.acknowledgement()
: null;
if (paidIntent && !acknowledgementReady && !existingAcknowledgement
&& typeof CommerceConsent !== 'undefined' && CommerceConsent.require) {
CommerceConsent.require(function(acknowledgement) {
var acknowledgedExtra = Object.assign({}, extra || {});
if (acknowledgement) acknowledgedExtra.legalAcknowledgement = acknowledgement;
if (SocketHandlers.emitFairGameStart(eventName, acknowledgedExtra, true)) {
$('#entryChoiceOverlay').remove();
if (typeof ScreenManager !== 'undefined' && ScreenManager.drawWaitingScreen) ScreenManager.drawWaitingScreen();
}
});
return false;
}
var acknowledgedPayload = Object.assign({}, extra || {});
if (existingAcknowledgement) acknowledgedPayload.legalAcknowledgement = existingAcknowledgement;
var payload = this.fairnessAttempt(acknowledgedPayload);
if (!payload) return false;
socket.emit(eventName, payload);
return true;
},
payoutAddressRequired: function() {
if (this._gameMode === 'PAID_SINGLE' && this._directPayoutsEnabled) return true;
@@ -114,6 +182,11 @@ const SocketHandlers = {
registerEventHandlers: function() {
// Connection handlers
socket.on('connect', this.onConnect);
socket.on('disconnect', function() {
if (typeof CommerceConsent !== 'undefined' && CommerceConsent.clear) {
CommerceConsent.clear();
}
});
socket.on('welcome', this.onWelcome);
socket.on('session_token', this.onSessionToken);
socket.on('session_resumed', this.onSessionResumed);
@@ -130,6 +203,9 @@ const SocketHandlers = {
socket.on('game_start', this.onGameStart);
socket.on('game_update', this.onGameUpdate);
socket.on('game_over', this.onGameOver);
socket.on('game_settlement_pending', this.onGameSettlementPending);
socket.on('fairness_offer', this.onFairnessOffer);
socket.on('fairness_error', this.onFairnessError);
// Discrete in-run events. Multi-level DESCEND is the big one — without this, taking the
// stairs down silently dumped the player at a new entrance and read as a bug.
socket.on('game_event', function (data) {
@@ -156,6 +232,7 @@ const SocketHandlers = {
socket.on('address_prompt', this.onAddressPrompt);
socket.on('game_mode_info', this.onGameModeInfo);
socket.on('payment_created', this.onPaymentCreated);
socket.on('commerce_ack_required', this.onCommerceAcknowledgementRequired);
socket.on('payment_confirmed', this.onPaymentConfirmed);
socket.on('payment_detected', this.onPaymentDetected);
socket.on('show_payment_options', this.onShowPaymentOptions);
@@ -208,18 +285,24 @@ const SocketHandlers = {
} catch (e) { /* non-critical */ }
},
onFairnessOffer: function(data) {
if (!data || !data.offerId || !/^[0-9a-f]{64}$/i.test(String(data.commitment || ''))) return;
SocketHandlers._fairnessOffer = data;
},
onFairnessError: function(data) {
SocketHandlers._pendingFairnessAttempt = null;
var message = (data && data.message) || 'Fairness offer could not be consumed. Please retry.';
$('#messages').append($('<li class="error">').text(message));
if (typeof UI !== 'undefined' && UI.scrollChat) UI.scrollChat();
socket.emit('fairness_offer_request');
},
onConnect: function() {
if (SocketHandlers._didConnect) return; // prevent duplicate registration emission
SocketHandlers._didConnect = true;
// Include stored session token in a lightweight resume emit (if server did not get it via handshake)
try {
const existing = localStorage.getItem('wownerogue_token');
if (existing) {
// If we later decide to rely solely on query param at io() creation, this is harmless redundancy.
socket.io.opts.query = socket.io.opts.query || {};
socket.io.opts.query.resumeToken = existing;
}
} catch (e) {}
// The token is supplied in Socket.IO's handshake auth object by index.html. Do not copy
// it into a query string: reverse proxies commonly log URLs, which would leak sessions.
socket.emit('register_client', {
clientId: socket.id,
userAgent: navigator.userAgent
@@ -545,14 +628,28 @@ const SocketHandlers = {
// Display provably fair commitment if present
if (data && data.proof && data.proof.commitment) {
var attempted = SocketHandlers._pendingFairnessAttempt;
var proofMatchesAttempt = !attempted || (
data.proof.offerId === attempted.offerId &&
data.proof.commitment === attempted.commitment &&
data.proof.clientSeed === attempted.clientSeed
);
const shortHash = data.proof.commitment.substring(0, 16) + '...';
const shortClientSeed = data.proof.clientSeed
? data.proof.clientSeed.substring(0, 16) + '...'
: '(legacy empty seed)';
const $proofMsg = $('<li class="proof-commitment" style="color:#0af; font-size:11px;">').html(
'🔐 <strong>Provably Fair:</strong> Game hash commitment: <code style="background:#001a00; padding:2px 4px; border-radius:3px;" title="' +
data.proof.commitment + '">' + shortHash + '</code> ' +
'<button class="copy-hash-btn" style="font-size:10px; padding:1px 4px; cursor:pointer;" data-hash="' +
data.proof.commitment + '">Copy</button>'
data.proof.commitment + '">Copy</button><br>' +
'<span style="color:#888;">Accepted client seed:</span> <code>' + shortClientSeed + '</code>'
);
$('#messages').append($proofMsg);
if (!proofMatchesAttempt) {
$('#messages').append($('<li class="error">').text('⚠️ Fairness proof mismatch: the server did not echo the offer/client seed used for this attempt.'));
}
SocketHandlers._pendingFairnessAttempt = null;
// Store for later verification display
SocketHandlers._currentGameProof = data.proof;
@@ -609,21 +706,40 @@ const SocketHandlers = {
UI.scrollChat();
},
onGameSettlementPending: function() {
// The server withholds game_over until the authoritative completion + any payout
// obligation commit together. Keep the player informed without publishing a result that
// PostgreSQL cannot yet prove or offering another entry while retry is in progress.
$('#messages').find('.solo-settlement-pending').remove();
$('#messages').append($('<li class="status solo-settlement-pending" style="color:#ffcc00;">')
.text('Result pending durable settlement · retrying safely…'));
SocketHandlers._setBannerStatus('Saving result…', '#ffcc00');
UI.scrollChat();
},
onGameOver: function(data) {
$('#messages').find('.solo-settlement-pending').remove();
$('#messages').append($('<li class="game-over">').text("Game Over: " + data.message));
// Display provably fair verification info if present
if (data && data.proof && data.proof.seed) {
const shortSeed = data.proof.seed.substring(0, 16) + '...';
const serverSeed = data.proof.serverSeed || '';
const effectiveSeed = data.proof.effectiveSeed || data.proof.seed;
const clientSeed = data.proof.clientSeed || '';
const shortServerSeed = serverSeed ? serverSeed.substring(0, 16) + '...' : '(unavailable)';
const shortEffectiveSeed = effectiveSeed.substring(0, 16) + '...';
const shortClientSeed = clientSeed ? clientSeed.substring(0, 16) + '...' : '(legacy empty seed)';
const shortCommitment = data.proof.commitment.substring(0, 16) + '...';
const verifyUrl = data.proof.verificationUrl || ('/verify/' + data.proof.gameId);
const $proofReveal = $('<li class="proof-reveal" style="color:#4ade80; font-size:11px; margin-top:5px; padding:8px; background:rgba(0,50,0,0.5); border-radius:4px;">').html(
'🔓 <strong>Game Verified:</strong><br>' +
'<span style="color:#888;">Seed:</span> <code style="background:#001a00; padding:2px 4px; border-radius:3px;" title="' +
data.proof.seed + '">' + shortSeed + '</code> ' +
'🔓 <strong>Proof revealed:</strong><br>' +
'<span style="color:#888;">Server seed:</span> <code style="background:#001a00; padding:2px 4px; border-radius:3px;" title="' +
serverSeed + '">' + shortServerSeed + '</code> ' +
'<button class="copy-seed-btn" style="font-size:10px; padding:1px 4px; cursor:pointer;" data-seed="' +
data.proof.seed + '">Copy</button><br>' +
serverSeed + '">Copy</button><br>' +
'<span style="color:#888;">Client seed:</span> <code>' + shortClientSeed + '</code><br>' +
'<span style="color:#888;">Effective seed:</span> <code title="' + effectiveSeed + '">' + shortEffectiveSeed + '</code><br>' +
'<span style="color:#888;">Hash:</span> <code style="background:#001a00; padding:2px 4px; border-radius:3px;">' + shortCommitment + '</code><br>' +
'<a href="' + verifyUrl + '" target="_blank" style="color:#0af;">🔗 Verify this game</a>'
);
@@ -783,10 +899,17 @@ const SocketHandlers = {
SocketHandlers._creditsPayoutsEnabled = !!data.creditsPayoutsEnabled;
SocketHandlers._directPayoutsEnabled = !!data.directPayoutsEnabled;
SocketHandlers._paymentsEnabled = !!data.paymentsEnabled;
SocketHandlers._smirkEnabled = data.smirkEnabled !== false; // Default to true if not specified
SocketHandlers._smirkEnabled = SocketHandlers._isSmirkExplicitlyEnabled(data);
SocketHandlers._cryptoType = data.cryptoType || 'WOW';
SocketHandlers._currencyLabel = data.currencyLabel || data.cryptoType || 'WOW'; // sXMR on stagenet
SocketHandlers._explorerTxUrl = data.explorerTxUrl || null;
// Do not ask prestige-only users for a payout address or imply that mainnet paid
// entries award crypto. Match crypto is exposed only when its economy is admitted.
var matchCryptoPayouts = !!(data.modes && data.modes.match && data.modes.match.economies
&& data.modes.match.economies.crypto_race);
var anyPayouts = SocketHandlers._creditsPayoutsEnabled
|| SocketHandlers._directPayoutsEnabled || matchCryptoPayouts;
$('#manageAddressButton').toggle(anyPayouts);
if (data.entitlements && typeof SinglePlayerAvatar !== 'undefined') {
SinglePlayerAvatar.applyEntitlements(data.entitlements);
}
@@ -1057,6 +1180,24 @@ const SocketHandlers = {
}
},
onCommerceAcknowledgementRequired: function(data) {
var message = data && (data.message || data.error)
|| 'Review the paid-play disclosures before continuing.';
$('#messages').append($('<li class="status" style="color:#fbbf24;">').text(message));
if (typeof UI !== 'undefined' && UI.scrollChat) UI.scrollChat();
if (typeof CommerceConsent !== 'undefined' && CommerceConsent.require) {
var refreshed = CommerceConsent.reject
? CommerceConsent.reject(data)
: Promise.resolve();
refreshed.catch(function() { return null; }).then(function() {
CommerceConsent.require(function() {
$('#messages').append($('<li class="status" style="color:#aaa;">').text('Disclosures acknowledged. Retry the paid action when ready.'));
if (typeof UI !== 'undefined' && UI.scrollChat) UI.scrollChat();
});
});
}
},
onBalanceCritical: function(data) {
console.warn('Balance critical - games halted:', data);
@@ -1729,7 +1870,9 @@ const SocketHandlers = {
var $btn = $('#earlyEntryButton');
$btn.prop('disabled', true).text('⏳ Entering...');
socket.emit('early_entry');
if (!SocketHandlers.emitFairGameStart('early_entry')) {
$btn.prop('disabled', false).text('⚡ ENTER NOW (RISKY!) ⚡');
}
},
/**
@@ -1806,8 +1949,8 @@ const SocketHandlers = {
'<span style="font-size:12px;letter-spacing:1px;color:' + accent + ';">ENTER &#9656;</span></div>';
}
function begin(msg, emit) {
if (emit() === false) return;
$('#entryChoiceOverlay').remove();
emit();
// Transient "dropping in…/queued…" line — cleared in onGameStart once the game is live so
// it doesn't linger next to a running game reading as "still starting". The queued variant
// stays visible during the (real) block wait; only a started game removes it.
@@ -1842,13 +1985,13 @@ const SocketHandlers = {
$('#ecNow').on('click', function () { timing = 'now'; render(); });
$('#ecX').on('click', function () { $('#entryChoiceOverlay').remove(); });
$('#ecFree').on('click', function () {
if (timing === 'now') begin('⚡ Free game — dropping in...', function () { socket.emit('auto_start', { free: true }); });
else begin('🛡️ Free game — queued for the next block...', function () { socket.emit('join_queue', { free: true }); });
if (timing === 'now') begin('⚡ Free game — dropping in...', function () { return SocketHandlers.emitFairGameStart('auto_start', { free: true }); });
else begin('🛡️ Free game — queued for the next block...', function () { return SocketHandlers.emitFairGameStart('join_queue', { free: true }); });
});
$('#ecRank').on('click', function () {
if (!hasCredits) { pay(); return; }
if (timing === 'now') begin('⚡ Ranked — dropping in now...', function () { socket.emit('auto_start'); });
else begin('🛡️ Ranked — queued for the next block...', function () { socket.emit('join_queue'); });
if (timing === 'now') begin('⚡ Ranked — dropping in now...', function () { return SocketHandlers.emitFairGameStart('auto_start'); });
else begin('🛡️ Ranked — queued for the next block...', function () { return SocketHandlers.emitFairGameStart('join_queue'); });
});
$('#ecBuy').on('click', pay);
}
+5 -1
View File
@@ -114,13 +114,17 @@
// Camera focus — centre the SP camera on the player cell (same convention as the tiled
// renderer). Sticky: only update when the player is present, so switching TO ascii mid-game
// doesn't leave focusPoint null (which pinned the whole grid to the corner → black screen).
var focusFallback = null;
for (var pj = 0; pj < scene.entities.length; pj++) {
var pe = scene.entities[pj];
if (pe.kind === 'player' || pe.you) {
if (pe.kind === 'player' && !focusFallback) focusFallback = pe;
if (pe.you || pe.cameraTarget) {
this.focusPoint = { x: pe.x * cell + cell / 2, y: pe.y * cell + cell / 2 };
focusFallback = null;
break;
}
}
if (focusFallback) this.focusPoint = { x: focusFallback.x * cell + cell / 2, y: focusFallback.y * cell + cell / 2 };
// Keep a light RAF alive so the torch glows flicker between game updates (~22fps).
this._hasTorches = hasTorch;
+4
View File
@@ -624,12 +624,16 @@
function modeLockedTitle(mode) {
var label = mode && mode.label ? mode.label : 'Mode';
if (mode && RK.isModeRuntimeAvailable && !RK.isModeRuntimeAvailable(mode.id)) {
return label + ' is unavailable on this server because its optional renderer dependency is disabled.';
}
if (mode && mode.pack) return label + ' is locked. Buy any credits or unlock ' + packLabel(mode.pack) + '.';
return label + ' is locked. Buy any credits to unlock premium modes.';
}
function modeStatus(mode, unlocked) {
if (!mode || !mode.premium) return 'Included';
if (RK.isModeRuntimeAvailable && !RK.isModeRuntimeAvailable(mode.id)) return 'Unavailable';
if (unlocked && RK.renderModeTestUnlocks && RK.renderModeTestUnlocks()) return 'Test';
return unlocked ? 'Unlocked' : 'Locked';
}
+10 -1
View File
@@ -32,6 +32,7 @@
this.cell = opts.cell || 26;
this.app = new PIXI.Application({ backgroundColor: 0x0a0c0f, antialias: true });
this.app.view.className = 'rk-canvas';
this.canvas = this.app.view;
host.appendChild(this.app.view);
this.tileLayer = new PIXI.Container();
@@ -288,7 +289,7 @@
};
FancyRenderer.prototype._syncEntities = function (scene) {
var cell = this.cell, seen = {}, RKr = window.RK;
var cell = this.cell, seen = {}, RKr = window.RK, focusFallback = null;
for (var i = 0; i < scene.entities.length; i++) {
var e = scene.entities[i];
seen[e.id] = true;
@@ -315,6 +316,14 @@
s = this.sprites[e.id] = { c: c, kind: kind, renderKey: renderKey };
}
s.tx = e.x; s.ty = e.y; s.e = e;
if (e.kind === 'player' && !focusFallback) focusFallback = e;
if (e.you || e.cameraTarget) {
this.focusPoint = { x: e.x * cell + cell / 2, y: e.y * cell + cell / 2 };
focusFallback = null;
}
}
if (!this.focusPoint && focusFallback) {
this.focusPoint = { x: focusFallback.x * cell + cell / 2, y: focusFallback.y * cell + cell / 2 };
}
for (var id in this.sprites) {
if (!seen[id]) {
+3 -2
View File
@@ -326,8 +326,9 @@
var e = scene.entities[i];
p = this._project(e.x, e.y, originX, originY);
items.push({ type: 'entity', e: e, sx: p.x, sy: p.y, depth: e.x + e.y + 0.55 });
// Sticky camera target (keep last if the player is momentarily absent).
if (e.you || e.kind === 'player') { this.focusPoint = { x: p.x, y: p.y + this.tileH }; this._plx = e.x; this._ply = e.y; }
// Sticky camera target (keep last if the player is momentarily absent). Multiplayer
// scenes explicitly mark one racer as cameraTarget; never let a later rival steal it.
if (e.you || e.cameraTarget) { this.focusPoint = { x: p.x, y: p.y + this.tileH }; this._plx = e.x; this._ply = e.y; }
}
items.sort(function (a, b) { return a.depth === b.depth ? (a.y || 0) - (b.y || 0) : a.depth - b.depth; });
+23
View File
@@ -2,6 +2,16 @@
(function (root) {
'use strict';
var RK = root.RK = root.RK || {};
RK.externalRenderersEnabled = function () {
return !!(root.WOWNGEON_RUNTIME && root.WOWNGEON_RUNTIME.rendererCdnEnabled === true);
};
RK.isModeRuntimeAvailable = function (id) {
if (!RK.modeMeta || !RK.modeMeta(id)) return false;
if (id === '3d') {
return !!(RK.THREE && RK.THREE.THREE) || RK.externalRenderersEnabled();
}
return true;
};
// Render tiers. `premium` marks modes intended to be unlocked with credits — a cosmetic
// entitlement gated by Operator Policy, the same pattern as avatar unlocks. NOTE: rendering
@@ -39,6 +49,7 @@
RK.canUseMode = function (id) {
var m = RK.modeMeta(id);
if (!m) return false;
if (!RK.isModeRuntimeAvailable(id)) return false;
if (RK.renderModeTestUnlocks && RK.renderModeTestUnlocks()) return true;
if (!m.premium) return true;
// A premium mode is available once the user has ANY unlocked pack for its projection.
@@ -47,6 +58,16 @@
return !!RK.entitlements.premium;
};
RK.modeAvailability = function (id) {
var runtimeAvailable = RK.isModeRuntimeAvailable(id);
var usable = runtimeAvailable && RK.canUseMode(id);
return {
usable: usable,
runtimeAvailable: runtimeAvailable,
reason: !runtimeAvailable ? 'runtime_unavailable' : (usable ? null : 'entitlement_locked')
};
};
RK.createRenderer = function (mode, host, opts) {
if (!RK.canUseMode(mode)) return new RK.TileRenderer(host, opts);
if (mode === 'ascii' && RK.AsciiRenderer) return new RK.AsciiRenderer(host, opts);
@@ -76,6 +97,7 @@
RK.pixiReady = function () { return typeof PIXI !== 'undefined'; };
RK.ensurePixi = function (cb) {
if (RK.pixiReady()) { cb(true); return; }
if (!RK.externalRenderersEnabled()) { cb(false); return; }
pixiCbs.push(cb);
if (pixiLoading) return;
pixiLoading = true;
@@ -96,6 +118,7 @@
RK.threeReady = function () { return !!(RK.THREE && RK.THREE.THREE); };
RK.ensureThree = function (cb) {
if (RK.threeReady()) { cb(true); return; }
if (!RK.externalRenderersEnabled()) { cb(false); return; }
threeCbs.push(cb);
if (threeLoading) return;
threeLoading = true;
+97 -12
View File
@@ -155,9 +155,67 @@ function maxDims(maps) {
return { rows: rows, cols: cols };
}
function normalizeGameStateOpts(opts) {
// Older multiplayer callers passed a socket id directly. Keep that path working while the
// public API moves to an options object (`{ viewerId, playerAppearance, cryptoType }`).
if (typeof opts === 'string') return { viewerId: opts };
return (opts && typeof opts === 'object') ? opts : {};
}
function pickCameraPlayer(players, state, opts) {
if (!players || !players.length) return null;
var viewerId = opts.viewerId || opts.socketId || null;
var focusId = opts.focusPlayerId || null;
var i, p;
// Match ticks are broadcast once, so the client socket id is the authoritative local marker
// when the server cannot include a recipient-specific `you` flag.
if (viewerId) {
for (i = 0; i < players.length; i++) {
p = players[i];
if (p && p.id === viewerId) return p;
}
}
for (i = 0; i < players.length; i++) {
p = players[i];
if (p && p.you === true) return p;
}
for (i = 0; i < players.length; i++) {
p = players[i];
if (p && focusId && p.id === focusId) return p;
}
for (i = 0; i < players.length; i++) {
p = players[i];
if (p && state.winnerId && p.id === state.winnerId) return p;
}
// Spectators follow a live contender by default, then gracefully fall back to the first racer.
for (i = 0; i < players.length; i++) {
p = players[i];
if (p && p.alive !== false && !p.finished) return p;
}
return players[0] || null;
}
function pointOf(value) {
if (!value) return null;
if (Array.isArray(value)) return { x: value[0], y: value[1] };
if (typeof value.x === 'number' && typeof value.y === 'number') return { x: value.x, y: value.y };
return null;
}
function racerColor(player, index, isYou) {
if (isYou) return '#67e8f9';
if (player && player.alive === false) return '#6b7280';
if (player && (player.finished || player.escaped)) return '#fbbf24';
var palette = ['#9aa4b2', '#a78bfa', '#4ade80', '#fb7185', '#60a5fa', '#f97316'];
var raw = String((player && player.id) || index), hash = 0;
for (var i = 0; i < raw.length; i++) hash = ((hash * 31) + raw.charCodeAt(i)) >>> 0;
return palette[hash % palette.length];
}
function sceneFromGameState(state, opts) {
state = state || {};
opts = opts || {};
opts = normalizeGameStateOpts(opts);
var visible = state.visibleTiles || {};
var explored = state.exploredTiles || {};
var lighting = state.lighting || {};
@@ -167,8 +225,12 @@ function sceneFromGameState(state, opts) {
var rows = state.dungeonRows || visible.length || dims.rows;
var cols = state.dungeonCols || dims.cols;
// Player cell — explored MEMORY fades to black with distance from here (see below).
var _pl = state.player || {};
var matchPlayers = Array.isArray(state.players) ? state.players : [];
var cameraPlayer = pickCameraPlayer(matchPlayers, state, opts);
// Player cell — explored MEMORY fades to black with distance from here (see below). Multiplayer
// states use `players[]`, while the original single-player protocol uses singular `player`.
var _pl = state.player || cameraPlayer || {};
var _plx = typeof _pl.x === 'number' ? _pl.x : (cols / 2);
var _ply = typeof _pl.y === 'number' ? _pl.y : (rows / 2);
@@ -215,15 +277,19 @@ function sceneFromGameState(state, opts) {
function inView(x, y) { return !!(visible[y] && visible[y][x] !== undefined); }
// Entrance / exit / treasure as entities (so they layer above tiles) — only once explored.
if (state.entrance && seen(state.entrance[0], state.entrance[1])) {
entities.push({ id: 'entrance', x: state.entrance[0], y: state.entrance[1], kind: 'feature', char: '<', color: '#3fb950', label: null });
// Solo uses `[x,y]`; match state uses `{x,y}` for treasure, so accept both point shapes.
var entrance = pointOf(state.entrance);
var exit = pointOf(state.exit);
var treasure = pointOf(state.treasure);
if (entrance && seen(entrance.x, entrance.y)) {
entities.push({ id: 'entrance', x: entrance.x, y: entrance.y, kind: 'feature', char: '<', color: '#3fb950', label: null });
}
if (state.exit && seen(state.exit[0], state.exit[1])) {
entities.push({ id: 'exit', x: state.exit[0], y: state.exit[1], kind: 'feature', char: '>', color: '#d29922', label: null });
if (exit && seen(exit.x, exit.y)) {
entities.push({ id: 'exit', x: exit.x, y: exit.y, kind: 'feature', char: '>', color: '#d29922', label: null });
}
if (state.treasure && seen(state.treasure[0], state.treasure[1])) {
if (treasure && seen(treasure.x, treasure.y) && !(state.treasure && state.treasure.carrierId)) {
var tChar = opts.cryptoType === 'XMR' ? '$M' : '$W';
entities.push({ id: 'treasure', x: state.treasure[0], y: state.treasure[1], kind: 'feature', char: tChar, color: '#fbbf24', label: null });
entities.push({ id: 'treasure', x: treasure.x, y: treasure.y, kind: 'feature', char: tChar, color: '#fbbf24', label: null });
}
// Items — only once explored.
@@ -246,15 +312,34 @@ function sceneFromGameState(state, opts) {
});
}
// Player.
if (state.player) {
// Multiplayer racers. Preserve public status fields useful to HUD/render extensions while
// keeping the shared entity contract identical to solo (`kind: player`, appearance, facing).
if (matchPlayers.length) {
var viewerId = opts.viewerId || opts.socketId || null;
for (var pi = 0; pi < matchPlayers.length; pi++) {
var rp = matchPlayers[pi];
if (!rp || typeof rp.x !== 'number' || typeof rp.y !== 'number') continue;
var isYou = viewerId ? rp.id === viewerId : rp.you === true;
var appearance = rp.appearance || (rp.avatar ? { avatar: rp.avatar } : null) || { avatar: 'default' };
entities.push({
id: rp.id || ('player:' + pi), x: rp.x, y: rp.y,
kind: 'player', char: '@', color: racerColor(rp, pi, isYou),
facing: rp.facing || null, label: rp.name || null,
avatar: appearance.avatar || rp.avatar || 'default', appearance: appearance,
you: isYou, cameraTarget: rp === cameraPlayer,
alive: rp.alive !== false, finished: !!rp.finished, escaped: !!rp.escaped,
hasTreasure: !!rp.hasTreasure, placement: rp.placement == null ? null : rp.placement
});
}
// Original single-player protocol.
} else if (state.player) {
var playerEntity = {
id: 'player', x: state.player.x, y: state.player.y,
kind: 'player', char: '@', color: '#9aa4b2',
// No bogus default: the SP server doesn't send facing, so leave it null and let the iso/3D
// renderers INFER facing from movement. A hardcoded 'down' made them always face down/SW.
facing: state.player.facing || null, label: null,
you: !state.isSpectating
you: !state.isSpectating, cameraTarget: true
};
// Attach the player's appearance if available (for render-kit character rendering).
if (opts.playerAppearance) {
+66 -3
View File
@@ -53,6 +53,7 @@
SP.setMode = function (mode) {
if (RK.canUseMode && !RK.canUseMode(mode)) return false;
if (SP._mode !== mode) SP._zoom = null; // let the new projection use its legible default
SP._mode = mode;
if (RK.saveMode) RK.saveMode(mode);
SP._destroyRenderer();
@@ -71,6 +72,42 @@
SP._renderer = null;
};
SP._setZoom = function (next) {
SP._zoom = Math.max(0.4, Math.min(4, Number(next) || SP._defaultZoom()));
var readout = doc() && doc().getElementById('rk-sp-camera-zoom');
if (readout) readout.textContent = Math.round(SP._zoom * 100) + '%';
SP._applyCamera();
};
SP._mountCameraControls = function (host) {
if (!host || host._rkCameraControls || !doc()) return;
var controls = doc().createElement('div');
controls.id = 'rk-sp-camera-controls';
controls.className = 'rk-camera-controls';
controls.setAttribute('aria-label', 'Dungeon camera controls');
controls.style.cssText = 'position:absolute;right:10px;bottom:10px;z-index:20;display:flex;' +
'align-items:center;gap:4px;padding:4px;background:rgba(4,7,10,.82);border:1px solid rgba(255,255,255,.2);' +
'border-radius:7px;box-shadow:0 4px 18px rgba(0,0,0,.45);font:12px monospace;';
function addButton(label, title, action) {
var b = doc().createElement('button');
b.type = 'button'; b.textContent = label; b.title = title; b.setAttribute('aria-label', title);
b.style.cssText = 'min-width:30px;height:28px;padding:0 7px;background:#151b22;color:#e5e7eb;' +
'border:1px solid #3b4552;border-radius:4px;cursor:pointer;font:inherit;';
b.addEventListener('click', function (e) { e.stopPropagation(); action(); });
controls.appendChild(b);
}
addButton('−', 'Zoom out', function () { SP._setZoom(((SP._zoom != null) ? SP._zoom : SP._defaultZoom()) / 1.18); });
var readout = doc().createElement('span');
readout.id = 'rk-sp-camera-zoom';
readout.style.cssText = 'min-width:42px;text-align:center;color:#a7f3d0;';
controls.appendChild(readout);
addButton('+', 'Zoom in', function () { SP._setZoom(((SP._zoom != null) ? SP._zoom : SP._defaultZoom()) * 1.18); });
addButton('⌂', 'Reset camera', function () { SP._zoom = null; SP._camX = null; SP._setZoom(SP._defaultZoom()); });
host.appendChild(controls);
host._rkCameraControls = controls;
readout.textContent = Math.round(((SP._zoom != null) ? SP._zoom : SP._defaultZoom()) * 100) + '%';
};
SP._ensureRenderer = function () {
if (SP._renderer) return SP._renderer;
var host = rkHost();
@@ -116,17 +153,42 @@
// NOT a hardcoded 1.7 — otherwise the first scroll on iso (default 1.0) jumped up to
// 1.7 and BOTH directions read as "zoom in".
var base = (SP._zoom != null) ? SP._zoom : SP._defaultZoom();
SP._zoom = Math.max(0.4, Math.min(4, base * Math.exp(-ev.deltaY * 0.0015)));
SP._applyCamera();
SP._setZoom(base * Math.exp(-ev.deltaY * 0.0015));
}, { passive: false });
host.addEventListener('dblclick', function (ev) {
if (ev.target && ev.target.closest && ev.target.closest('.rk-camera-controls')) return;
SP._zoom = null; SP._camX = null; SP._setZoom(SP._defaultZoom());
});
var points = {}, pinchDistance = null;
host.addEventListener('pointerdown', function (ev) {
if (ev.target && ev.target.closest && ev.target.closest('.rk-camera-controls')) return;
points[ev.pointerId] = { x: ev.clientX, y: ev.clientY };
try { host.setPointerCapture(ev.pointerId); } catch (_) {}
});
host.addEventListener('pointermove', function (ev) {
if (!points[ev.pointerId]) return;
points[ev.pointerId] = { x: ev.clientX, y: ev.clientY };
var ids = Object.keys(points);
if (ids.length < 2) return;
var a = points[ids[0]], b = points[ids[1]];
var distance = Math.hypot(a.x - b.x, a.y - b.y);
if (pinchDistance) SP._setZoom(((SP._zoom != null) ? SP._zoom : SP._defaultZoom()) * (distance / pinchDistance));
pinchDistance = distance;
});
function release(ev) { delete points[ev.pointerId]; pinchDistance = null; }
host.addEventListener('pointerup', release);
host.addEventListener('pointercancel', release);
}
SP._mountCameraControls(host);
return SP._renderer;
};
// Mode-aware default zoom: iso tiles are large (84px) so they want less magnification than the
// small tiled/ascii cells (~24px).
SP._defaultZoom = function () {
return (SP._renderer && SP._renderer.name === 'iso') ? 1.0 : 1.7;
if (SP._renderer && SP._renderer.name === 'iso') return 1.0;
if (SP._renderer && SP._renderer.name === '3d') return 1.05;
return 1.7;
};
// Centre the (whole-scene) canvas on the player via a CSS transform, clipped to the host —
@@ -138,6 +200,7 @@
// The 3D renderer fills the host itself (setSize) and its OWN THREE camera follows the
// player — so DON'T apply a CSS transform (it would double-transform the WebGL view).
if (r.name === '3d') {
if (r.setZoom) r.setZoom((SP._zoom != null) ? SP._zoom : SP._defaultZoom());
r.canvas.style.transform = 'none';
r.canvas.style.left = '0';
r.canvas.style.top = '0';
+34 -9
View File
@@ -59,7 +59,9 @@
targetX: x, targetY: y,
moveCooldown: 0,
sitTimer: 0,
speechTimer: 0,
// Stagger the first lines so entering the room feels conversational instead of every
// patron opening a bubble on the same frame.
speechTimer: opts.speechTimer == null ? 1800 + Math.random() * 7000 : opts.speechTimer,
speech: null, speechUntil: 0,
color: opts.color || '#d7dbe0',
label: opts.label || null,
@@ -334,6 +336,7 @@
// Get the screen position of an entity for a given renderer/cell size.
// This is renderer-agnostic: top-down uses grid coords * cell; iso uses projection.
TavernLife.prototype._entityScreenPos = function (e, scene, cell, mode) {
var pos;
if (mode === 'iso') {
// Match IsoRenderer._project: originX = margin + rows * tileW/2 + tileW; originY = margin + imageH
var tileW = (RK.isoAssets && RK.isoAssets.tile && RK.isoAssets.tile.w) || 84;
@@ -342,18 +345,21 @@
var margin = 28;
var originX = margin + scene.rows * tileW / 2 + tileW;
var originY = margin + imageH;
return {
pos = {
x: originX + (e.x - e.y) * tileW / 2,
y: originY + (e.x + e.y) * tileH / 2
};
}
if (mode === '3d') {
} else if (mode === '3d') {
// 3D renderer uses Three.js — we can't easily get screen coords.
// Skip speech bubbles for 3D mode.
return null;
} else {
// top-down / ascii / fancy: grid coords * cell
pos = { x: e.x * cell + cell / 2, y: e.y * cell + cell / 2 };
}
// top-down / ascii / fancy: grid coords * cell
return { x: e.x * cell + cell / 2, y: e.y * cell + cell / 2 };
var view = this._viewTransform;
if (view) return { x: view.left + pos.x * view.scaleX, y: view.top + pos.y * view.scaleY };
return pos;
};
TavernLife.prototype._drawBubbles = function (scene, cell, mode, now) {
@@ -369,7 +375,7 @@
var remaining = npc.speechUntil - now;
if (remaining < BUBBLE_FADE) alpha = remaining / BUBBLE_FADE;
var pos = this._entityScreenPos(npc, scene, cell, mode);
if (pos) drawBubble(ctx, pos.x, pos.y - cell * 0.3, npc.speech, alpha);
if (pos) drawBubble(ctx, pos.x, pos.y - cell * 0.3 * ((this._viewTransform && this._viewTransform.scaleY) || 1), npc.speech, alpha);
}
// Real player bubbles (from chat).
@@ -386,7 +392,7 @@
var rRemaining = bubble.until - now;
if (rRemaining < BUBBLE_FADE) rAlpha = rRemaining / BUBBLE_FADE;
var rPos = this._entityScreenPos(e, scene, cell, mode);
if (rPos) drawBubble(ctx, rPos.x, rPos.y - cell * 0.3, bubble.text, rAlpha);
if (rPos) drawBubble(ctx, rPos.x, rPos.y - cell * 0.3 * ((this._viewTransform && this._viewTransform.scaleY) || 1), bubble.text, rAlpha);
}
};
@@ -419,7 +425,26 @@
// Draw speech bubbles on the overlay.
var rendererCanvas = this.host.querySelector('.rk-canvas');
if (rendererCanvas) {
this._syncOverlaySize(rendererCanvas.width, rendererCanvas.height);
this._syncOverlaySize(this.host.clientWidth || rendererCanvas.width, this.host.clientHeight || rendererCanvas.height);
// Keep the overlay at viewport scale (so chat remains readable), but project each
// world-space head position through the camera-transformed canvas rectangle.
var hostRect = this.host.getBoundingClientRect ? this.host.getBoundingClientRect() : { left: 0, top: 0 };
var canvasRect = rendererCanvas.getBoundingClientRect ? rendererCanvas.getBoundingClientRect() : {
left: 0, top: 0, width: rendererCanvas.width, height: rendererCanvas.height
};
this._viewTransform = {
left: canvasRect.left - hostRect.left,
top: canvasRect.top - hostRect.top,
scaleX: canvasRect.width / (rendererCanvas.width || 1),
scaleY: canvasRect.height / (rendererCanvas.height || 1)
};
this._overlay.style.inset = '0';
this._overlay.style.left = '0';
this._overlay.style.top = '0';
this._overlay.style.maxWidth = 'none';
this._overlay.style.maxHeight = 'none';
this._overlay.style.transform = '';
this._overlay.style.transition = '';
}
this._drawBubbles(scene, cell, mode, now);
};
+46 -4
View File
@@ -22,6 +22,9 @@
this.mixers = [];
this.entities = {};
this.last = {};
this.zoom = 1;
this.panX = 0;
this.panY = 0;
this._sizeKey = null;
this._init();
}
@@ -40,7 +43,13 @@
this.camera.lookAt(0, 0, 0);
this.renderer = new T.WebGLRenderer({ antialias: true, alpha: false, preserveDrawingBuffer: true });
this.renderer.domElement.className = 'rk-canvas';
this.canvas = this.renderer.domElement;
this.renderer.setPixelRatio(Math.min(2, root.devicePixelRatio || 1));
if (T.SRGBColorSpace) this.renderer.outputColorSpace = T.SRGBColorSpace;
if (T.ACESFilmicToneMapping != null) {
this.renderer.toneMapping = T.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.08;
}
this.host.appendChild(this.renderer.domElement);
var hemi = new T.HemisphereLight(0xfff3d2, 0x283044, 2.1);
@@ -48,6 +57,11 @@
var key = new T.DirectionalLight(0xffffff, 1.6);
key.position.set(6, 10, 5);
this.scene.add(key);
// A subtle player-carried torch adds depth and keeps the followed avatar readable without
// washing out the dungeon's black fog-of-war background.
this.playerLight = new T.PointLight(0xffb35c, 2.2, 8, 2);
this.playerLight.position.set(0, 3.2, 0);
this.scene.add(this.playerLight);
this.world = new T.Group();
this.scene.add(this.world);
this.clock = new T.Clock();
@@ -65,7 +79,7 @@
if (w === this._cw && h === this._ch) return;
this._cw = w; this._ch = h;
this.renderer.setSize(w, h, true); // updateStyle:true → the canvas CSS-fills the host
var aspect = w / h, span = 8; // fixed zoom = a screenful around the player
var aspect = w / h, span = 8 / (this.zoom || 1); // fixed screenful, user-adjustable zoom
this.camera.left = -span * aspect;
this.camera.right = span * aspect;
this.camera.top = span;
@@ -73,6 +87,24 @@
this.camera.updateProjectionMatrix();
};
ThreeRenderer.prototype.setZoom = function (zoom) {
var next = Math.max(0.55, Math.min(3.2, Number(zoom) || 1));
if (Math.abs(next - this.zoom) < 0.001) return;
this.zoom = next;
this._cw = null; // force projection update even when the host dimensions did not change
this._fitToHost();
};
// `attachCamera` reports drag pan in viewport pixels. Keep that contract for 3D and convert the
// offset to ground-plane world units in _animate(), where the followed player's current smoothed
// position is available. Bound it to one viewport so a stray gesture cannot lose the dungeon.
ThreeRenderer.prototype.setPan = function (x, y) {
var w = (this.host && (this.host.clientWidth || this.host.offsetWidth)) || 640;
var h = (this.host && (this.host.clientHeight || this.host.offsetHeight)) || 400;
this.panX = Math.max(-w, Math.min(w, Number(x) || 0));
this.panY = Math.max(-h, Math.min(h, Number(y) || 0));
};
ThreeRenderer.prototype._mat = function (hex) {
var T = this.THREE;
return new T.MeshStandardMaterial({ color: colorNum(hex), roughness: 0.82, metalness: 0.02 });
@@ -297,11 +329,21 @@
var pcam = null;
for (var pid in this.entities) {
var pen = this.entities[pid];
if (pen.e && (pen.e.you || pen.e.kind === 'player')) { pcam = pen.obj; break; }
if (pen.e && (pen.e.you || pen.e.cameraTarget)) { pcam = pen.obj; break; }
if (!pcam && pen.e && pen.e.kind === 'player') pcam = pen.obj;
}
if (pcam) {
this.camera.position.set(pcam.position.x + 8, 9, pcam.position.z + 8);
this.camera.lookAt(pcam.position.x, 0, pcam.position.z);
// Dragging the viewport should move the rendered dungeon with the pointer. Translate the
// camera target opposite the corresponding screen-space axes while retaining the fixed
// isometric camera offset and player-follow smoothing.
var viewportHeight = (this.host && (this.host.clientHeight || this.host.offsetHeight)) || 400;
var unitsPerPixel = (16 / (this.zoom || 1)) / Math.max(1, viewportHeight);
var diagonal = unitsPerPixel / Math.sqrt(2);
var targetX = pcam.position.x + (-this.panX - this.panY) * diagonal;
var targetZ = pcam.position.z + (this.panX - this.panY) * diagonal;
this.camera.position.set(targetX + 8, 9, targetZ + 8);
this.camera.lookAt(targetX, 0, targetZ);
if (this.playerLight) this.playerLight.position.set(pcam.position.x, 3.2, pcam.position.z);
}
this.renderer.render(this.scene, this.camera);
} catch (err) {
+6 -2
View File
@@ -41,11 +41,15 @@
// The player/you entity that carries the torch (for the light composite + embers).
function findPlayer(scene) {
if (!scene || !scene.entities) return null;
var live = null, fallback = null;
for (var i = 0; i < scene.entities.length; i++) {
var e = scene.entities[i];
if (e.kind === 'player' || e.you) return e;
if (!(e.kind === 'player' || e.you)) continue;
if (e.you || e.cameraTarget) return e;
if (!live && e.alive !== false && !e.finished) live = e;
if (!fallback) fallback = e;
}
return null;
return live || fallback;
}
// Real-tile coord for a dungeon feature entity, keyed off its glyph.
+235
View File
@@ -37,4 +37,239 @@
RK.applyZoom(host);
});
};
function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
function rendererCanvas(renderer) {
return renderer && (renderer.canvas || (renderer.app && renderer.app.view) ||
(renderer.renderer && renderer.renderer.domElement));
}
// Player-follow camera for fixed viewports (single/multiplayer races and spectator views).
// Renderers only need to expose `canvas` + `focusPoint`; ThreeRenderer instead handles zoom and
// following internally through setZoom(). The older attachZoom API above remains unchanged for
// whole-room previews that intentionally do not follow an avatar.
RK.attachCamera = function (host, opts) {
if (!host) return null;
if (host._rkCamera) return host._rkCamera.api;
opts = opts || {};
var state = host._rkCamera = {
zoom: clamp(Number(opts.zoom) || 1.35, Number(opts.min) || 0.55, Number(opts.max) || 3.2),
defaultZoom: Number(opts.zoom) || 1.35,
fitRatio: Number(opts.fitRatio) || 0,
autoFit: false,
min: Number(opts.min) || 0.55,
max: Number(opts.max) || 3.2,
panX: 0,
panY: 0,
renderer: null,
pointers: {},
pinchDistance: null,
listeners: [],
destroyed: false
};
host.style.position = host.style.position || 'relative';
host.style.overflow = 'hidden';
host.style.touchAction = 'none';
host.style.cursor = 'grab';
function updateReadout() {
if (state.readout) state.readout.textContent = Math.round(state.zoom * 100) + '%';
}
function listen(target, type, handler, options) {
target.addEventListener(type, handler, options);
state.listeners.push({ target: target, type: type, handler: handler, options: options });
}
function fitZoom(renderer, ratio) {
if (!renderer || renderer.name === '3d') return clamp(state.defaultZoom, state.min, state.max);
var canvas = rendererCanvas(renderer);
if (!canvas) return clamp(state.defaultZoom, state.min, state.max);
var cw = canvas.width || canvas.offsetWidth || 1;
var ch = canvas.height || canvas.offsetHeight || 1;
var w = host.clientWidth || host.offsetWidth || 640;
var h = host.clientHeight || host.offsetHeight || 400;
return clamp(Math.min(w / cw, h / ch) * (Number(ratio) || state.fitRatio || 0.72), state.min, state.max);
}
function setZoom(next, manual) {
if (state.destroyed) return;
if (manual) state.autoFit = false;
state.zoom = clamp(Number(next) || 1, state.min, state.max);
updateReadout();
RK.updateCamera(host, state.renderer);
}
function reset() {
if (state.destroyed) return;
state.panX = 0;
state.panY = 0;
state.autoFit = !!(state.fitRatio && state.renderer);
setZoom(state.autoFit ? fitZoom(state.renderer) : state.defaultZoom);
}
function onWheel(e) {
if (state.destroyed) return;
e.preventDefault();
setZoom(state.zoom * Math.exp(-e.deltaY * 0.0015), true);
}
function onDoubleClick(e) {
if (state.destroyed) return;
if (e.target && e.target.closest && e.target.closest('.rk-camera-controls')) return;
reset();
}
function onPointerDown(e) {
if (state.destroyed) return;
if (e.target && e.target.closest && e.target.closest('.rk-camera-controls')) return;
state.pointers[e.pointerId] = { x: e.clientX, y: e.clientY };
state.dragId = e.pointerId;
host.style.cursor = 'grabbing';
try { host.setPointerCapture(e.pointerId); } catch (_) {}
}
function onPointerMove(e) {
if (state.destroyed) return;
var prev = state.pointers[e.pointerId];
if (!prev) return;
state.pointers[e.pointerId] = { x: e.clientX, y: e.clientY };
var ids = Object.keys(state.pointers);
if (ids.length > 1) {
var a = state.pointers[ids[0]], b = state.pointers[ids[1]];
var dist = Math.hypot(a.x - b.x, a.y - b.y);
if (state.pinchDistance) setZoom(state.zoom * (dist / state.pinchDistance));
state.pinchDistance = dist;
} else {
state.autoFit = false;
state.panX += e.clientX - prev.x;
state.panY += e.clientY - prev.y;
RK.updateCamera(host, state.renderer);
}
}
function releasePointer(e) {
if (state.destroyed) return;
delete state.pointers[e.pointerId];
state.pinchDistance = null;
if (!Object.keys(state.pointers).length) host.style.cursor = 'grab';
}
listen(host, 'wheel', onWheel, { passive: false });
listen(host, 'dblclick', onDoubleClick);
listen(host, 'pointerdown', onPointerDown);
listen(host, 'pointermove', onPointerMove);
listen(host, 'pointerup', releasePointer);
listen(host, 'pointercancel', releasePointer);
if (opts.controls !== false && root.document) {
var controls = root.document.createElement('div');
controls.className = 'rk-camera-controls';
controls.setAttribute('aria-label', 'Camera controls');
controls.style.cssText = 'position:absolute;right:10px;bottom:10px;z-index:20;display:flex;' +
'align-items:center;gap:4px;padding:4px;background:rgba(4,7,10,.82);border:1px solid rgba(255,255,255,.2);' +
'border-radius:7px;box-shadow:0 4px 18px rgba(0,0,0,.45);font:12px ui-monospace,monospace;';
function button(label, title, fn) {
var b = root.document.createElement('button');
b.type = 'button'; b.textContent = label; b.title = title; b.setAttribute('aria-label', title);
b.style.cssText = 'min-width:30px;height:28px;padding:0 7px;background:#151b22;color:#e5e7eb;' +
'border:1px solid #3b4552;border-radius:4px;cursor:pointer;font:inherit;';
listen(b, 'click', function (e) { e.stopPropagation(); fn(); });
controls.appendChild(b);
}
button('−', 'Zoom out', function () { setZoom(state.zoom / 1.18, true); });
state.readout = root.document.createElement('span');
state.readout.style.cssText = 'min-width:42px;text-align:center;color:#a7f3d0;';
controls.appendChild(state.readout);
button('+', 'Zoom in', function () { setZoom(state.zoom * 1.18, true); });
button('⌂', 'Reset camera', reset);
host.appendChild(controls);
state.controls = controls;
}
updateReadout();
if (typeof root.ResizeObserver === 'function') {
state.observer = new root.ResizeObserver(function () {
if (state.destroyed) return;
if (state.autoFit) setZoom(fitZoom(state.renderer));
else RK.updateCamera(host, state.renderer);
});
state.observer.observe(host);
}
state.api = {
update: function (renderer) {
if (!state.destroyed) RK.updateCamera(host, renderer);
},
setZoom: setZoom,
setDefaultZoom: function (zoom) {
if (!state.destroyed) state.defaultZoom = Number(zoom) || state.defaultZoom;
},
fit: function (renderer, ratio) {
if (state.destroyed) return;
state.renderer = renderer || state.renderer;
if (ratio != null) state.fitRatio = Number(ratio) || state.fitRatio;
state.panX = 0;
state.panY = 0;
state.autoFit = !!state.renderer;
setZoom(fitZoom(state.renderer));
},
reset: reset,
getZoom: function () { return state.zoom; },
destroy: function () {
if (state.destroyed) return;
state.destroyed = true;
state.listeners.splice(0).forEach(function (entry) {
if (entry.target && typeof entry.target.removeEventListener === 'function') {
entry.target.removeEventListener(entry.type, entry.handler, entry.options);
}
});
Object.keys(state.pointers).forEach(function (pointerId) {
try {
if (typeof host.releasePointerCapture === 'function') {
host.releasePointerCapture(Number(pointerId));
}
} catch (_) {}
});
state.pointers = {};
state.pinchDistance = null;
host.style.cursor = 'grab';
if (state.observer) {
state.observer.disconnect();
state.observer = null;
}
if (state.controls && state.controls.parentNode) state.controls.parentNode.removeChild(state.controls);
state.controls = null;
state.readout = null;
state.renderer = null;
if (host._rkCamera === state) delete host._rkCamera;
}
};
return state.api;
};
RK.updateCamera = function (host, renderer) {
var state = host && host._rkCamera;
if (!state || !renderer) return;
state.renderer = renderer;
if (renderer.name === '3d') {
if (typeof renderer.setZoom === 'function') renderer.setZoom(state.zoom);
if (typeof renderer.setPan === 'function') renderer.setPan(state.panX, state.panY);
return;
}
var canvas = rendererCanvas(renderer);
if (!canvas) return;
var cw = canvas.width || canvas.offsetWidth || 1;
var ch = canvas.height || canvas.offsetHeight || 1;
var w = host.clientWidth || host.offsetWidth || 640;
var h = host.clientHeight || host.offsetHeight || 400;
var focus = renderer.focusPoint || { x: cw / 2, y: ch / 2 };
var z = state.zoom;
var tx = w / 2 - focus.x * z + state.panX;
var ty = h / 2 - focus.y * z + state.panY;
var sw = cw * z, sh = ch * z;
tx = sw <= w ? (w - sw) / 2 : clamp(tx, w - sw, 0);
ty = sh <= h ? (h - sh) / 2 : clamp(ty, h - sh, 0);
canvas.style.position = 'absolute';
canvas.style.left = '0';
canvas.style.top = '0';
canvas.style.maxWidth = 'none';
canvas.style.maxHeight = 'none';
canvas.style.transformOrigin = '0 0';
canvas.style.imageRendering = 'pixelated';
canvas.style.transition = 'transform 110ms ease-out';
canvas.style.transform = 'translate(' + tx + 'px,' + ty + 'px) scale(' + z + ')';
};
})(window);
+13 -6
View File
@@ -33,6 +33,16 @@ const HelpModal = {
updateConfig: function(config) {
this._config = config;
const payoutsOn = !!(config && (config.directPayoutsEnabled || config.creditsPayoutsEnabled));
if (payoutsOn) {
$('#helpPayoutTitle').text('🎁 Payouts');
$('#helpPayoutCopy').text('Set your payout address with “Manage Payout Address.” An escape pays the configured reward automatically, and escaping with the treasure earns the higher multiplier.');
$('#helpTreasureLegend').text('Treasure - collect for the higher payout and score bonus');
} else {
$('#helpPayoutTitle').text('🏅 Prestige rewards');
$('#helpPayoutCopy').text('This server does not pay crypto winnings. Paid entries and credits qualify scores for the Hall of Champions; free runs stay on the separate Pleb leaderboard.');
$('#helpTreasureLegend').text('Treasure - collect for a score bonus');
}
},
show: function() {
@@ -73,7 +83,7 @@ const HelpModal = {
// discount; 1 credit = 1 run either way.
const price = config.singleGamePriceFormatted || '1';
const packages = config.creditPackages || [];
const payoutsOn = !!(config.payoutsEnabled || config.directPayoutsEnabled || config.creditsPayoutsEnabled);
const payoutsOn = !!(config.directPayoutsEnabled || config.creditsPayoutsEnabled);
const buy = [];
if (directOn) buy.push(`<strong>1 credit</strong> — ${price} ${currency}`);
@@ -82,16 +92,13 @@ const HelpModal = {
const bonus = pkg.bonus > 0 ? ` +${pkg.bonus}` : '';
return `${pkg.credits}${bonus} for ${pkg.priceFormatted}`;
}).join(' · ');
buy.push(`<strong>Bundles</strong> — ${bundles} ${currency} <span style="color:#888;">(cheaper per run)</span>`);
buy.push(`<strong>Bundles</strong> — ${bundles} ${currency}`);
}
// Reward line is config-driven so it stays honest on prestige (no-payout) deployments.
let reward;
if (payoutsOn) {
const m = (config.payoutMultipliers && (config.payoutMultipliers.direct || config.payoutMultipliers.credits)) || {};
const esc = m.escape || 2;
const tre = m.escapeWithTreasure || m.treasure || 3;
reward = `<span style="color:#4ade80;">💰 Escape pays <strong>${esc}×</strong> · with treasure <strong>${tre}×</strong>.</span>`;
reward = '<span style="color:#4ade80;">💰 Exact escape and treasure rewards are shown before entry and locked for that run.</span>';
} else {
reward = `<span style="color:#fbbf24;">🏅 No crypto payout — escape for the win; top scores enter the <strong>Hall of Champions</strong>.</span>`;
}
+28 -9
View File
@@ -5,7 +5,7 @@
const Leaderboard = {
_isLoading: false,
_currentPeriod: 'all',
_currentBoard: 'champions', // 'champions' (paid) | 'pleb' (free)
_currentBoard: 'champions', // solo paid | solo/free match | credits-prestige PvP
init: function() {
$('#leaderboardButton').on('click', function() {
@@ -33,16 +33,18 @@ const Leaderboard = {
if ($('#leaderboard-panel').length) return;
var panel = $(
'<div id="leaderboard-panel" style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); z-index:2100; background:rgba(10,10,20,0.97); border:2px solid #f59e0b; padding:20px; color:#e0e0e0; min-width:380px; max-width:500px; max-height:80vh; overflow-y:auto; box-shadow:0 0 20px rgba(245,158,11,0.3); border-radius:6px;">' +
'<div id="leaderboard-panel" role="dialog" aria-modal="false" aria-labelledby="leaderboard-title" style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); z-index:2100; background:rgba(10,10,20,0.97); border:2px solid #f59e0b; padding:20px; color:#e0e0e0; min-width:380px; max-width:500px; max-height:80vh; overflow-y:auto; box-shadow:0 0 20px rgba(245,158,11,0.3); border-radius:6px;">' +
'<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px;">' +
'<strong id="leaderboard-title" style="color:#fbbf24; font-size:1.1em;">🏅 Hall of Champions</strong>' +
'<button id="close-leaderboard" style="background:#500; color:#f00; border:1px solid #f00; padding:2px 8px; cursor:pointer; font-size:14px;">✕</button>' +
'<button id="close-leaderboard" type="button" aria-label="Close scores" style="background:#500; color:#f00; border:1px solid #f00; padding:2px 8px; cursor:pointer; font-size:14px;">✕</button>' +
'</div>' +
'<div id="leaderboard-boards" style="display:flex; gap:4px; margin-bottom:8px;">' +
'<button class="lb-board" data-board="champions" style="flex:1; padding:7px; font-size:12px; font-weight:bold; cursor:pointer; border:1px solid #555; border-radius:3px;">🏅 Champions</button>' +
'<button class="lb-board" data-board="pleb" style="flex:1; padding:7px; font-size:12px; font-weight:bold; cursor:pointer; border:1px solid #555; border-radius:3px;">🪙 Pleb</button>' +
'<div id="leaderboard-boards" role="group" aria-label="Score board" style="display:flex; gap:4px; margin-bottom:8px;">' +
'<button type="button" class="lb-board" data-board="champions" style="flex:1; padding:7px; font-size:12px; font-weight:bold; cursor:pointer; border:1px solid #555; border-radius:3px;">🏅 Champions</button>' +
'<button type="button" class="lb-board" data-board="prestige" style="flex:1; padding:7px; font-size:12px; font-weight:bold; cursor:pointer; border:1px solid #555; border-radius:3px;">✨ Prestige</button>' +
'<button type="button" class="lb-board" data-board="pleb" style="flex:1; padding:7px; font-size:12px; font-weight:bold; cursor:pointer; border:1px solid #555; border-radius:3px;">🪙 Free / Pleb</button>' +
'</div>' +
'<div id="leaderboard-tabs" style="display:flex; gap:4px; margin-bottom:12px;">' +
'<div id="leaderboard-board-note" style="margin:0 0 8px;min-height:24px;color:#9ca3af;font-size:10px;line-height:1.25;"></div>' +
'<div id="leaderboard-tabs" role="group" aria-label="Score period" style="display:flex; gap:4px; margin-bottom:12px;">' +
'<button class="lb-tab" data-period="all" style="flex:1; padding:6px; font-size:11px; cursor:pointer; border:1px solid #555; border-radius:3px;">All Time</button>' +
'<button class="lb-tab" data-period="month" style="flex:1; padding:6px; font-size:11px; cursor:pointer; border:1px solid #555; border-radius:3px;">Month</button>' +
'<button class="lb-tab" data-period="week" style="flex:1; padding:6px; font-size:11px; cursor:pointer; border:1px solid #555; border-radius:3px;">Week</button>' +
@@ -84,13 +86,30 @@ const Leaderboard = {
});
var board = this._currentBoard;
$('.lb-board').each(function() {
if ($(this).data('board') === board) {
var selected = $(this).data('board') === board;
$(this).attr('aria-pressed', selected ? 'true' : 'false');
if (selected) {
$(this).css({ background: '#92400e', color: '#fff', borderColor: '#f59e0b' });
} else {
$(this).css({ background: '#1a1a2e', color: '#aaa', borderColor: '#555' });
}
});
$('#leaderboard-title').text(board === 'pleb' ? '🪙 Pleb Board' : '🏅 Hall of Champions');
var boardMeta = {
champions: {
title: '🏅 Hall of Champions',
note: 'Paid solo and configured crypto-stakes competitive results; never mixed with Free or Prestige.'
},
prestige: {
title: '✨ PvP Prestige',
note: 'Credit-entry competitive PvP scores only; never mixed with Free or the Hall of Champions.'
},
pleb: {
title: '🪙 Free / Pleb Board',
note: 'Free solo and free competitive results only; no paid entries or payouts.'
}
}[board] || {};
$('#leaderboard-title').text(boardMeta.title || 'Scores');
$('#leaderboard-board-note').text(boardMeta.note || '');
},
_fetchAndRender: function() {
+163
View File
@@ -0,0 +1,163 @@
(function (root) {
'use strict';
var MODES = {
race: {
label: 'Dungeon Race',
description: 'Outrun the other delvers, survive the shared dungeon, and reach the exit first.',
badge: 'FIRST TO EXIT',
objective: 'Reach the exit (→) first.',
participant: 'racer',
complete: 'Race complete',
victory: '🏆 You escaped first!'
},
'last-alive': {
label: 'Last Delver Standing',
description: 'Rivals can strike each other down. Survive the dungeon and be the last contender alive.',
badge: 'LAST ALIVE',
objective: 'Stay alive; move into a rival to strike.',
participant: 'contender',
complete: 'Last-delver round complete',
victory: '🏆 You are the last delver standing!'
},
'score-attack': {
label: 'Score Attack',
description: 'Build the strongest run before the arena clock expires.',
badge: 'HIGH SCORE',
objective: 'Build the highest score before time expires.',
participant: 'delver',
complete: 'Score attack complete',
victory: '🏆 You set the high score!'
},
'coop-escape': {
label: 'Co-op Escape',
description: 'Work together and get every surviving delver to safety.',
badge: 'TEAM ESCAPE',
objective: 'Work together and get every surviving delver to the exit (→).',
participant: 'teammate',
complete: 'Co-op expedition complete',
victory: '🤝 Team escaped!'
}
};
function cleanId(raw) {
var id = raw && (raw.id || raw.rulesetId);
return Object.prototype.hasOwnProperty.call(MODES, id) ? id : 'race';
}
function normalize(raw) {
raw = raw || {};
var id = cleanId(raw);
var base = MODES[id];
var win = raw.winCondition;
if (win && typeof win === 'object') win = win.type;
return {
id: id,
label: raw.label || base.label,
description: raw.description || raw.summary || base.description,
badge: String(win || raw.win || base.badge).replace(/[-_]/g, ' ').toUpperCase(),
objective: base.objective,
participant: base.participant,
complete: base.complete,
victory: base.victory,
cooperative: id === 'coop-escape'
};
}
function fromPayload(data, fallback) {
data = data || {};
var state = data.state || data.gameState || {};
return normalize(data.ruleset || state.ruleset || fallback || {});
}
function plural(mode, count) {
var word = normalize(mode).participant;
return word + (Number(count) === 1 ? '' : 's');
}
function playerFor(players, viewerId) {
players = Array.isArray(players) ? players : [];
for (var i = 0; i < players.length; i++) {
var player = players[i];
if (player && (player.you || (viewerId && player.id === viewerId))) return player;
}
return null;
}
function winnerFor(data, players) {
players = Array.isArray(players) ? players : [];
for (var i = 0; i < players.length; i++) {
if (players[i] && players[i].id === data.winnerId) return players[i];
}
return null;
}
function finalResult(data, viewerId, fallbackRuleset) {
data = data || {};
var players = Array.isArray(data.players) ? data.players : [];
var mode = fromPayload(data, fallbackRuleset);
var me = playerFor(players, viewerId);
var reason = data.reason || data.endReason || '';
if (mode.cooperative) {
var escaped = reason === 'all_escaped';
var detail = '';
if (me) detail = me.escaped ? 'you reached safety' : 'you did not escape';
return {
mode: mode,
won: escaped,
headline: escaped ? mode.victory : '☠️ The expedition was lost',
detail: detail,
text: (escaped ? mode.victory : '☠️ The expedition was lost') + (detail ? ' · ' + detail : '')
};
}
var winner = winnerFor(data, players);
var won = !!me && (me.id === data.winnerId || (!data.winnerId && Number(me.placement) === 1));
var details = [];
if (me && me.placement) details.push('you placed #' + me.placement);
if (mode.id === 'score-attack' && me && Number.isFinite(Number(me.score))) {
details.push('score ' + Number(me.score));
}
if (!won && winner) details.push('winner: ' + (winner.name || 'another delver'));
var headline = won ? mode.victory : mode.complete;
return {
mode: mode,
won: won,
headline: headline,
detail: details.join(' · '),
text: headline + (details.length ? ' · ' + details.join(' · ') : '')
};
}
function liveSummary(state, viewerId, fallbackRuleset) {
state = state || {};
var players = Array.isArray(state.players) ? state.players : [];
var mode = fromPayload({ state: state }, fallbackRuleset);
var me = playerFor(players, viewerId);
var alive = players.filter(function (p) { return p && p.alive !== false && !p.finished; }).length;
var escaped = players.filter(function (p) { return p && p.escaped; }).length;
if (mode.id === 'last-alive') {
return alive + ' ' + plural(mode, alive) + ' still in' + (me && me.alive === false ? ' · you are out' : '');
}
if (mode.id === 'score-attack') {
return alive + ' ' + plural(mode, alive) + ' still scoring' + (me && me.alive === false ? ' · you are out' : '');
}
if (mode.cooperative) {
return escaped + '/' + players.length + ' safe · ' + alive + ' still exploring';
}
if (me && me.escaped) return 'You escaped';
if (me && me.alive === false) return 'You are out · ' + alive + ' still racing';
return players.length + ' ' + plural(mode, players.length) + ' in the dungeon';
}
root.MatchUiCopy = {
modes: MODES,
normalize: normalize,
fromPayload: fromPayload,
plural: plural,
finalResult: finalResult,
liveSummary: liveSummary
};
})(window);
+50 -24
View File
@@ -143,6 +143,23 @@ const PaymentUI = {
return `<div style="font-size:0.78em;color:#fbbf24;margin-top:4px;margin-left:${options.indent || 0}px;">Includes: ${this.escapeHtml(parts.join(' • '))}</div>`;
},
payoutSummaryHtml: function(mode, currency) {
const outcomes = this.config?.payoutOutcomes?.[mode];
if (!outcomes?.escape || !outcomes?.escapeWithTreasure) {
return '<span style="color:#f87171;">Exact payout terms are unavailable. Reload before entering paid play.</span>';
}
const describe = (label, outcome) => {
if (!outcome.payable) {
const why = outcome.suppressedReason === 'below_minimum' ? ' (below configured minimum)' : '';
return `${label}: no payout${why}`;
}
const amount = `${this.escapeHtml(outcome.amountFormatted)} ${this.escapeHtml(currency)}`;
if (outcome.capApplied) return `${label}: ${amount} (configured cap applied)`;
return `${label}: ${this.escapeHtml(outcome.multiplier)}× = ${amount}`;
};
return `<span style="color:#4ade80;">💰 ${describe('Escape', outcomes.escape)} • ${describe('Treasure', outcomes.escapeWithTreasure)}</span>`;
},
render: function() {
if (!this.config) return;
@@ -172,15 +189,10 @@ const PaymentUI = {
// === SECTION 1: Use existing credits (if available) ===
if (hasCredits && this.config.creditsModeEnabled) {
const creditsPayoutsEnabled = this.config.creditsPayoutsEnabled;
const creditsMultipliers = this.config.payoutMultipliers?.credits || { escape: 2, escapeWithTreasure: 3 };
const creditsBaseValue = this.config.creditsPayoutBaseValue || this.config.singleGamePrice;
let payoutNote = '';
if (creditsPayoutsEnabled) {
const baseFormatted = this.formatPrice(creditsBaseValue);
const escapeWin = (parseFloat(baseFormatted) * creditsMultipliers.escape).toFixed(2);
const treasureWin = (parseFloat(baseFormatted) * creditsMultipliers.escapeWithTreasure).toFixed(2);
payoutNote = `<span style="color:#4ade80;">💰 Win: ${creditsMultipliers.escape}x (${escapeWin} ${currency}) • Treasure: ${creditsMultipliers.escapeWithTreasure}x (${treasureWin} ${currency})</span><br><span style="color:#fbbf24;">🏅 High scores enter the Hall of Champions</span>`;
payoutNote = `${this.payoutSummaryHtml('credits', currency)}<br><span style="color:#fbbf24;">🏅 High scores enter the Hall of Champions</span>`;
} else {
payoutNote = '<span style="color:#fbbf24;">🏅 High scores enter the Hall of Champions</span>';
}
@@ -204,7 +216,6 @@ const PaymentUI = {
// === SECTION 2: Direct payment (pay per game) ===
if (this.config.directModeEnabled) {
const price = this.config.singleGamePriceFormatted || this.formatPrice(this.config.singleGamePrice);
const multipliers = this.config.payoutMultipliers?.direct || { escape: 2, escapeWithTreasure: 3 };
// Payout-honest: only show multipliers when payouts are actually on (default off, not on).
const directPayoutsEnabled = this.config.directPayoutsEnabled != null
? !!this.config.directPayoutsEnabled
@@ -212,9 +223,7 @@ const PaymentUI = {
let payoutInfo = '';
if (directPayoutsEnabled) {
const escapeWin = (parseFloat(price) * multipliers.escape).toFixed(2);
const treasureWin = (parseFloat(price) * multipliers.escapeWithTreasure).toFixed(2);
payoutInfo = `<span style="color:#4ade80;">Win: ${multipliers.escape}x (${escapeWin} ${currency}) • Treasure: ${multipliers.escapeWithTreasure}x (${treasureWin} ${currency})</span><br><span style="color:#fbbf24;">🏅 High scores enter the Hall of Champions</span>`;
payoutInfo = `${this.payoutSummaryHtml('direct', currency)}<br><span style="color:#fbbf24;">🏅 High scores enter the Hall of Champions</span>`;
} else {
payoutInfo = '<span style="color:#fbbf24;">🏅 High scores enter the Hall of Champions</span>';
}
@@ -241,16 +250,11 @@ const PaymentUI = {
if (this.config.creditsModeEnabled && creditPackages.length > 0) {
const singlePrice = this.config.singleGamePrice;
const creditsPayoutsEnabled = this.config.creditsPayoutsEnabled;
const creditsMultipliers = this.config.payoutMultipliers?.credits || { escape: 2, escapeWithTreasure: 3 };
const creditsBaseValue = this.config.creditsPayoutBaseValue || this.config.singleGamePrice;
// Build payout info for credits mode
let creditsPayoutInfo = '';
if (creditsPayoutsEnabled) {
const baseFormatted = this.formatPrice(creditsBaseValue);
const escapeWin = (parseFloat(baseFormatted) * creditsMultipliers.escape).toFixed(2);
const treasureWin = (parseFloat(baseFormatted) * creditsMultipliers.escapeWithTreasure).toFixed(2);
creditsPayoutInfo = `<div style="font-size:0.85em;color:#4ade80;margin-bottom:10px;">💰 Win: ${creditsMultipliers.escape}x (${escapeWin} ${currency}) • Treasure: ${creditsMultipliers.escapeWithTreasure}x (${treasureWin} ${currency})</div>`;
creditsPayoutInfo = `<div style="font-size:0.85em;margin-bottom:10px;">${this.payoutSummaryHtml('credits', currency)}</div>`;
} else {
creditsPayoutInfo = `<div style="font-size:0.85em;color:#fbbf24;margin-bottom:10px;">🏅 High scores enter the Hall of Champions • bulk discount</div>`;
}
@@ -283,7 +287,7 @@ const PaymentUI = {
packagesHtml += `
<label style="display:block;padding:10px;margin:5px 0;background:#252540;border:1px solid #444;border-radius:4px;cursor:pointer;"
class="package-option" data-package-id="${pkg.id}">
<input type="radio" name="credit-package" value="${pkg.id}" ${checked} style="margin-right:10px;">
<input type="radio" name="credit-package" value="${this.escapeHtml(pkg.id)}" ${checked} style="margin-right:10px;">
<strong>${pkg.credits} credits${bonusText}</strong>${discountBadge}
<span style="float:right;color:#fbbf24;font-weight:bold;">${priceFormatted} ${currency}</span>
<div style="font-size:0.8em;color:#888;margin-top:4px;margin-left:22px;">
@@ -298,7 +302,7 @@ const PaymentUI = {
<div class="payment-section" style="margin-bottom:15px;padding:12px;background:#1a1a2e;border:1px solid #444;border-radius:6px;">
<div style="margin-bottom:10px;">
<strong style="color:#f0f0f0;">🎫 Buy Credits</strong>
<span style="font-size:0.85em;color:#888;margin-left:10px;">Bulk discount • Never expire</span>
<span style="font-size:0.85em;color:#888;margin-left:10px;">Bulk discount • tied to this browser session</span>
</div>
${creditsPayoutInfo}
<div class="packages-list">
@@ -370,24 +374,39 @@ const PaymentUI = {
}
},
handleModeSelection: function(mode, action, packageId) {
handleModeSelection: function(mode, action, packageId, acknowledgementReady, legalAcknowledgement) {
console.log("Mode selected:", mode, "Action:", action, "Package:", packageId);
if (mode === 'FREE') {
$('#payment-ui').hide();
if (window.socket) {
if (window.socket && typeof SocketHandlers !== 'undefined' && SocketHandlers.emitFairGameStart) {
// play_free records the game as FREE (Pleb leaderboard, no payout) even on
// an instance that also sells credits/entry.
window.socket.emit('play_free');
SocketHandlers.emitFairGameStart('play_free', { free: true });
}
return;
}
// A checkbox in the browser is not a legal/identity verification, but requiring a fresh
// per-session statement prevents the UI from silently opening a value-bearing action.
if (!acknowledgementReady) {
if (typeof CommerceConsent === 'undefined' || !CommerceConsent.require) {
$('#payment-status').text('Paid-play disclosures are unavailable. No payment was requested.');
return;
}
CommerceConsent.require(function(acknowledgement) {
PaymentUI.handleModeSelection(mode, action, packageId, true, acknowledgement);
});
return;
}
// If using existing credits, just start the game
if (action === 'use_credit' && this.userCredits >= 1) {
$('#payment-ui').hide();
if (window.socket) {
window.socket.emit('enter_game');
if (window.socket && typeof SocketHandlers !== 'undefined' && SocketHandlers.emitFairGameStart) {
SocketHandlers.emitFairGameStart('auto_start', {
legalAcknowledgement: legalAcknowledgement
}, true);
}
return;
}
@@ -401,6 +420,7 @@ const PaymentUI = {
}
const requestData = { type: paymentType };
if (legalAcknowledgement) requestData.legalAcknowledgement = legalAcknowledgement;
if (packageId) {
if (paymentType === 'cosmetic_pack') {
requestData.productId = packageId;
@@ -410,7 +430,13 @@ const PaymentUI = {
}
if (window.socket) {
window.socket.emit('request_payment', requestData);
if (paymentType === 'single_game' && typeof SocketHandlers !== 'undefined' && SocketHandlers.fairnessAttempt) {
var fairRequest = SocketHandlers.fairnessAttempt(requestData);
if (!fairRequest) return;
window.socket.emit('request_payment', fairRequest);
} else {
window.socket.emit('request_payment', requestData);
}
// Show loading state
$('.game-modes').hide();
+9 -3
View File
@@ -46,11 +46,17 @@
var modeRow = doc().createElement('div');
modeRow.className = 'rp-row';
RK.RENDER_MODES.forEach(function (m) {
var usable = !RK.canUseMode || RK.canUseMode(m.id);
var availability = RK.modeAvailability
? RK.modeAvailability(m.id)
: { usable: !RK.canUseMode || RK.canUseMode(m.id), runtimeAvailable: true };
var usable = availability.usable;
var b = doc().createElement('button');
b.className = 'rp-btn' + (m.id === current ? ' active' : '') + (usable ? '' : ' locked');
b.textContent = m.label + (m.premium && !usable ? ' 🔒' : '');
b.title = usable ? m.label : (m.label + ' — unlock with credits');
b.textContent = m.label + (!availability.runtimeAvailable ? ' ⛔' : (m.premium && !usable ? ' 🔒' : ''));
b.title = !availability.runtimeAvailable
? (m.label + ' — unavailable on this server (optional renderer dependency disabled)')
: (usable ? m.label : (m.label + ' — unlock with credits'));
b.setAttribute('aria-disabled', usable ? 'false' : 'true');
b.onclick = function () {
if (!usable) return;
if (RK.SPGame.setMode(m.id)) build();