From 4a0dc8d15f1b1db35fa34cc46d19e39ed4750412 Mon Sep 17 00:00:00 2001 From: Jonathan Vitale <jvitale@une.edu.au> Date: Thu, 1 Dec 2022 14:10:13 +1100 Subject: [PATCH] Add code for tutorial 5 --- game-logic.js | 60 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 53 insertions(+), 7 deletions(-) diff --git a/game-logic.js b/game-logic.js index c074d3d..9679bbd 100644 --- a/game-logic.js +++ b/game-logic.js @@ -1,7 +1,8 @@ const gameState = { playerWallet: 100, currentBet: null, - cards: [[], []] + cards: [[], []], + hiddenCard: null } function collectBet(){ @@ -31,24 +32,52 @@ function drawCard(){ return rndNum; } +function handValue(cards){ + let sum = 0; + let aces = 0; + for (let i = 0; i < cards.length; i++){ + sum = sum + cards[i]; + if (cards[i] == 11){ + aces++; + } + } + while (sum > 21 && aces > 0){ + sum = sum - 10; + aces--; + } + + return sum; +} + function blackjack(){ // decide the bet, collect it gameState.currentBet = collectBet(); + // we deal the first 2 cards for the player + // we deal the first 2 cards for the dealer + // one is hidden for(let playerIndex = 0; playerIndex < gameState.cards.length; playerIndex++){ for(let cardIndex = 0; cardIndex < 2; cardIndex++){ - gameState.cards[playerIndex][cardIndex] = drawCard(); + if (cardIndex === 1 && playerIndex === 1){ + gameState.hiddenCard = drawCard(); + } else { + gameState.cards[playerIndex][cardIndex] = drawCard(); + } } } - console.log(gameState.cards); + let curPlayerScore = handValue(gameState.cards[0]); + let curDealerScore = handValue(gameState.cards[1]); + + console.log(`Player score is ${curPlayerScore}, Dealer score is ${curDealerScore}`); - // we deal the first 2 cards for the player // check immediately that the player has blackjack // if so, we need to pay 2.5 the bet -> end the game - - // we deal the first 2 cards for the dealer - // one is hidden + if (curPlayerScore === 21){ + console.log('Player has blackjack!'); + gameState.playerWallet += gameState.currentBet*2.5; + return true; + } // REPEAT THIS ------ // player makes a choice: hit or stand @@ -58,6 +87,23 @@ function blackjack(){ // if new score > 21 player loses -> end the game // --- UNTIL THE PLAYER stands + while(curPlayerScore < 21){ + let threshold = (21 - curPlayerScore) / 21; + let likelihood = Math.random(); + if (likelihood < threshold){ + console.log('Player hitting a new card'); + let curCard = drawCard(); + gameState.cards[0].push(curCard); + curPlayerScore = handValue(gameState.cards[0]); + console.log(`Player got ${curCard} and the current score is ${curPlayerScore}`); + } else { + console.log('Player is not taking any more card'); + break; + } + } + + console.log(gameState.cards[0]); + // show the hidden card of the dealer // REPEAT THIS ----- // If dealer has less than 17 -- GitLab