-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblackjack.js
535 lines (464 loc) · 15.6 KB
/
blackjack.js
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
const cards = [
["2 of Clubs", 2, "cards/2_of_clubs.png"],
["3 of Clubs", 3, "cards/3_of_clubs.png"],
["4 of Clubs", 4, "cards/4_of_clubs.png"],
["5 of Clubs", 5, "cards/5_of_clubs.png"],
["6 of Clubs", 6, "cards/6_of_clubs.png"],
["7 of Clubs", 7, "cards/7_of_clubs.png"],
["8 of Clubs", 8, "cards/8_of_clubs.png"],
["9 of Clubs", 9, "cards/9_of_clubs.png"],
["10 of Clubs", 10, "cards/10_of_clubs.png"],
["Jack of Clubs", 10, "cards/jack_of_clubs.png"],
["Queen of Clubs", 10, "cards/queen_of_clubs.png"],
["King of Clubs", 10, "cards/king_of_clubs.png"],
["Ace of Clubs", 1, "cards/ace_of_clubs.png"],
["2 of Diamonds", 2, "cards/2_of_diamonds.png"],
["3 of Diamonds", 3, "cards/3_of_diamonds.png"],
["4 of Diamonds", 4, "cards/4_of_diamonds.png"],
["5 of Diamonds", 5, "cards/5_of_diamonds.png"],
["6 of Diamonds", 6, "cards/6_of_diamonds.png"],
["7 of Diamonds", 7, "cards/7_of_diamonds.png"],
["8 of Diamonds", 8, "cards/8_of_diamonds.png"],
["9 of Diamonds", 9, "cards/9_of_diamonds.png"],
["10 of Diamonds", 10, "cards/10_of_diamonds.png"],
["Jack of Diamonds", 10, "cards/jack_of_diamonds.png"],
["Queen of Diamonds", 10, "cards/queen_of_diamonds.png"],
["King of Diamonds", 10, "cards/king_of_diamonds.png"],
["Ace of Diamonds", 1, "cards/ace_of_diamonds.png"],
["2 of Hearts", 2, "cards/2_of_hearts.png"],
["3 of Hearts", 3, "cards/3_of_hearts.png"],
["4 of Hearts", 4, "cards/4_of_hearts.png"],
["5 of Hearts", 5, "cards/5_of_hearts.png"],
["6 of Hearts", 6, "cards/6_of_hearts.png"],
["7 of Hearts", 7, "cards/7_of_hearts.png"],
["8 of Hearts", 8, "cards/8_of_hearts.png"],
["9 of Hearts", 9, "cards/9_of_hearts.png"],
["10 of Hearts", 10, "cards/10_of_hearts.png"],
["Jack of Hearts", 10, "cards/jack_of_hearts.png"],
["Queen of Hearts", 10, "cards/queen_of_hearts.png"],
["King of Hearts", 10, "cards/king_of_hearts.png"],
["Ace of Hearts", 1, "cards/ace_of_hearts.png"],
["2 of Spades", 2, "cards/2_of_spades.png"],
["3 of Spades", 3, "cards/3_of_spades.png"],
["4 of Spades", 4, "cards/4_of_spades.png"],
["5 of Spades", 5, "cards/5_of_spades.png"],
["6 of Spades", 6, "cards/6_of_spades.png"],
["7 of Spades", 7, "cards/7_of_spades.png"],
["8 of Spades", 8, "cards/8_of_spades.png"],
["9 of Spades", 9, "cards/9_of_spades.png"],
["10 of Spades", 10, "cards/10_of_spades.png"],
["Jack of Spades", 10, "cards/jack_of_spades.png"],
["Queen of Spades", 10, "cards/queen_of_spades.png"],
["King of Spades", 10, "cards/king_of_spades.png"],
["Ace of Spades", 1, "cards/ace_of_spades.png"],
];
let bank = 1000;
let betAmount = 0;
let insuranceBet = 0;
let hasHit = false;
let turnOver = false;
let deck = [];
let playerHand = [];
let dealerHand = [];
let playerBusted = false;
let betsOn = true;
let gotBlackjack = false;
const dealerCards = document.querySelector(".dealer-cards p");
const playerCards = document.querySelector(".player-cards p");
const playerTotal = document.querySelector(".player-total p");
const playerTurn = document.querySelector(".player-turn p");
const dealerTotal = document.querySelector(".dealer-total p");
const dealerTurn = document.querySelector(".dealer-turn p");
const betDisplay = document.querySelector(".bet p");
const insuranceBetDisplay = document.querySelector(".insurance-bet p");
const result = document.querySelector(".result p");
const betForm = document.querySelector(".bet-form");
const betFormAmount = document.getElementById("betForm");
const betCounter = betForm.querySelector("h2");
const betAmountDisplay = betFormAmount.querySelector("p");
const betButtons = document.querySelectorAll(".bet-button");
document.getElementById("betForm").addEventListener("submit", function (event) {
event.preventDefault();
});
// Set up the bet buttons
betButtons.forEach((button) => {
button.addEventListener("click", function () {
const amountToAdd = parseInt(button.value);
betAmount += amountToAdd;
betCounter.innerHTML = convertBetToChips(betAmount);
let betCounterHTML = `Bet Amount: ${betAmount}<br>`;
betAmountDisplay.innerHTML = betCounterHTML;
});
});
/*
Helper Functions
*/
function getHandTotal(hand) {
let total1 = 0;
let total11 = 0;
let aces = 0;
for (let card of hand) {
let [name, value] = card;
total1 += value;
total11 += value;
if (name.startsWith("Ace")) aces += 1;
}
if (aces > 0) total11 += aces * 10;
while (total11 > 21 && aces > 0) {
total11 -= 10;
aces -= 1;
}
return total1 === total11 || total11 > 21 ? total1 : [total1, total11];
}
function getFinalTotal(hand) {
let total = getHandTotal(hand);
return Array.isArray(total) ? total[1] : total;
}
function displayDealerCards() {
let dealerCardsHTML = `<img src="${dealerHand[0][2]}" alt="Card" class="card-image">`;
for (let i = 1; i < dealerHand.length; i++) {
dealerCardsHTML += `<img src="${dealerHand[i][2]}" alt="Card" class="card-image">`;
}
dealerCards.innerHTML = dealerCardsHTML;
dealerTotal.innerHTML = formatHandTotal(getHandTotal(dealerHand), "Dealer");
}
function updateBank() {
document.querySelector(".bank p").innerHTML = `Bank: ${bank}`;
}
function formatHandTotal(total, owner) {
if (Array.isArray(total) && total.length === 2) {
return `${owner} Total: ${total[0]} or ${total[1]}`; // If it's a tuple, return two numbers separated by a comma
} else {
return `${owner} Total: ${total}`; // If it's not a tuple, just convert it to a string
}
}
function convertBetToChips(betAmount) {
let betCounterHTML = "";
let betCount = betAmount;
while (betCount > 0) {
if (betCount >= 100) {
betCount -= 100;
betCounterHTML += `<img src="poker_chips/black.png" alt="Bet" class="bet-image">`;
} else if (betCount >= 25) {
betCount -= 25;
betCounterHTML += `<img src="poker_chips/green.png" alt="Bet" class="bet-image">`;
} else if (betCount >= 10) {
betCount -= 10;
betCounterHTML += `<img src="poker_chips/red.png" alt="Bet" class="bet-image">`;
} else if (betCount >= 5) {
betCount -= 5;
betCounterHTML += `<img src="poker_chips/blue.png" alt="Bet" class="bet-image">`;
}
}
return betCounterHTML;
}
function generateButtons() {
// Clear any existing buttons before appending new ones
document.querySelectorAll(".button-container").forEach((buttonContainer) => {
buttonContainer.remove();
});
const buttonContainer = document.createElement("div");
buttonContainer.className = "button-container";
// Append button container to the document body directly
document.body.appendChild(buttonContainer);
if (!turnOver) {
const hitButton = document.createElement("button");
hitButton.textContent = "Hit";
hitButton.className = "hit";
hitButton.addEventListener("click", function (event) {
event.preventDefault();
hit();
});
buttonContainer.appendChild(hitButton);
}
if (!turnOver) {
const standButton = document.createElement("button");
standButton.textContent = "Stand";
standButton.className = "stand";
standButton.addEventListener("click", function (event) {
event.preventDefault();
stand();
});
buttonContainer.appendChild(standButton);
}
if (canDoubleDown()) {
const doubleDownButton = document.createElement("button");
doubleDownButton.textContent = "Double Down";
doubleDownButton.className = "double-down";
doubleDownButton.addEventListener("click", function (event) {
event.preventDefault();
doubleDown();
});
buttonContainer.appendChild(doubleDownButton);
}
if (canGetInsurance()) {
const insuranceButton = document.createElement("button");
insuranceButton.textContent = "Insurance";
insuranceButton.className = "insurance";
insuranceButton.addEventListener("click", function (event) {
event.preventDefault();
insurance();
});
buttonContainer.appendChild(insuranceButton);
}
// if (canSplit()) {
// const splitButton = document.createElement('button');
// splitButton.textContent = 'Split';
// splitButton.className ='split';
// splitButton.addEventListener('click', function(event) {
// event.preventDefault();
// split();
// determineWinner();
// });
// buttonContainer.appendChild(splitButton);
// }
const resetButton = document.createElement("button");
resetButton.textContent = "Reset";
resetButton.className = "reset";
resetButton.addEventListener("click", function (event) {
event.preventDefault();
reset();
});
buttonContainer.appendChild(resetButton);
}
function canSplit() {
if (hasHit || playerHand.length !== 2) return false;
let card1Value = playerHand[0][1];
let card2Value = playerHand[1][1];
return card1Value == card2Value;
}
function canDoubleDown() {
if (hasHit || turnOver || playerHand.length !== 2) return false;
if (getFinalTotal(playerHand) === 21) return false;
let totalsAllowed = [9, 10, 11];
let total = getHandTotal(playerHand);
return Array.isArray(total)
? totalsAllowed.includes(total[0]) || totalsAllowed.includes(total[1])
: totalsAllowed.includes(total);
}
function canGetInsurance() {
return (
insuranceBet === 0 && !turnOver && !hasHit && dealerHand[0][0][0] === "A"
);
}
function checkBetsOn() {
if (!betsOn) {
document.querySelector(".bank p").classList.add("hidden");
console.log("bets are off");
betAmount = 0;
const betForm = document.getElementById("betForm");
betForm.classList.add("hidden");
dealCards();
generateButtons();
}
}
function determineWinner() {
dealerTurn.innerHTML = "";
let playerTotalValue = getFinalTotal(playerHand);
let dealerTotalValue = getFinalTotal(dealerHand);
console.log("Final total player: " + playerTotalValue);
console.log("Final total dealer: " + dealerTotalValue);
if (gotBlackjack) {
console.log("Player Wins!");
result.innerHTML = "Blackjack! Player Wins!";
betDisplay.innerHTML += betDisplay.innerHTML;
bank += 2.5 * betAmount;
updateBank();
return 1;
} else if (playerTotalValue > 21) {
console.log("Player Busted!");
result.innerHTML = "Player Busted!";
betDisplay.innerHTML = "";
updateBank();
return -1;
} else if (dealerTotalValue > 21) {
console.log("Dealer Busted!");
result.innerHTML = "Dealer Busted!";
if (!playerBusted) {
result.innerHTML = "Dealer Busted! Player Wins!";
betDisplay.innerHTML += betDisplay.innerHTML;
bank += 2 * betAmount;
updateBank();
}
return 1;
} else if (playerTotalValue > dealerTotalValue) {
console.log("Player Wins!");
result.innerHTML = "Player Wins!";
bank += 2 * betAmount;
betDisplay.innerHTML += betDisplay.innerHTML;
updateBank();
return 1;
} else if (playerTotalValue < dealerTotalValue) {
console.log("Dealer Wins!");
result.innerHTML = "Dealer Wins!";
betDisplay.innerHTML = "";
updateBank();
return -1;
} else {
console.log("Push!");
bank += betAmount;
result.innerHTML = "Push!";
updateBank();
return 0;
}
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/*
Game Actions
*/
function split() {
console.log("splitting");
}
function doubleDown() {
betAmount *= 2;
let newCard = deck.pop();
playerHand.push(newCard);
let playerCardsHTML = "";
for (let i = 0; i < playerHand.length; i++) {
playerCardsHTML += `<img src="${playerHand[i][2]}" alt="Card" class="card-image">`;
}
playerCards.innerHTML = playerCardsHTML;
playerTotal.innerHTML = formatHandTotal(getHandTotal(playerHand), "Player");
betDisplay.innerHTML = convertBetToChips(betAmount);
stand();
}
function insurance() {
console.log("Getting insurance");
insuranceBet = parseFloat(0.5 * betAmount);
bank -= insuranceBet;
updateBank();
insuranceBetDisplay.innerHTML = convertBetToChips(insuranceBet);
generateButtons();
}
function hit() {
hasHit = true;
let newCard = deck.pop();
playerHand.push(newCard);
let playerCardsHTML = "";
for (let i = 0; i < playerHand.length; i++) {
playerCardsHTML += `<img src="${playerHand[i][2]}" alt="Card" class="card-image">`;
}
playerCards.innerHTML = playerCardsHTML;
playerTotal.innerHTML = formatHandTotal(getHandTotal(playerHand), "Player");
if (getFinalTotal(playerHand) > 21) {
console.log("Player Busted!");
playerBusted = true;
result.innerHTML = "Player Busted!";
betDisplay.innerHTML = "";
updateBank();
stand();
}
generateButtons();
}
async function stand() {
await delay(200);
playerTurn.innerHTML = "";
dealerTurn.innerHTML = "Dealer's Turn";
turnOver = true;
generateButtons();
dealerCards.innerHTML = `<img src="${dealerHand[0][2]}" alt="Card" class="card-image">`;
await delay(500);
displayDealerCards();
let finalTotal = getFinalTotal(dealerHand);
if (finalTotal === 21) {
console.log("Dealer Wins!");
result.innerHTML = "Blackjack! Dealer Wins!";
if (insuranceBet > 0) {
insuranceBetDisplay.innerHTML += insuranceBetDisplay.innerHTML;
bank += 2 * insuranceBet;
console.log("Got insurance!");
}
updateBank();
return -1;
} else {
insuranceBetDisplay.innerHTML = "";
}
while (true) {
await delay(800);
finalTotal = getFinalTotal(dealerHand);
console.log(dealerHand);
if (finalTotal >= 17) break;
let newCard = deck.pop();
dealerHand.push(newCard);
displayDealerCards();
dealerTotal.innerHTML = formatHandTotal(getHandTotal(dealerHand), "Dealer");
}
if (finalTotal > 21) {
console.log("Dealer Busted!");
} else {
console.log(finalTotal);
}
determineWinner();
}
/*
Game Play
*/
function reset() {
turnOver = false;
gotBlackjack = false;
deck = [];
playerHand = [];
dealerHand = [];
result.innerHTML = "";
dealerCards.innerHTML = "";
dealerTotal.innerHTML = "";
playerCards.innerHTML = "";
playerTotal.innerHTML = "";
betDisplay.innerHTML = "";
insuranceBetDisplay.innerHTML = "";
playerBusted = false;
insuranceBet = 0;
betAmount = 0;
betCounter.innerHTML = "";
betAmountDisplay.innerHTML = "";
const buttonContainer = document.querySelector(".button-container");
buttonContainer.innerHTML = "";
const betForm = document.querySelector(".bet-form");
betForm.classList.remove("hidden");
play();
}
function bet() {
console.log("Bet Amount:", betAmount);
betDisplay.innerHTML = `Bet: ${betAmount}`;
betDisplay.innerHTML = convertBetToChips(betAmount);
bank -= betAmount;
updateBank();
const betForm = document.querySelector(".bet-form");
betForm.classList.add("hidden");
dealCards();
generateButtons();
}
function dealCards() {
playerTurn.innerHTML = "Your Turn";
deck = [...cards];
deck.sort(() => Math.random() - 0.5);
for (let i = 0; i < 2; i++) {
playerHand.push(deck.pop());
dealerHand.push(deck.pop());
}
// Get initial cards
dealerCards.innerHTML = `<img src="${dealerHand[0][2]}" alt="Card" class="card-image">`;
playerCards.innerHTML = `<img src="${playerHand[0][2]}" alt="Card" class="card-image"><img src="${playerHand[1][2]}" alt="Card" class="card-image">`;
// Get initial totals
playerTotal.innerHTML = formatHandTotal(getHandTotal(playerHand), "Player");
if (getFinalTotal(playerHand) === 21) {
console.log("Player Wins!");
result.innerHTML = "Blackjack! Player Wins!";
betDisplay.innerHTML;
bank += betAmount * 2.5;
gotBlackjack = true;
let originalHTML = betDisplay.innerHTML;
betDisplay.innerHTML += originalHTML;
let halfLength = Math.floor(originalHTML.length / 2);
betDisplay.innerHTML += originalHTML.substring(0, halfLength);
updateBank();
stand();
}
}
function play() {
checkBetsOn();
updateBank();
}
play();