Skip to content
Advertisement

BlackJack game in JavaScript

I was given this challenge for an interview process and I have been trying to solve it correctly. On the console, the function returns undefined and sometimes just runs until (samPoints += getRandomCard()); Would you help me identify what I am doing wrong?

These are the instructions:

Model the game create a single deck of playing cards two players (called Sam and the Dealer) who will play against each other each player is given two cards from the top of a shuffled deck of cards Rules to implement determine score of a hand[1] check if either player has blackjack (21) with their initial hand and wins the game if neither player has blackjack then Sam can start drawing cards from the top of the deck Sam should stop drawing cards from the deck if their total reaches 17 or higher Sam has lost the game if their total is higher than 21 when Sam has stopped drawing cards the Dealer can start drawing cards from the top of the deck the Dealer should stop drawing cards when their total is higher than Sam. the Dealer has lost the game if their total is higher than 21 determine which player wins the game [1] Numbered cards are their point value. Jack, Queen and King count as 10 and Ace counts as 11.

And this is my code:

const cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11];
const deckOfCards = [...cards, ...cards, ...cards, ...cards];

let samPoints = 0;
let dealerPoints = 0;

function getRandomCard() {
  const randomCard = Math.floor(Math.random() * 52);
  const pickedCard = deckOfCards.splice(randomCard, 1)[0];
  return pickedCard;
}

samPoints += getRandomCard();
samPoints += getRandomCard();

dealerPoints += getRandomCard();
dealerPoints += getRandomCard();

console.log(samPoints);
console.log(dealerPoints);

function checkBlackjack() {
  if (samPoints === 21) {
    console.log("Sam wins!");
  } else if (dealerPoints === 21) {
    console.log("Dealer wins");
  } else if (samPoints === 21 && dealerPoints === 21) {
    console.log("Its a draw");
  } else if (samPoints <= 17) {
    while (samPoints <= 17) {
      return (samPoints += getRandomCard());
    }
    if (samPoints > 21) {
      console.log("Dealer wins. Game over");
    } else if (samPoints >= 17) {
      while (dealerPoints > samPoints) {
        return (dealerPoints += getRandomCard());
      }
      if (dealerPoints > 21) {
        console.log("Sam wins. Game over");
      }
    }
  }
}
console.log(checkBlackjack());

Advertisement

Answer

One problem i see, is that you are randomly selecting one of the 52 cards, but after each selection, you remove the card from the deck. So next selection should be among 51 cards and next among 50 etc.. (not 52 every time)

So you should change the

const randomCard = Math.floor(Math.random() * 52);

to

const randomCard = Math.floor(Math.random() * deckOfCards.length);
Advertisement