-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcasino-engine.js
More file actions
255 lines (225 loc) · 9.45 KB
/
Copy pathcasino-engine.js
File metadata and controls
255 lines (225 loc) · 9.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
(function () {
'use strict';
const SYMBOLS = ['🍒', '🍋', '⭐', '7', '💎', '🍀'];
const SPIN_COST = 5;
let spinning = false;
let panel;
let reels = [];
let resultEl;
let balanceEl;
let payoutEl;
let netEl;
let spinBtn;
let machine;
async function getSupabaseClient() {
if (!window.HWAuth || typeof window.HWAuth.getClient !== 'function') return null;
const maybeClient = window.HWAuth.getClient();
const resolvedClient = maybeClient && typeof maybeClient.then === 'function' ? await maybeClient : maybeClient;
return resolvedClient && typeof resolvedClient.rpc === 'function' ? resolvedClient : null;
}
function getPoints() {
try {
if (window.HWPoints && typeof window.HWPoints.get === 'function') return window.HWPoints.get();
if (window.HWPoints && typeof window.HWPoints.getState === 'function') return window.HWPoints.getState().points;
} catch (error) {}
return 0;
}
function setText(el, value) {
if (el) el.textContent = String(value);
}
function money(value) {
const n = Number.parseInt(value, 10) || 0;
return n + ' CP';
}
function rpcWithTimeout(client, name, args, ms) {
var rpc = client.rpc(name, args || {});
var timer = new Promise(function (_, reject) {
window.setTimeout(function () {
reject(new Error('Slots timed out. Close and reopen the machine, then try again.'));
}, ms || 9000);
});
return Promise.race([rpc, timer]);
}
function randomSymbol() {
return SYMBOLS[Math.floor(Math.random() * SYMBOLS.length)];
}
function ensurePanel() {
if (panel) return panel;
panel = document.createElement('section');
panel.className = 'casino-engine-panel';
panel.id = 'casinoEnginePanel';
panel.setAttribute('aria-hidden', 'true');
panel.innerHTML = '' +
'<div class="casino-machine" role="dialog" aria-modal="true" aria-labelledby="casinoEngineTitle">' +
'<div class="casino-engine-head">' +
'<div>' +
'<span class="casino-engine-kicker">Supabase Slots</span>' +
'<h2 id="casinoEngineTitle">Vintage Slots</h2>' +
'<p>One wallet. Supabase decides the reels, payout, ledger, and your HYPHSWORLD Cool Points balance.</p>' +
'</div>' +
'<button class="casino-engine-close" type="button" data-casino-close>Close</button>' +
'</div>' +
'<div class="casino-reel-stage">' +
'<div class="casino-reels" data-casino-reels>' +
'<span class="casino-reel">🍒</span>' +
'<span class="casino-reel">7</span>' +
'<span class="casino-reel">🍋</span>' +
'</div>' +
'<div class="casino-result" data-casino-result>Ready. Spin costs 5 Cool Points.</div>' +
'</div>' +
'<div class="casino-engine-stats">' +
'<div class="casino-engine-stat"><span>Balance</span><strong data-casino-balance>0 CP</strong></div>' +
'<div class="casino-engine-stat"><span>Payout</span><strong data-casino-payout>0 CP</strong></div>' +
'<div class="casino-engine-stat"><span>Net</span><strong data-casino-net>0 CP</strong></div>' +
'</div>' +
'<div class="casino-engine-actions">' +
'<button class="casino-spin-btn" type="button" data-casino-spin>SPIN 5 CP</button>' +
'<button class="casino-back-btn" type="button" data-casino-close>Back To Casino</button>' +
'</div>' +
'</div>';
document.body.appendChild(panel);
machine = panel.querySelector('.casino-machine');
reels = Array.from(panel.querySelectorAll('.casino-reel'));
resultEl = panel.querySelector('[data-casino-result]');
balanceEl = panel.querySelector('[data-casino-balance]');
payoutEl = panel.querySelector('[data-casino-payout]');
netEl = panel.querySelector('[data-casino-net]');
spinBtn = panel.querySelector('[data-casino-spin]');
panel.querySelectorAll('[data-casino-close]').forEach((button) => {
button.addEventListener('click', closeSlots);
});
if (spinBtn) spinBtn.addEventListener('click', spinSlots);
panel.addEventListener('click', (event) => {
if (event.target === panel) closeSlots();
});
return panel;
}
function updateBalance() {
setText(balanceEl, money(getPoints()));
const casinoBalance = document.getElementById('casinoCoolPoints');
if (casinoBalance) casinoBalance.textContent = String(getPoints());
}
async function refreshPoints() {
try {
if (window.HWPoints && typeof window.HWPoints.refresh === 'function') await window.HWPoints.refresh();
} catch (error) {}
updateBalance();
}
function openSlots() {
ensurePanel();
panel.classList.add('is-open');
panel.setAttribute('aria-hidden', 'false');
document.body.classList.add('casino-engine-open');
updateBalance();
setText(payoutEl, '0 CP');
setText(netEl, '0 CP');
setText(resultEl, 'Ready. Spin costs 5 Cool Points.');
if (spinBtn) spinBtn.focus();
}
function closeSlots() {
if (!panel) return;
panel.classList.remove('is-open');
panel.setAttribute('aria-hidden', 'true');
document.body.classList.remove('casino-engine-open');
}
function animateReels(finalReels) {
const wrap = panel ? panel.querySelector('[data-casino-reels]') : null;
if (wrap) wrap.classList.add('is-spinning');
let ticks = 0;
const timer = window.setInterval(() => {
reels.forEach((reel) => { reel.textContent = randomSymbol(); });
ticks += 1;
if (ticks >= 14) {
window.clearInterval(timer);
reels.forEach((reel, index) => { reel.textContent = finalReels[index] || randomSymbol(); });
if (wrap) wrap.classList.remove('is-spinning');
}
}, 70);
return new Promise((resolve) => window.setTimeout(resolve, 1050));
}
function resultCopy(data) {
if (!data) return 'Spin complete.';
const result = String(data.result || '').replace(/_/g, ' ');
const payout = Number.parseInt(data.payout, 10) || 0;
const net = Number.parseInt(data.net, 10) || 0;
if (data.result === 'jackpot') return 'JACKPOT. ' + payout + ' Cool Points hit the ledger.';
if (payout > 0) return result.toUpperCase() + '. Payout: ' + payout + ' CP. Net: ' + net + ' CP.';
return 'No hit that spin. Cost: ' + SPIN_COST + ' CP. Run it back clean.';
}
async function spinSlots() {
if (spinning) return;
ensurePanel();
spinning = true;
if (spinBtn) spinBtn.disabled = true;
if (machine) machine.classList.remove('is-win', 'is-loss');
setText(resultEl, 'Connecting to Supabase engine...');
setText(payoutEl, '—');
setText(netEl, '—');
try {
const client = await getSupabaseClient();
if (!client) throw new Error('Supabase client not ready. Reload the casino page and try again.');
setText(resultEl, 'Calling Supabase engine...');
const { data, error } = await rpcWithTimeout(client, 'spin_slots', {}, 9000);
if (error) throw error;
const payload = data || {};
if (payload.ok === false || payload.result === 'not_enough_points') {
setText(payoutEl, money(0));
setText(netEl, money(0));
setText(resultEl, payload.message || 'Not enough Cool Points for this spin.');
if (typeof payload.balance !== 'undefined') setText(balanceEl, money(payload.balance));
if (machine) machine.classList.add('is-loss');
return;
}
await animateReels(payload.reels || []);
setText(payoutEl, money(payload.payout));
setText(netEl, money(payload.net));
setText(resultEl, resultCopy(payload));
if (machine) machine.classList.add((payload.payout || 0) > 0 ? 'is-win' : 'is-loss');
await refreshPoints();
if (typeof payload.balance !== 'undefined') {
setText(balanceEl, money(payload.balance));
const casinoBalance = document.getElementById('casinoCoolPoints');
if (casinoBalance) casinoBalance.textContent = String(payload.balance);
}
} catch (error) {
setText(resultEl, error.message || 'Slots engine missed. Try again.');
if (machine) machine.classList.add('is-loss');
} finally {
spinning = false;
if (spinBtn) spinBtn.disabled = false;
}
}
function bindCasinoCards() {
document.querySelectorAll('.casino-room[data-room="slots"]').forEach((card) => {
card.style.cursor = 'pointer';
card.addEventListener('click', (event) => {
const interactive = event.target.closest('a,button');
if (interactive && !interactive.matches('[data-room-action="spin"],[data-room-action="preview"]')) return;
event.preventDefault();
openSlots();
});
});
document.querySelectorAll('[data-room-action="spin"],[data-room-action="preview"]').forEach((button) => {
const card = button.closest('.casino-room[data-room="slots"]');
if (!card) return;
button.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
openSlots();
if (button.dataset.roomAction === 'spin') {
window.setTimeout(spinSlots, 180);
}
}, true);
});
}
function boot() {
ensurePanel();
bindCasinoCards();
updateBalance();
document.addEventListener('hyph:points-updated', updateBalance);
window.addEventListener('hw:points-change', updateBalance);
window.HWCasinoEngine = { openSlots, closeSlots, spinSlots, refreshPoints };
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);
else boot();
})();