forked from rocketacademy/basics-blackjack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
565 lines (504 loc) · 20.1 KB
/
script.js
File metadata and controls
565 lines (504 loc) · 20.1 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
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
// GLOBAL VARIABLES
// current player
var currentPlayer = "0";
// number of players
var numOfPlayers = "number of players";
// OBJECTS/ ARRAYS
// card deck - stores entire deck of unshuffled cards
var deck = [];
// current player hand - stores current player hand
var currentPlayerHand = [];
// individual player statistics
var allPlayerStatistics = [];
// dealer hand
var computerHand = [];
// GAME MODES
// player number input
var gameModeNumOfPlayers = "input numOfPlayers";
// player bets
// var gameModePlaceBets = "place bets";
var gameModeCurrentPlayerTurn = "current player turn";
// player number decision
// var gameModeCurrentPlayerDecision = "current player decision";
// game mode player change
// var gameModeChangePlayer = " change player turn";
// computer decision
var gameModeComputerTurn = "computer turn";
// compare scores
var gameModeCompareScores = "compare scores";
// default starting game mode where all arrays are empty/reset
var gameModeReset = "reset";
var gameMode = gameModeReset;
// ******** START CARD HELPER FUNCTIONS START *******
// Create a deck of cards
var makeDeck = function () {
// Initialise an empty deck array
var cardDeck = [];
// Initialise an array of the 4 suits in our deck. We will loop over this array.
var suits = ["spades", "hearts", "clubs", "diamonds"];
// suitValue helps compare suit superiority
var suitValue = [4, 3, 2, 1];
// card value is the score we compare against player vs computer. index [0] is Ace/1 where this is not read by the code generating the deck, index [1] for Ace is default cardValue of 11.
var cardValue = [1, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10];
// Loop over the suits array
var suitIndex = 0;
while (suitIndex < suits.length) {
// Store the current suit in a variable
var currentSuit = suits[suitIndex];
// Store the current suit value in a variable
var currentSuitValue = suitValue[suitIndex];
// Loop from 1 to 13 to create all cards for a given suit
// Notice rankCounter starts at 1 and not 0, and ends at 13 and not 12.
// This is an example of a loop without an array.
var rankCounter = 1;
while (rankCounter <= 13) {
// Store the current card value in a variable
var currentCardValue = cardValue[rankCounter];
// rankCounter determines name of card
var cardName = rankCounter;
// If rank is 1, 11, 12, 13 set cardName to the ace or face card's name
if (cardName == 1) {
cardName = "Ace";
} else if (cardName == 11) {
cardName = "Jack";
} else if (cardName == 12) {
cardName = "Queen";
} else if (cardName == 13) {
cardName = "King";
}
// Create a new card with the current name, suit, suitValue, rankCounter/name of card in number value and cardValue
var card = {
name: cardName,
suit: currentSuit,
suitValue: currentSuitValue,
rank: rankCounter,
cardValue: currentCardValue,
};
// Add the new card to the deck
cardDeck.push(card);
// Increment rankCounter to iterate over the next rank
rankCounter += 1;
}
// Increment the suit index to iterate over the next suit
suitIndex += 1;
}
// Return the completed card deck
return cardDeck;
};
// Get a random index ranging from 0 (inclusive) to max (exclusive) - used in shuffleCards()
var getRandomIndex = function (max) {
return Math.floor(Math.random() * max);
};
// Shuffle the elements in the cardDeck array
var shuffleCards = function (cardDeck) {
// Loop over the card deck array once
var currentIndex = 0;
while (currentIndex < cardDeck.length) {
// Select a random index in the deck
var randomIndex = getRandomIndex(cardDeck.length);
// Select the card that corresponds to randomIndex
var randomCard = cardDeck[randomIndex];
// Select the card that corresponds to currentIndex
var currentCard = cardDeck[currentIndex];
// Swap positions of randomCard and currentCard in the deck
cardDeck[currentIndex] = randomCard;
cardDeck[randomIndex] = currentCard;
// Increment currentIndex
currentIndex = currentIndex + 1;
}
// Return the shuffled deck
return cardDeck;
};
// draw one random card
var drawOneCard = function (shuffledDeck) {
var oneRandomCard = shuffledDeck.pop();
return oneRandomCard;
};
// draw player hand function uses pop to get 2 random cards out of shuffleddeck.
var drawStartingPlayerHand = function (shuffledDeck) {
currentPlayerHand.push(drawOneCard(shuffledDeck));
currentPlayerHand.push(drawOneCard(shuffledDeck));
};
// draw player hand function uses pop to get 1 random cards out of shuffleddeck.
var hitPlayerHand = function (shuffledDeck) {
currentPlayerHand.push(drawOneCard(shuffledDeck));
};
// computer hand function draws 2 random cards from shuffleddeck
var drawStartingComputerHand = function (shuffledDeck) {
computerHand.push(drawOneCard(shuffledDeck));
computerHand.push(drawOneCard(shuffledDeck));
};
// calculates total sum of computer hand array, checks for ace value, stores to all player statistics index [0]
var calculateComputerHand = function () {
// calculates sum of computerhandarray
var sumOfComputerHandArray = 0;
for (var cardIndex = 0; cardIndex < computerHand.length; cardIndex += 1) {
sumOfComputerHandArray = Math.floor(
sumOfComputerHandArray + computerHand[cardIndex].cardValue
);
// conditional ace value function NOT WORKING
var numOfAces = 0;
if (computerHand[cardIndex].rank == 1) {
numOfAces = numOfAces + 1;
}
for (var index = 0; index < numOfAces; index += 1) {
if (sumOfComputerHandArray > 21) {
sumOfComputerHandArray = sumOfComputerHandArray - 10;
}
}
}
return sumOfComputerHandArray;
};
////////// computerhand function not working /////////////
// check sumofcomputerhandarray and stores result to allplayerstatistics[0]
// var checkComputerHand = function () {
// var myOutputValue = "";
// var sumOfComputerHandArray = calculateComputerHand();
// if (computerHand.length == 2 && sumOfComputerHandArray == 21) {
// myOutputValue = `DEALER BLACKJACK! Dealer drew ${computerHand[0].name} of ${computerHand[0].suit} and ${computerHand[1].name} of ${computerHand[1].suit}.`;
// allPlayerStatistics[0].playerName = "Dealer";
// allPlayerStatistics[0].totalSum = "blackjack";
// gameMode = gameModeCompareScores;
// console.log("dealerblackjack");
// return myOutputValue;
// }
// // check if >=17 && <21 = stand
// else if (sumOfComputerHandArray >= 17 && sumOfComputerHandArray <= 21) {
// // myOutputValue = displayComputerHand`which comes up to ${sumOfComputerHandArray}`;
// myOutputValue = ______();
// console.log(myOutputValue);
// console.log("dealer stand");
// gameMode = gameModeCompareScores;
// return myOutputValue;
// }
// // check if <=16, hit until <=21
// else if (sumOfComputerHandArray < 17) {
// computerHand.push(drawOneCard(shuffledDeck));
// // myOutputValue = displayComputerHand`which comes up to (${sumOfComputerHandArray})`;
// myOutputValue = _________();
// console.log(myOutputValue);
// console.log("dealer hand less than 17, should hit until 21");
// return myOutputValue;
// }
// // check if >21 = bust
// else {
// allPlayerStatistics[0].totalSum = "bust";
// myOutputValue = "dealer busts!";
// console.log("dealer busts");
// gameMode = gameModeCompareScores;
// return myOutputValue;
// }
// };
////////// computer hand function not working CONTROL FLOW ISSUE ///////////
// ******** END CARD HELPER FUNCTIONS END *******
// ****** START GAME MODE/MAIN HELPER FUNCTIONS START *****
// game mode = gamemodenumofplayers, input validation to check number of players is a number, not isnan
var checkNumOfPlayers = function (input) {
if (input == isNaN || input > 11) {
return (myOutputValue = `Your input is invalid. Please enter the number of players playing today.`);
} else {
numOfPlayers = input;
return numOfPlayers;
}
};
// game mode = gamemodenumofplayers, push number of players to create player names and 100 points per player. array starts at index 1 for player 1.
var createPlayerProfiles = function (numOfPlayers) {
// for loop to run player counter and increment to max of numOfPlayers, setting up each player 1 to numOfPlayers with 100 points - betting NOT COMPLETED -
for (
var playerCounter = 0;
playerCounter <= numOfPlayers;
playerCounter += 1
) {
var playerNameValue = playerCounter;
var currentPlayerTokens = 100;
var sumOfCards = 0;
// var card = {
// name: cardName,
// suit: currentSuit,
// suitValue: currentSuitValue,
// rank: rankCounter,
// cardValue: currentCardValue,
// };
//creates new player in an object array at index 0
var player = {
playerName: playerNameValue,
tokens: currentPlayerTokens,
totalSum: sumOfCards,
};
// pushes individual player stat into all player stats within the loop
allPlayerStatistics.push(player);
}
return allPlayerStatistics;
};
// prints current player hand to myoutputvalue
var displayCurrentPlayerHand = function (currentPlayerHand) {
var printCurrentPlayerHand = "";
for (var index = 0; index < currentPlayerHand.length; index += 1) {
var cardsOfCurrentPlayerHand = `${currentPlayerHand[index].name} of ${currentPlayerHand[index].suit}<br>`;
printCurrentPlayerHand = printCurrentPlayerHand + cardsOfCurrentPlayerHand;
}
return `Player ${currentPlayer}, you have drawn ${printCurrentPlayerHand}`;
};
var displayComputerHand = function (computerHand) {
var printComputerHand = "";
for (var index = 0; index < computerHand.length; index += 1) {
var cardsOfComputerHand = `${computerHand[index].name} of ${computerHand[index].suit}<br>`;
printComputerHand = printComputerHand + cardsOfComputerHand;
}
return `Dealer has drawn ${printComputerHand}`;
};
// var allocateCurrentPlayerHandToAllPlayerStats = function(){
// }
// var displayAllPlayerStatistics = function () {
// var printAllPlayerStatistics = "";
// for (playerIndex = 1; playerIndex < allPlayerStatistics.length; playerIndex += 1) {
// var allPlayerHands = `${allPlayerStatistics[playerIndex].name} of ${allPlayerStatistics[playerIndex].suit}<br>`;
// printAllPlayerStatistics = printAllPlayerStatistics + allPlayerHands;
// console.log(printAllPlayerStatistics);
// }
// return `Player ${currentPlayer}, you have drawn ${printAllPlayerStatistics}`;
// };
// game mode reset all DOESN'T WORK >.<
var resetAllGameMode = function () {
gameMode = gameModeReset;
if (gameMode == "reset") {
currentPlayer = "0";
numOfPlayers = "input numofPlayers";
deck = [];
shuffledDeck = [];
computerHand = [];
currentPlayerHand = [];
allPlayerStatistics = [];
return `The game has been reset.`;
}
};
// ****** END GAME MODE/MAIN HELPER FUNCTIONS END *****
// ****** START MATH FUNCTIONS START *****
var calculateTotalHand = function () {
var totalSumOfCurrentPlayerHandArray = 0;
for (
var cardIndex = 0;
cardIndex < currentPlayerHand.length;
cardIndex += 1
) {
totalSumOfCurrentPlayerHandArray = Math.floor(
totalSumOfCurrentPlayerHandArray + currentPlayerHand[cardIndex].cardValue
);
// conditional ace value function NOT WORKING
var numOfAces = 0;
if (currentPlayerHand[cardIndex].rank == 1) {
numOfAces = numOfAces + 1;
}
for (var index = 0; index < numOfAces; index += 1) {
if (totalSumOfCurrentPlayerHandArray > 21) {
totalSumOfCurrentPlayerHandArray =
totalSumOfCurrentPlayerHandArray - 10;
}
}
}
allPlayerStatistics[currentPlayer].totalSum =
totalSumOfCurrentPlayerHandArray;
return totalSumOfCurrentPlayerHandArray;
};
var checkPlayerScore = function () {
//player blackjack only if 2 cards and total card value = 21, payout = 1.5x
var myOutputValue = "";
if (
currentPlayerHand[currentPlayer].length < 2 &&
allPlayerStatistics[currentPlayer].totalSum == 21
) {
allPlayerStatistics[currentPlayer].totalSum = "blackjack";
myOutputValue = `BLACKJACK!`;
return myOutputValue;
// player 777 payout =7x
} else if (
currentPlayerHand[0].cardValue == 7 &&
currentPlayerHand[1].cardValue == 7 &&
currentPlayerHand[2].cardValue == 7
) {
allPlayerStatistics[currentPlayer].totalSum = "seventimes";
myOutputValue = `TRIPLE 7 WIN!`;
return myOutputValue;
}
// player 5cardwin payout =2x
else if (
currentPlayerHand[currentPlayer].length <= 5 &&
allPlayerStatistics[currentPlayer].totalSum <= 21
) {
allPlayerStatistics[currentPlayer].totalSum = "fivecardwin";
myOutputValue = `5 cards less than 21, great hand!`;
return myOutputValue;
} else if (allPlayerStatistics[currentPlayer].totalSum > 21) {
allPlayerStatistics[currentPlayer].totalSum = "bust";
myOutputValue = `Sorry ${currentPlayer}, you bust! Click submit to start the game again.`;
//currently only using 1 playermode
gameMode = gameModeReset;
resetAllGameMode();
deck = makeDeck();
var shuffledDeck = shuffleCards(deck);
return myOutputValue;
} else if (allPlayerStatistics[currentPlayer].totalSum < 21);
myOutputValue = `Please enter h to hit or s to stand and click submit.`;
return myOutputValue;
};
//
//****** END MATH FUNCTIONS END *****
// generate card deck
// shuffle deck
deck = makeDeck();
var shuffledDeck = shuffleCards(deck);
console.log(shuffledDeck);
var main = function (input) {
var myOutputValue = "";
var currentPlayerScore = "";
// launch screen - instructions are on HTML page. This if statement:
// 1. creates allPlayerStatistics[]
// 2. allows user to input number of players
// 3. output is a prompt for player to click submit to draw starting hand
if (currentPlayer == 0 && gameMode == "reset") {
// first input from user requires indication of numofplayers. input validation for any input other than numbers is invalid.
gameMode = gameModeNumOfPlayers;
// run input validation function to check that input is a number
var numOfPlayers = checkNumOfPlayers(input);
//call function that generates allplayerstats objarray. we need to store .playerName .tokens .sumOfCards
createPlayerProfiles(numOfPlayers);
currentPlayer = 1;
myOutputValue =
myOutputValue + `welcome player(s)! Click submit to draw your cards. `;
return myOutputValue;
}
console.log(currentPlayer);
console.log(gameMode);
//switch game mode from input = number of players to current player turn
if (currentPlayer == 1 && gameMode == "input numOfPlayers") {
gameMode = gameModeCurrentPlayerTurn;
}
// gamemode = current player turn. the idea is to push currentplayer into all player statistics after the current player turn ends. for loop cycles through all players until each player either wins, busts or hits "s". code is written only for 1 player at the moment. bust = needs hard reset and "s" should prompt computer turn.
if (currentPlayer == 1 && gameMode == "current player turn") {
for (var playerIndex = 1; playerIndex < numOfPlayers; playerIndex += 1) {
currentPlayer = playerIndex;
}
if (
gameMode == "current player turn" &&
currentPlayer == playerIndex &&
input == "h"
) {
hitPlayerHand(shuffledDeck);
calculateTotalHand(currentPlayer);
currentPlayerScore = checkPlayerScore(currentPlayer);
myOutputValue = displayCurrentPlayerHand(currentPlayerHand);
return myOutputValue + currentPlayerScore;
} else if (
gameMode == "current player turn" &&
currentPlayer == playerIndex &&
input == "s"
) {
myOutputValue = "you've selected Stand! It's the computer's turn.";
// modify this for including additional players
// currentPlayerScore = checkPlayerScore(currentPlayer);
// myOutputValue = displayCurrentPlayerHand();
// currentPlayerHand = [];
gameMode = gameModeComputerTurn;
currentPlayer = "computer";
return myOutputValue;
} else if (
gameMode == "current player turn" &&
currentPlayer == playerIndex
) {
drawStartingPlayerHand(shuffledDeck);
drawStartingComputerHand(shuffledDeck);
calculateTotalHand(currentPlayer);
currentPlayerScore = checkPlayerScore(currentPlayer);
myOutputValue = displayCurrentPlayerHand(currentPlayerHand);
return myOutputValue + currentPlayerScore;
}
}
// game mode changes to computer turn after all player(s) have had a turn.
gameMode == gameModeComputerTurn;
console.log(currentPlayer);
console.log(gameMode);
if (gameMode == "computer turn" && currentPlayer == "computer") {
var sumOfComputerHandArray = calculateComputerHand();
var computerOutcome = "";
if (computerHand.length == 2) {
if (sumOfComputerHandArray == 21) {
computerOutcome = `DEALER BLACKJACK! Dealer drew ${computerHand[0].name} of ${computerHand[0].suit} and ${computerHand[1].name} of ${computerHand[1].suit}.`;
allPlayerStatistics[0].playerName = "Dealer";
allPlayerStatistics[0].totalSum = "blackjack";
return computerOutcome;
}
}
if (sumOfComputerHandArray < 16) {
computerHand.push(drawOneCard(shuffledDeck));
computerOutcome = displayComputerHand(computerHand);
sumOfComputerHandArray = calculateComputerHand();
return computerOutcome;
} else if (sumOfComputerHandArray >= 17 && sumOfComputerHandArray <= 21) {
allPlayerStatistics[0].totalSum = sumOfComputerHandArray;
computerOutcome = displayComputerHand(computerHand);
gameMode = gameModeCompareScores;
return computerOutcome;
} else if (sumOfComputerHandArray > 21) {
computerOutcome = displayComputerHand(computerHand);
allPlayerStatistics[0].totalSum = "bust";
console.log(allPlayerStatistics[0].totalSum);
gameMode = gameModeCompareScores;
return computerOutcome;
}
}
console.log(gameMode);
// scores are compared within the all player statistics array. computer hand is stored at index [0], player 1 at [1] etc. currently hard coded for all the permutations, need to work on functions for each condition.
console.log(allPlayerStatistics[0].totalSum);
console.log(allPlayerStatistics[1].totalSum);
if (gameMode == "compare scores") {
// for (var playerIndex = 1; playerIndex <= numOfPlayers; playerIndex += 1) {
// console.log(myOutputValue);
if (
// tie for the following outcomes: dealer blackjack == player(s) blackjack || dealer score == player score.
//player win blackjack, fivecard and seventimes is an instant win regardless of dealer hand
(allPlayerStatistics[0].totalSum == "blackjack" &&
allPlayerStatistics[1].totalSum == "blackjack") ||
allPlayerStatistics[0].totalSum == allPlayerStatistics[1].totalSum
) {
myOutputValue = "it's a tie!";
return myOutputValue;
} else if (
allPlayerStatistics[0].totalSum > allPlayerStatistics[1].totalSum ||
(allPlayerStatistics[0].totalSum <= 21 &&
allPlayerStatistics[1].totalSum == "bust")
) {
myOutputValue = "sorry player loses to dealer";
console.log(myOutputValue);
return myOutputValue;
} else if (
allPlayerStatistics[0].totalSum < allPlayerStatistics[1].totalSum ||
(allPlayerStatistics[0].totalSum == "bust" &&
allPlayerStatistics[1].totalSum <= 21)
) {
myOutputValue = "player wins dealer";
console.log(myOutputValue);
return myOutputValue;
} else if (
(allPlayerStatistics[0].totalSum =
"bust" || allPlayerStatistics[0].totalSum <= 21) &&
(allPlayerStatistics[1].totalSum == "blackjack" ||
allPlayerStatistics[1].totalSum == "seventimes" ||
allPlayerStatistics[1].totalSum == "fivecardwin")
) {
myOutputValue = "player wins dealer";
console.log(myOutputValue);
return myOutputValue;
} else if (
(allPlayerStatistics[0].totalSum =
"blackjack" ||
allPlayerStatistics[0].totalSum == "seventimes" ||
allPlayerStatistics[0].totalSum == "fivecardwin")
) {
myOutputValue = "dealer special win!";
console.log(myOutputValue);
return myOutputValue;
}
}
console.log(myOutputValue);
return myOutputValue;
};