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
339 lines (312 loc) · 12.3 KB
/
Copy pathscript.js
File metadata and controls
339 lines (312 loc) · 12.3 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
//helper functions provided by rocket in 9.1 & 9.2
//make a deck
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 = ["Hearts♥️", "Diamonds♦️", "Clubs♣️", "Spades♠️"];
// Loop over the suits array
var suitIndex = 0;
while (suitIndex < suits.length) {
// Store the current suit in a variable
var currentSuit = suits[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) {
// By default, the card name is the same as rankCounter
var cardName = rankCounter;
// These are custom lines added for blackjack scoring. add cardscore, then setting ace, j q and k to score 10 points worth each. we will deal with ace being a variable score later during the main function
let cardScore = rankCounter;
if (cardScore === 11 || cardScore === 12 || cardScore === 13) {
cardScore = 10;
}
if (cardScore === 1) {
cardScore = 11;
}
// 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";
}
// Create a new card with the current name, suit, and rank
var card = {
name: cardName,
suit: currentSuit,
rank: rankCounter,
score: cardScore,
};
// 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).
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;
};
/* things to do
1) edit the card editor to add in points for blackjack score counting (D)
3) plan for states
a) "initialize" should make it such that when you click submit. draws 2 cards, shows player the results and total score. tells you to hit or stand.
b) "playerMidgame" should have 2 inputs, hit or stand. plays a card if hit, shows the results and total score.
ace will be lowered to score 10 if a card is hit. check for bust, if bust and in the presence of ace, reduce ace to 1.
if stand, move game phase to "computerMidgame"
c) "computerMidgame" should basically make the cpu hit until the cpu is either bigger than player, or busts. then moves to "result" phase
d) "result" phase shows who has won. moves it to cleaning phase
e) "scoreboard" phase will resets the deck, the hand and all required stuff on submit, moves it back to "initialize". also shows scoreboard
*/
let deck = shuffleCards(makeDeck());
let gameState = "initialize";
let playerHand = [];
let computerHand = [];
let playerScore = 0;
let computerScore = 0;
let playerBustStatus = false;
let computerBustStatus = false;
let playerWonTimes = 0;
let computerWonTimes = 0;
//main game
function main(gameInput) {
let input = gameInput.toLowerCase();
if (gameState === "initialize") {
if (input !== "") {
return `Hello Player! Please do not type in anything and just press submit to start a game of Blackjack!`;
} else {
dealInitialHands();
let initializeWinnerMessage = checkInitialResults();
return initializeWinnerMessage;
}
} else if (gameState === "playerMidgame") {
if (input !== "h" && input !== "s") {
return `Please input only hit or stand!<br>${outputMessage()}`;
} else if (input === "h") {
let playerMidGameAction = playerMidGameHitAction();
return playerMidGameAction;
} else if (input === "s") {
gameState = "computerMidgame";
return `You have chosen to stand at ${playerScore} points!<br><br> The Computer will now take it's turn!<br> ${outputMessageForCPU()}`;
}
} else if (gameState === "computerMidgame") {
let computerAction = checkComputerScoring();
return computerAction;
} else if (gameState === "result") {
gameState = "scoreboard";
let endGameResult = checkEndGameScenario();
return endGameResult;
} else if (gameState === "scoreboard") {
refreshEverything();
return `Scoreboard- You : Computer <br> ${playerWonTimes} : ${computerWonTimes}<br> Click Submit to start a new round!`;
}
}
// end of main
// dealing initial hands small function.
function dealInitialHands() {
for (let i = 0; i < 2; i++) {
playerHand.push(deck.pop());
computerHand.push(deck.pop());
}
}
//checking initial hand for blackjacks
function checkInitialHands(playerHand, computerHand) {
let playerStartScore = 0;
let computerStartScore = 0;
let initialPhaseResult = "";
for (let i = 0; i < playerHand.length; i += 1) {
playerStartScore += playerHand[i].score;
}
for (let j = 0; j < computerHand.length; j += 1) {
computerStartScore += computerHand[j].score;
}
if (playerStartScore === computerStartScore && playerStartScore === 21) {
initialPhaseResult = "double blackjack";
} else if (playerStartScore === 21 && computerStartScore !== 21) {
initialPhaseResult = "player blackjack";
} else if (playerStartScore !== 21 && computerStartScore === 21) {
initialPhaseResult = "computer blackjack";
} else {
initialPhaseResult = "game continue";
}
return initialPhaseResult;
}
// function to reset the whole game
function refreshEverything() {
gameState = "initialize";
deck = [];
deck = shuffleCards(makeDeck());
playerHand = [];
computerHand = [];
playerScore = 0;
computerScore = 0;
playerBustStatus = false;
computerBustStatus = false;
}
//function to display all players cards depending on current size of hand
function callCards() {
let message = "";
for (i = 0; i < playerHand.length; i += 1) {
message += `<br>${playerHand[i].name} of ${playerHand[i].suit} [${playerHand[i].score}]`;
}
return message;
}
// function to display all cpu cards depending on current size of hand
function callCPUCards() {
let message = "";
for (i = 0; i < computerHand.length; i += 1) {
message += `<br>${computerHand[i].name} of ${computerHand[i].suit} [${computerHand[i].score}]`;
}
return message;
}
//function to calculate player scores
function calculatePlayerScore(playerHand) {
let score = 0;
for (let i = 0; i < playerHand.length; i += 1) {
score += playerHand[i].score;
}
return score;
}
//function to calculate computer scores
function calculateComputerScore(computerHand) {
let score = 0;
for (let i = 0; i < computerHand.length; i += 1) {
score += computerHand[i].score;
}
return score;
}
//function to check for aces, and reduce ONLY one ace each time if there are multiple aces.
function checkForAces(playerHand) {
let temporaryPlayerScore = calculatePlayerScore(playerHand);
if (temporaryPlayerScore > 21) {
for (let i = 0; i < playerHand.length; i += 1) {
if (playerHand[i].name === "Ace") {
playerHand[i].name = "🂡 Ace";
playerHand[i].score = 1;
break;
}
}
}
}
//output message for player turn
function outputMessage() {
return `The Cards that you drew are as follows..${callCards()}<br>The total sum is currently ${playerScore}.<br> Please decide if you would like to Hit or Stand! Submit h to hit and submit s to stand!`;
}
//output message for computer turn
function outputMessageForCPU() {
return `The Cards that the CPU drew are as follows.. ${callCPUCards()}<br>The total sum is currently ${computerScore}. <br> Please click on submit to proceed!`;
}
//function to shorten main code when player hits
function playerHits() {
playerHand.push(deck.pop());
checkForAces(playerHand);
playerScore = calculatePlayerScore(playerHand);
console.log(playerScore, playerHand);
}
function checkInitialResults() {
if (checkInitialHands(playerHand, computerHand) === "double blackjack") {
gameState = "scoreboard";
return `Both you and the Computer have gotten blackjacks! This is a draw! Click on Submit to continue!`;
} else if (
checkInitialHands(playerHand, computerHand) === "player blackjack"
) {
gameState = "scoreboard";
playerWonTimes += 1;
return "You Win! You have a blackjack! Click on Submit to continue!";
} else if (
checkInitialHands(playerHand, computerHand) === "computer blackjack"
) {
gameState = "scoreboard";
computerWonTimes += 1;
return "You Lose! Computer scored a blackjack! Click on Submit to continue!";
} else if (checkInitialHands(playerHand, computerHand === "game continue")) {
checkForAces(playerHand);
playerScore = calculatePlayerScore(playerHand);
computerScore = calculateComputerScore(computerHand);
gameState = "playerMidgame";
return outputMessage();
}
}
function checkComputerScoring() {
if (computerScore > 21) {
gameState = "result";
computerBustStatus = true;
return `The Computer drew ${
computerHand[computerHand.length - 1].name
} of ${
computerHand[computerHand.length - 1].suit
}! The Computer BUSTED at 💣${computerScore}💣!<br><br> Click Submit to proceed!`;
} else if (computerScore < 17) {
computerHand.push(deck.pop());
checkForAces(computerHand);
computerScore = calculateComputerScore(computerHand);
return outputMessageForCPU();
} else if (computerScore > 16 && computerScore < 22) {
gameState = "result";
return `The Computer has chosen to stand at ${computerScore}! Click Submit to Proceed!`;
} else {
return "ERROR: LOGIC WRONG PLEASE CHECK";
}
}
function playerMidGameHitAction() {
playerHits();
if (playerScore > 21) {
gameState = "computerMidgame";
playerBustStatus = true;
return `You drew a ${playerHand[playerHand.length - 1].name} of ${
playerHand[playerHand.length - 1].suit
}! You BUSTED at💣${playerScore}💣!<br><br> The Computer will now take it's turn!<br> ${outputMessageForCPU()} Click Submit to proceed! `;
}
return `${outputMessage()}`;
}
function checkEndGameScenario() {
if (playerBustStatus && computerBustStatus) {
return `Both players have 💣BUSTED💣! It is a draw!<br>You scored ${playerScore}!<br> The Computer scored ${computerScore}!<br>Click Submit to head to the scoreboard!`;
} else if (!playerBustStatus && computerBustStatus) {
playerWonTimes += 1;
return `You won!<br> You scored ${playerScore}!<br>The Computer scored 💣💣${computerScore}💣💣!<br>Click Submit to head to the scoreboard!`;
} else if (playerBustStatus && !computerBustStatus) {
computerWonTimes += 1;
return `The Computer won!<br> You scored 💣💣${playerScore}💣💣!<br>The Computer scored ${computerScore}!<br>Click Submit to head to the scoreboard!`;
} else if (playerScore === computerScore) {
return `Both players have scored ${playerScore}!<br> It is a draw!<br> Click Submit to head to the scoreboard!`;
} else if (playerScore > computerScore) {
playerWonTimes += 1;
return `You won!<br> You scored ${playerScore}!<br>The Computer scored ${computerScore}! Click Submit to head to the scoreboard!`;
} else if (playerScore < computerScore) {
computerWonTimes += 1;
return `The Computer won!<br> You scored ${playerScore}!<br>The Computer scored ${computerScore}! Click Submit to head to the scoreboard! `;
} else {
return "THE RESULT LOGIC WENT WRONG";
}
}