Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
444 lines (371 loc) · 11.8 KB
/
Copy pathscript.js
File metadata and controls
444 lines (371 loc) · 11.8 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
const suits = ['♠', '♥', '♦', '♣'];
const ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
let deck = [];
let playerHand = [];
let splitHand = [];
let dealerHand = [];
let chips = 1000;
let highestBankroll = 1000;
let currentBet = 0;
let splitBet = 0;
let isSplit = false;
let activeHandIndex = 0;
let gameOver = false;
let currentTitle = "Rookie";
let audioCtx = null;
const MILESTONES = [
{ threshold: 100000, title: "Luck Is My Name" },
{ threshold: 50000, title: "Unbreakable" },
{ threshold: 20000, title: "Top Gun" },
{ threshold: 10000, title: "Pro" },
{ threshold: 5000, title: "Jack of All Trades" }
];
// --- SOUND SYNTHESIZER ---
function initAudio() {
try {
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
} catch (e) {
console.warn("Audio Context setup prevented by browser:", e);
}
}
function playSound(type) {
if (!audioCtx) return;
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.connect(gain);
gain.connect(audioCtx.destination);
const now = audioCtx.currentTime;
if (type === 'card') {
osc.type = 'triangle';
osc.frequency.setValueAtTime(300, now);
osc.frequency.exponentialRampToValueAtTime(100, now + 0.08);
gain.gain.setValueAtTime(0.15, now);
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.08);
osc.start(now);
osc.stop(now + 0.08);
} else if (type === 'chip') {
osc.type = 'sine';
osc.frequency.setValueAtTime(1200, now);
osc.frequency.exponentialRampToValueAtTime(800, now + 0.05);
gain.gain.setValueAtTime(0.2, now);
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.05);
osc.start(now);
osc.stop(now + 0.05);
} else if (type === 'unlock') {
const notes = [523.25, 659.25, 783.99, 1046.50];
notes.forEach((freq, index) => {
const noteOsc = audioCtx.createOscillator();
const noteGain = audioCtx.createGain();
noteOsc.connect(noteGain);
noteGain.connect(audioCtx.destination);
noteOsc.frequency.setValueAtTime(freq, now + index * 0.1);
noteGain.gain.setValueAtTime(0.15, now + index * 0.1);
noteGain.gain.exponentialRampToValueAtTime(0.001, now + index * 0.1 + 0.3);
noteOsc.start(now + index * 0.1);
noteOsc.stop(now + index * 0.1 + 0.3);
});
}
}
// --- LOCAL STORAGE MANAGER ---
function loadGameState() {
try {
const savedChips = localStorage.getItem('bj_chips');
const savedHigh = localStorage.getItem('bj_highest');
const savedTitle = localStorage.getItem('bj_title');
if (savedChips !== null && !isNaN(parseInt(savedChips))) chips = parseInt(savedChips);
if (savedHigh !== null && !isNaN(parseInt(savedHigh))) highestBankroll = parseInt(savedHigh);
if (savedTitle !== null) currentTitle = savedTitle;
} catch (e) {
console.warn("Storage read failed, using defaults:", e);
}
const chipsEl = document.getElementById('chips');
const titleEl = document.getElementById('player-title');
if (chipsEl) chipsEl.textContent = chips;
if (titleEl) titleEl.textContent = currentTitle;
}
function saveGameState() {
try {
localStorage.setItem('bj_chips', chips);
localStorage.setItem('bj_highest', highestBankroll);
localStorage.setItem('bj_title', currentTitle);
} catch (e) {
console.warn("Storage write failed:", e);
}
}
// --- START GAME & RESET ACTIONS ---
function enterGame(event) {
if (event) event.preventDefault();
const startScreen = document.getElementById('start-screen');
if (startScreen) {
startScreen.style.display = 'none';
}
initAudio();
loadGameState();
checkMilestones();
checkBrokeState();
}
function checkBrokeState() {
if (chips <= 0) {
setTimeout(() => {
const brokeScreen = document.getElementById('broke-screen');
if (brokeScreen) {
brokeScreen.classList.remove('hidden');
}
}, 600);
}
}
function resetGame() {
chips = 1000;
saveGameState();
const chipsEl = document.getElementById('chips');
if (chipsEl) chipsEl.textContent = chips;
const brokeScreen = document.getElementById('broke-screen');
if (brokeScreen) {
brokeScreen.classList.add('hidden');
}
document.getElementById('status-message').textContent = 'Place a bet to start playing!';
}
function checkMilestones() {
if (chips > highestBankroll) {
highestBankroll = chips;
}
let earnedTitle = "Rookie";
for (let milestone of MILESTONES) {
if (highestBankroll >= milestone.threshold) {
earnedTitle = milestone.title;
break;
}
}
let upgraded = false;
if (earnedTitle !== currentTitle) {
currentTitle = earnedTitle;
upgraded = true;
playSound('unlock');
}
const titleEl = document.getElementById('player-title');
if (titleEl) titleEl.textContent = currentTitle;
saveGameState();
return upgraded;
}
function createDeck() {
deck = [];
for (let suit of suits) {
for (let rank of ranks) {
deck.push({ suit, rank });
}
}
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[deck[i], deck[j]] = [deck[j], deck[i]];
}
}
function getCardValue(card) {
if (['J', 'Q', 'K'].includes(card.rank)) return 10;
if (card.rank === 'A') return 11;
return parseInt(card.rank);
}
function calculateScore(hand) {
let total = 0;
let aces = 0;
for (let card of hand) {
total += getCardValue(card);
if (card.rank === 'A') aces++;
}
while (total > 21 && aces > 0) {
total -= 10;
aces--;
}
return total;
}
function renderHand(hand, elementId, hideFirstCard = false) {
const container = document.getElementById(elementId);
if (!container) return;
container.innerHTML = '';
hand.forEach((card, index) => {
const cardDiv = document.createElement('div');
cardDiv.classList.add('card', 'draw-anim');
if (hideFirstCard && index === 0) {
cardDiv.classList.add('hidden');
cardDiv.textContent = '?';
} else {
if (card.suit === '♥' || card.suit === '♦') {
cardDiv.classList.add('red');
}
cardDiv.textContent = `${card.rank}${card.suit}`;
}
container.appendChild(cardDiv);
});
}
function startGame() {
if (chips <= 0) {
checkBrokeState();
return;
}
const betInput = document.getElementById('bet-input');
currentBet = parseInt(betInput.value);
if (isNaN(currentBet) || currentBet <= 0 || currentBet > chips) {
document.getElementById('status-message').textContent = 'Invalid bet amount!';
return;
}
playSound('chip');
chips -= currentBet;
document.getElementById('chips').textContent = chips;
saveGameState();
createDeck();
playerHand = [deck.pop(), deck.pop()];
dealerHand = [deck.pop(), deck.pop()];
splitHand = [];
isSplit = false;
activeHandIndex = 0;
splitBet = 0;
gameOver = false;
playSound('card');
document.getElementById('split-hand-section').style.display = 'none';
document.getElementById('betting-controls').style.display = 'none';
document.getElementById('game-controls').style.display = 'flex';
document.getElementById('double-btn').style.display = 'inline-block';
if (playerHand[0].rank === playerHand[1].rank && chips >= currentBet) {
document.getElementById('split-btn').style.display = 'inline-block';
} else {
document.getElementById('split-btn').style.display = 'none';
}
document.getElementById('status-message').textContent = 'Hit, Stand, or Double Down?';
updateUI(true);
}
function updateUI(hideDealerCard = false) {
renderHand(playerHand, 'player-cards');
document.getElementById('player-score').textContent = calculateScore(playerHand);
if (isSplit) {
renderHand(splitHand, 'player-cards-2');
document.getElementById('player-score-2').textContent = calculateScore(splitHand);
document.getElementById('active-hand-indicator').textContent = activeHandIndex === 0 ? '(Hand 1)' : '(Hand 2)';
} else {
document.getElementById('active-hand-indicator').textContent = '';
}
renderHand(dealerHand, 'dealer-cards', hideDealerCard);
document.getElementById('dealer-score').textContent = hideDealerCard ? '?' : calculateScore(dealerHand);
}
function hit() {
if (gameOver) return;
playSound('card');
document.getElementById('double-btn').style.display = 'none';
document.getElementById('split-btn').style.display = 'none';
const currentHand = activeHandIndex === 0 ? playerHand : splitHand;
currentHand.push(deck.pop());
updateUI(true);
if (calculateScore(currentHand) > 21) {
if (isSplit && activeHandIndex === 0) {
activeHandIndex = 1;
document.getElementById('status-message').textContent = 'Hand 1 Busted! Playing Hand 2...';
updateUI(true);
} else {
if (!isSplit) {
endGame('Bust! You lost your bet.');
} else {
processDealerTurn();
}
}
}
}
function doubleDown() {
if (gameOver || chips < currentBet) {
document.getElementById('status-message').textContent = 'Not enough chips to Double Down!';
return;
}
playSound('chip');
chips -= currentBet;
currentBet *= 2;
document.getElementById('chips').textContent = chips;
playSound('card');
playerHand.push(deck.pop());
updateUI(true);
if (calculateScore(playerHand) > 21) {
endGame('Busted on Double Down!');
} else {
stand();
}
}
function handleSplit() {
if (chips < currentBet) return;
playSound('chip');
isSplit = true;
splitBet = currentBet;
chips -= splitBet;
document.getElementById('chips').textContent = chips;
playSound('card');
splitHand.push(playerHand.pop());
playerHand.push(deck.pop());
splitHand.push(deck.pop());
document.getElementById('split-hand-section').style.display = 'block';
document.getElementById('split-btn').style.display = 'none';
document.getElementById('double-btn').style.display = 'none';
document.getElementById('status-message').textContent = 'Playing Hand 1...';
updateUI(true);
}
function stand() {
if (gameOver) return;
if (isSplit && activeHandIndex === 0) {
activeHandIndex = 1;
document.getElementById('status-message').textContent = 'Playing Hand 2...';
updateUI(true);
return;
}
processDealerTurn();
}
function processDealerTurn() {
while (calculateScore(dealerHand) < 17) {
dealerHand.push(deck.pop());
playSound('card');
}
const dealerScore = calculateScore(dealerHand);
updateUI(false);
let totalPayout = 0;
let summary = [];
totalPayout += evaluateHandScore(playerHand, currentBet, dealerScore, summary, "Hand 1");
if (isSplit) {
totalPayout += evaluateHandScore(splitHand, splitBet, dealerScore, summary, "Hand 2");
}
chips += totalPayout;
endGame(summary.join(' | '));
}
function evaluateHandScore(hand, bet, dealerScore, summaryArray, label) {
const score = calculateScore(hand);
if (score > 21) {
summaryArray.push(`${label}: Bust`);
return 0;
}
if (dealerScore > 21 || score > dealerScore) {
summaryArray.push(`${label}: Win`);
return bet * 2;
} else if (score === dealerScore) {
summaryArray.push(`${label}: Push`);
return bet;
} else {
summaryArray.push(`${label}: Loss`);
return 0;
}
}
function endGame(message) {
gameOver = true;
document.getElementById('chips').textContent = chips;
const upgraded = checkMilestones();
if (upgraded) {
message += ` 🎉 New Title Unlocked: ${currentTitle}!`;
}
saveGameState();
document.getElementById('status-message').textContent = message;
document.getElementById('betting-controls').style.display = 'flex';
document.getElementById('game-controls').style.display = 'none';
checkBrokeState();
}
document.addEventListener('DOMContentLoaded', () => {
const startBtn = document.querySelector('#start-screen button');
if (startBtn) {
startBtn.addEventListener('click', enterGame);
}
});