Question

In: Computer Science

Making a blackjack game in javascript Create a function called createDeck() that will create an array...

Making a blackjack game in javascript

  • Create a function called createDeck() that will create an array of objects (52). Each object contains two properties: suit and value. The suit property will be either 'Hearts', 'Clubs', 'Diamonds', or 'Spades'. The value property will be either 'Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three' , or 'Two''.

    Note: We will probably want to store possible suits and values in separate arrays.
  • Create a function called shuffleDeck() that will randomly "shuffle" our deck of cards
  • We will create a Node application in repl.it that will listen for user input:
  • Create a function that will "draw" four cards (2 for the player and 2 for the computer). The function will choose these cards from our shuffled deck.
  • Display both sets of cards to the console.
  • Create a function to get the numeric card value to calculate the score of each hand
  • Create a function to calculate the score of all the cards in a hand (dealer or player). Hint: You may need two functions.
  • Create a function to "show status" which will be displaying the cards of both players (computer and player) and their score so far. Have the status to the player look like screen shot below:
  •   
  • Well, we need to give the player a chance to hit (get a new card) as many times as they want. We will add the checking for going over 21 and having the computer decide if it it should hit or stand in the next part. Use recursion

Solutions

Expert Solution

// BlackJack App

//Card Vars
let suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades'];
let values = ['Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight',
             'Seven', 'Six', 'Five', 'Four', 'Three', 'Two'];

//Dom Vars
let paragraph = document.getElementById('text-area');
let playerCardsParagraph = document.getElementById('player-cards');
let dealerCardsParagraph = document.getElementById('dealer-cards');
let playerScoreParagraph = document.getElementById('player-score');
let dealerScoreParagraph = document.getElementById('dealer-score');
let newGameButton = document.getElementById('new-game');
let hitButton = document.getElementById('hit');
let stayButton = document.getElementById('stay');
let winnerText = document.getElementById('winner');

//Game vars
let gameStarted = false,
    gameOver = false,
    gameWon = false,
    playerWon = false,
    dealerWon = false,
    dealerCards = [],
    playerCards = [],
    deck = [],
    playerScore = 0,
    dealerScore = 0;

//New Game Button
  newGameButton.addEventListener('click', function() {
    gameStarted = true;

    deck = createDeck();
    playerCards = [getNextCard(), getNextCard()];
    dealerCards = [getNextCard(), getNextCard()];

    paragraph.innerText = 'New Game Started';
    playerCardsParagraph.innerText = `${getCardString(playerCards[0])}
      ${getCardString(playerCards[1])}`;
    playerScoreParagraph.innerText = `Score: ${getScore(playerCards)}`;

    dealerCardsParagraph.innerText = `${getCardString(dealerCards[0])}
      ${getCardString(dealerCards[1])} `;
    dealerScoreParagraph.innerText = `Score: ${getScore(dealerCards)}`;
      
    hideNewGameButton();
  });

//Hit Button
  hitButton.addEventListener('click', function() {
    playerCards.push(getNextCard());
    playerCardsParagraph.innerText += `\n ${getCardString(playerCards[playerCards.length - 1])}`;
    playerScoreParagraph.innerText = `Score: ${getScore(playerCards)}`;
    dealerScoreParagraph.innerText = `Score: ${getScore(dealerCards)}`;
    gameOver = false;
    checkEndGame();
  });

//Stay Button
  stayButton.addEventListener('click', function() {
    gameOver = true;
    checkEndGame();
  });

//Show New Game Button
function showNewGameButton() {
  newGameButton.style.display = 'inline';
  hitButton.style.display = 'none';
  stayButton.style.display = 'none';
}

//Hide New Game Button
function hideNewGameButton() {
  newGameButton.style.display = 'none';
  hitButton.style.display = 'inline';
  stayButton.style.display = 'inline';
}

//Winner Text
function returnWinner(winner) {
  return winnerText.innerText = `${winner} Won`;
}

//Create the Deck
function createDeck() {
  let deck = [];
  for (let suitIdx = 0; suitIdx < suits.length; suitIdx++) {
    for (let valueIdx = 0; valueIdx < values.length; valueIdx++) {
      let card = {
        suit: suits[suitIdx],
        value: values[valueIdx]
      };
      deck.push(card);
    }
  }
  return deck;
}

//Get next card
function getNextCard() {
  let cardNum = Math.round(Math.random() * 51);
  return deck[cardNum];
}

//Convert Card obj to String
function getCardString(card) {
  return card.value + ' of ' + card.suit;
}

//Get Card Values
function getCardvalues(card) {
  switch(card.value) {
    case 'Ace':
      return 1;
      break;
    case 'Two':
      return 2;
      break;
    case 'Three':
      return 3;
      break;
    case 'Four':
      return 4;
      break;
    case 'Five':
      return 5;
      break;
    case 'Six':
      return 6;
      break;
    case 'Seven':
      return 7;
      break;
    case 'Eight':
      return 8;
      break;
    case 'Nine':
      return 9;
      break;
    default: 
      return 10;
      break;
  }
}

//Calculate Score
function getScore(cardArray) {
  let score = 0;
  let hasAce = false;
  for (let i = 0; i < cardArray.length; i++) {
    score += getCardvalues(cardArray[i]);
    if (cardArray[i].value === 'Ace') {
      hasAce = true;
    }
  }
  if (hasAce && score + 10 <= 21) {
    return score + 10;
  }
  return score;
}

//Update Score
function updateScore() {
  dealerScore = getScore(dealerCards);
  playerScore = getScore(playerCards);
}

