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
289 lines (260 loc) Β· 9.34 KB
/
script.js
File metadata and controls
289 lines (260 loc) Β· 9.34 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
///// Global variables/////
let playerHand = [];
let computerHand = [];
let state = "Draw cards for both";
///// Global functions/////
// Function to create a deck of 52 cards
let makeDeck = function () {
// Initialise an empty deck array
let cardDeck = [];
// Initialise an array of the 4 suits in our deck. We will loop over this array.
let suits = ["β₯οΈ", "β¦οΈ", "β£οΈ", "β οΈ"];
// Loop over the suits array
let suitIndex = 0;
while (suitIndex < suits.length) {
// Store the current suit in a variable
let currentSuit = suits[suitIndex];
let rankCounter = 1;
while (rankCounter <= 13) {
// By default, the card name is the same as rankCounter
let cardName = rankCounter;
// If rank is 1, 11, 12, or 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";
}
// If name is Jack, Queen and King, set cardRank to 10 points
let cardRank = 0;
if (cardName == "Jack" || cardName == "Queen" || cardName == "King") {
cardRank = 10;
} else {
cardRank = rankCounter;
}
// Create a new card with the current name, suit, and rank
let card = {
name: cardName,
suit: currentSuit,
rank: cardRank,
};
// 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;
};
// Function to shuffle the deck
let 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;
};
let shuffledDeck = shuffleCards(makeDeck());
//Function to check for blackjack
let checkBlackJack = function (hand) {
let hasBlackJack = false;
let hasTen = false;
let hasAce = false;
for (position = 0; position < hand.length; position += 1) {
if (hand[position].rank == "10") {
hasTen = true;
}
if (hand[position].name == "Ace") {
hasAce = true;
}
if (hasTen && hasAce) {
hasBlackJack = true;
console.log("black jack");
}
return hasBlackJack;
}
};
// Function to calculate sum of cards
let getSum = function (handarray) {
let sum = 0; // Auto reset each time
let hasAce = false;
// Loop to count cards in hand
for (let sumCounter = 0; sumCounter < handarray.length; sumCounter += 1) {
sum = sum + handarray[sumCounter].rank;
if (handarray[sumCounter].rank == 1) {
hasAce = true;
}
}
// Ace is read as 11 if hand is less 21 or less
// Ace is read as 1 by default
if (sum + 10 < 22 && hasAce) {
// Adding 10 to the sum first to check if the hand > 21
sum = sum + 10;
}
return sum;
};
// Function to calculate sum of cards
let showHandCards = function (hand) {
let handOutput = "";
for (counter = 0; counter < hand.length; counter += 1) {
handOutput += hand[counter].name + " " + hand[counter].suit;
if (counter != hand.length - 1) {
handOutput += " , "; // no commas after the last card
}
}
return handOutput;
};
// Function to output message for PLAYER card sum and the cards
let showPlayerMessage = function (hand) {
myOutputValue = `Your hand:<br><b>${showHandCards(
hand
)}</b><br><br>Your total: ${getSum(hand)}`;
return myOutputValue;
};
// Function to output message for DEALER card sum and the cards
let showComputerMessage = function (hand) {
myOutputValue = `Dealer's hand:<br><b>${showHandCards(
hand
)}</b><br><br>Dealer's total: ${getSum(hand)}`;
return myOutputValue;
};
///// Main function /////
let main = function (input) {
console.log("State:", state);
console.log("Input:", input);
// Game start, draw 2 cards for player and dealer
if (state == "Draw cards for both") {
for (counter = 0; counter < 2; counter += 1) {
let playerDraw = shuffledDeck.pop();
let computerDraw = shuffledDeck.pop();
playerHand.push(playerDraw);
computerHand.push(computerDraw);
}
console.log(`Player draw: ${showHandCards(playerHand)}`);
console.log(`Computer draw: ${showHandCards(computerHand)}`);
// Check for Blackjack
let playerHasBlackJack = checkBlackJack(playerHand);
let computerHasBlackJack = checkBlackJack(computerHand);
console.log(`Player has blackjack = ${playerHasBlackJack}`);
console.log(`Computer has blackjack = ${computerHasBlackJack}`);
// If only player has blackjack
if (playerHasBlackJack && !computerHasBlackJack) {
let myOutputValue = `Computer blackjack!<br><br>Computer wins!`;
return myOutputValue;
}
// If only dealer has blackjack
if (!playerHasBlackJack && computerHasBlackJack) {
let myOutputValue = `Player blackjack!<br><br>Player wins!`;
return myOutputValue;
}
// If both player and dealer has blackjack
if (playerHasBlackJack && computerHasBlackJack) {
let myOutputValue = `Double blackjack!<br><br>It's a tie!`;
return myOutputValue;
}
let sumPlayerHand = getSum(playerHand);
let sumComputerHand = getSum(computerHand);
console.log("Player sum: " + sumPlayerHand);
console.log("Computer sum (initial draw): " + sumComputerHand);
// If no blackjack, give player choice to hit or stand
let myOutputValue = `${showPlayerMessage(
playerHand
)}<br><br>Enter 'h' for hit or 's' for stand.`;
state = "Player choice";
return myOutputValue;
}
// If player enters blank or any other words, return with error msg
if (
state == "Player choice" &&
(!input || !["h", "s"].includes(input.toLowerCase()))
) {
return "Oops! Please only enter 'h' for hit or 's' for stand!";
}
// If player hit and has less than 21, draw another card
if (input.toLowerCase() == "h" && state == "Player choice") {
playerDraw = shuffledDeck.pop();
playerHand.push(playerDraw);
console.log("Player draw: " + showHandCards(playerHand));
let sumPlayerHand = getSum(playerHand);
let sumComputerHand = getSum(computerHand);
console.log("Player sum: " + sumPlayerHand);
console.log("Computer sum: " + sumComputerHand);
// If player hit and bust, dealers's turn begin
if (sumPlayerHand > 21) {
state = "Computer turn";
let myOutputValue = `${showPlayerMessage(
playerHand
)}<br><br>You bust! Dealer's turn!`;
return myOutputValue;
}
// If player hit and did not bust, player's turn again
let myOutputValue = `${showPlayerMessage(
playerHand
)}<br><br>Enter 'h' for hit or 's' for stand.`;
return myOutputValue;
}
/////DEALER TURN/////
// Dealer is also computer
// If player stand OR player hit and bust, dealer's turn
if (input.toLowerCase() == "s" || state == "Computer turn") {
let sumPlayerHand = getSum(playerHand);
let sumComputerHand = getSum(computerHand);
console.log("Player sum: " + sumPlayerHand);
console.log("Computer sum: " + sumComputerHand);
// If dealer has 16 or less , it needs to draw until greater than 16
while (sumComputerHand < 17) {
let computerDraw = shuffledDeck.pop();
computerHand.push(computerDraw);
sumComputerHand = getSum(computerHand);
console.log("Computer final sum: " + sumComputerHand);
}
let myOutputValue = `${showPlayerMessage(
playerHand
)}<br><br>${showComputerMessage(computerHand)}<br><br>`;
// If player did not bust and has a higher score, player win
if (sumPlayerHand < 22 && sumPlayerHand > sumComputerHand) {
myOutputValue = myOutputValue + "<b>ππ Player wins! ππ</b>";
// If player did not bust and dealer bust, player win
} else if (sumPlayerHand < 22 && sumComputerHand > 21) {
myOutputValue = myOutputValue + "<b>π£π£ Dealer bust! You win! π£π£ </b>";
// If player and dealer have same scores, both tie
} else if (sumPlayerHand == sumComputerHand) {
myOutputValue = myOutputValue + "<b>ππ It's a tie! ππ</b>";
// If player and dealer both bust, both tie
} else if (sumPlayerHand > 21 && sumComputerHand > 21) {
myOutputValue = myOutputValue + "<b>π₯π₯ Both bust! It's a tie! π₯π₯";
// Dealer wins
} else {
myOutputValue = myOutputValue + "<b>β¨β¨ Dealer wins! β¨β¨";
}
// Reset the game
shuffledDeck = shuffleCards(makeDeck());
console.log("Deck reset");
playerHand = [];
computerHand = [];
state = "Draw cards for both";
return myOutputValue;
}
};