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
+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();