function winner(winner) {
  gameOver = true;
  returnWinner(winner);
  showNewGameButton();
}

//Check for a Blackjack
function hasBlackjack() {
    gameOver = true;
    returnWinner('Player has a Blackjack');
    showNewGameButton();
}

//Check for End of Game
function checkEndGame() {
  updateScore(); 

  if (gameOver) {
    while(dealerScore < 17) {
      dealerCards.push(getNextCard());
      updateScore(); 
      dealerCardsParagraph.innerText += `\n ${getCardString(dealerCards[dealerCards.length - 1])}`;
      dealerScoreParagraph.innerText = `Score: ${getScore(dealerCards)}`;
    }
  }

  if (playerScore > 21) {
    dealerWon = true;
    winner('Dealer');
  }

  else if (dealerScore > 21) {
    playerWon = true;
    winner('Player');
  }

  else if (playerScore === dealerScore) {
    gameOver = true;
    returnWinner('No one');
    showNewGameButton();
  }

  else if (playerScore ===  21) {
    hasBlackjack();
  }

  else if (gameOver) {
    if (playerScore > dealerScore) {
      playerWon = true;
      winner('Player');
    }
    else {
      dealerWon = true;
      winner('Dealer');
    }
  }
}

Related Solutions

javascript BlackJack i made a blackjack game, the code is below //this method will return a...
javascript BlackJack i made a blackjack game, the code is below //this method will return a shuffled deck function shuffleDeck() { //this will store array fo 52 objects const decks = [] const suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades'] const values = ['Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two', 'One'] //run a loop till 52 times for (let i = 0; i < 52; i++) { //push a random item decks.push({ suit: suits[Math.floor(Math.random() *...
javascript BlackJack i made a blackjack game, the code is below //this method will return a...
javascript BlackJack i made a blackjack game, the code is below //this method will return a shuffled deck function shuffleDeck() { //this will store array fo 52 objects const decks = [] const suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades'] const values = ['Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two', 'One'] //run a loop till 52 times for (let i = 0; i < 52; i++) { //push a random item decks.push({ suit: suits[Math.floor(Math.random() *...
Write a function (in Javascript) called longestMorseCodeWords which takes in an array of strings. The output...
Write a function (in Javascript) called longestMorseCodeWords which takes in an array of strings. The output of longestMorseCodeWords should be an array of the strings that were passed in, but ordered by the length of their Morse Code equivalent in descending order. If the length of Morse Code is equal, order the words alphabetically.For convenience, the full table for the 26 letters of the English alphabet is given below: [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] let words = ["gin", "zen", "gig", "msg"] longestMorseCodeWords(words) The Morse...
Write an Html Page that uses JavaScript Program to make a Blackjack Game. I need to...
Write an Html Page that uses JavaScript Program to make a Blackjack Game. I need to write an html file (P5.html) that uses JavaScript program to create a Blackjack game. 1. Blackjack Games Rules: a. The object of the game is to "beat the dealer", which can be done in a number of ways: • Get 21 points on your first two cards (called a blackjack), without a dealer blackjack; • Reach a final score higher than the dealer without...
array • First, create a function called addNumber, which has a formal parameter for an array...
array • First, create a function called addNumber, which has a formal parameter for an array of integers and increase the value of each array element by a random integer number between 1 to 10. o Add any other formal parameters that are needed. • Second, create another function called printReverse that prints this array in reverse order. • Then, you need to write a C++ program to test the use of these two functions.
JAVASCRIPT: Please create an array of student names and another array of student grades. - Create...
JAVASCRIPT: Please create an array of student names and another array of student grades. - Create a function that can put a name and a grade to the arrays. - Keep Read student name and grade until student name is “???”. And save the reading by using a function - Create another function to show all the grade in that object. - Create the third function that can display the maximum grade and the student’s name. - Create a sorting...
Write a javascript code to Create a function called Hotel that takes Room no, Customer name....
Write a javascript code to Create a function called Hotel that takes Room no, Customer name. amount paid. Write a code to call hotel function for each customer and display details of customers lodging in rooms with even room numbers. I need only js and html code. no css pls take screenshot of output , else I might dislike thanks
<HTML JAVASCRIPT> Please create an array of student names and another array of student grades. Create...
<HTML JAVASCRIPT> Please create an array of student names and another array of student grades. Create a function that can put a name and a grade to the arrays. Keep Read student name and grade until student name is “???”. And save the reading by using a function Create another function to show all the grade in that object. Create the third function that can display the maximum grade and the student’s name. Create a sorting function that can sort...
How to do a blackjack game with the following rules and WITHOUT USING ARRAY Part 1...
How to do a blackjack game with the following rules and WITHOUT USING ARRAY Part 1 – Displaying Cards Write a function to display (print) a card. sample program output void displayCard(int card) Prints the name of the card (ten of spades, queen of diamonds etc.). The parameter should be a value between 1 and 13, from which the type of card can be determined (1 = ace, 2 = two, …, 10, == ten, 11 = jack, 12 =...
Mini JAVASCRIPT Algorithm Exercise "Sum All In Array" Objectives Create a function that adds all numbers...
Mini JAVASCRIPT Algorithm Exercise "Sum All In Array" Objectives Create a function that adds all numbers of a provided array (arr), accounting for non-integer values in arr. The output should return an integer. Notes Remember your data types? If the element is an integer (8), it should be added. If the element is a string with a number value ("8"), it should be added. If the element is not a number, or if it is a string with a non-number...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT