Question

In: Computer Science

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() * suits.length)], value: values[Math.floor(Math.random() * values.length)] })

}

return decks

}

//function that will draw four cards form the deck

function draw(decks) {

return {

player: [decks[0], decks[1]],

computer: [decks[2], decks[3]]

}

}

//first shuffle the deck

const shuffled = shuffleDeck()

console.log((shuffled))

//now draw the card

const drawn = draw(shuffled)

console.log("\n\nDrawn Cards :" ,(drawn))

i want to make a node application that will listen for user input. this is what i have so far for it.

function startGame () {
let input;
input = prompt("Welcome to Blackjack. Do you want to play? (Y)es or (N)o").toUpperCase();
if (input == 'Y') {}
}

i am stuck on how to finish the startGame Function.

Solutions

Expert Solution

Simple HTML Code for the front page and th Buttons:-

<!DOCTYPE html>

<html>

  <head>

    <link rel="stylesheet" href="style.css">

  </head>

  <body>

    <h1>WELCOME TO BLACKJACK</h1>

    <h4>DO YOU WANT TO PLAY?</h4>

    <p id="text-area">Welcome to Blackjack!</p>

    <button id="new-game-button">Start Game!</button>

    <button id="hit-button">Hit!</button>

    <button id="stay-button">Stay</button>

    

    <script src="script.js"></script>

  </body>

</html>

Javascript Code to connect and run the Game:-

let suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades'];

let values = ['Ace', 'King', 'Queen', 'Jack',

  'Ten', 'Nine', 'Eight', 'Seven', 'Six',

  'Five', 'Four', 'Three', 'Two', 'One'

];

let textArea = document.getElementById('text-area');

let newGameButton = document.getElementById('new-game-button');

let hitButton = document.getElementById('hit-button');

let stayButton = document.getElementById('stay-button');

hitButton.style.display = 'none';

stayButton.style.display = 'none';

let gameStart = false,

  gameOver = false,

  playWon = false,

  dealerCards = [],

  playerCards = [],

  dealerScore = 0,

  playerScore = 0,

  deck = [];

newGameButton.addEventListener('click', function() {

  gameStarted = true;

  gameOver = false;

  playerWon = false;

  deck = createDeck();

  shuffleDeck(deck);

  dealerCards = [getNextCard(), getNextCard()];

  playerCards = [getNextCard(), getNextCard()];

  newGameButton.style.display = 'none';

  hitButton.style.display = 'inline';

  stayButton.style.display = 'inline';

  showStatus();

})

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;

}

function shuffleDeck(deck){

  for(let i=0; i<deck.length; i++)

  {

    let swapIdx = Math.trunc(Math.random() *deck.length);

    let tmp = deck[swapIdx];

    deck[swapIdx] = deck[i];

    deck[i] = tmp;

  }

}

hitButton.addEventListener('click', function(){

  playerCards.push(getNextCard());

  checkForEndOfGame();

  showStatus();

});

stayButton.addEventListener('click', function(){

  gameOver = true;

  checkForEndOfGame();

  showStatus();

});

function checkForEndOfGame(){

  updateScores();

  

  if(gameOver){

    while(dealerScore<playerScore &&

          playerScore <=21 &&

          dealerScore <=21){

            dealerCards.push(getNextCard());

            updateScores();

    }

  }

    

    if(playerScore>21){

      playerWon=false;

      gameOver = true;

    }

    

    else if(dealerScore>21){

      playerWon = true;

      gameOver = true;

    }

    

    else if(gameOver){

      if(playerScore>dealerScore){

        playerWon = true;

      }

      else{

        playerWon = false;

      }

    }

}

function getCardString(card) {

  return card.value + " of " + card.suit;

}

function getCardNumericValue(card){

  switch(card.value){

    case 'Ace':

      return 1;

    case 'Two':

      return 2;

    case 'Three':

      return 3;

    case 'Four':

      return 4;

    case 'Five':

      return 5;

    case 'Six':

      return 6;

    case 'Seven':

      return 7;

    case 'Eight':

      return 8;

    case 'Nine':

      return 9;

    default:

      return 10;

  }

}

function showStatus()

{

  if(!gameStarted)

  {

    textArea.innerText = 'Welcome to Blackjack!';

    return;

  }

  

  let dealerCardString = '';

  for(let i=0; i<dealerCards.length; i++)

  {

    dealerCardString += getCardString(dealerCards[i]) + '\n';

  }

  let playerCardString='';

  for(let i=0; i<playerCards.length; i++)

  {

    playerCardString += getCardString(playerCards[i]) + '\n';

  }

  

  updateScores();

  

  textArea.innerText = 'Dealer has:\n' +

                        dealerCardString +

                        '(score: ' + dealerScore + ')\n\n' +

                        

                        'Player has:\n' +

                        playerCardString +

                        '(score: ' + playerScore + ')\n\n';

                        

  if(gameOver){

    if(playerWon)

    {

      textArea.innerText += "YOU WIN!";

    }

    else{

      textArea.innerText += "DEALER WINS";

    }

    newGameButton.style.display = 'inline';

    hitButton.style.display = 'none';

    stayButton.style.display = 'none';

    

  }

}

function getScore(cardArray){

  let score = 0;

  let hasAce = false;

  for(let i=0; i<cardArray.length; i++){

    let card = cardArray[i];

    score += getCardNumericValue(card);

    if(card.value == 'Ace'){

      hasAce = true;

    }

    

    if(hasAce && score+10<=21){

      return score+10;

    }

  }

   return score;

}

function updateScores(){

  dealerScore = getScore(dealerCards);

  playerScore = getScore(playerCards);

}


function getNextCard() {

  return deck.shift();

}

Summary:-Run the code mentioned above and your Blackjack Game will be ready.You can style the Game according to your need so didnot provide the CSS part.


Related Solutions

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...
Write the below code to use HTML and JavaScript. 1. a) Write a JavaScript program to...
Write the below code to use HTML and JavaScript. 1. a) Write a JavaScript program to display the current day and time. b) Write a JavaScript program to print the contents of the current window.   c) Write a JavaScript program where the program takes a random integer between 1 to 10 d) Write a JavaScript program to calculate multiplication and division of two numbers (input from the user). e)Write a JavaScript program to create a new string from a given...
Please take the code below and add some javascript to it. Please use javascript inline. Please...
Please take the code below and add some javascript to it. Please use javascript inline. Please be sure to specify within the webpage with something like 'Click here' too show what was done and how to activate it. Please post in a format that can be directly copied. Thank you in advance HINT: add some fun widgets to the page index-css.html: <!DOCTYPE html> <html lang="en"> <head> <!-- title for web page --> <title>Index-CSS Page</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1">...
//Trying to get this code with JavaScript. I could partition the subarrays, but I don't know...
//Trying to get this code with JavaScript. I could partition the subarrays, but I don't know how to check for unique elements Given an array of integers check if it is possible to partition the array into some number of subsequences of length k each, such that: Each element in the array occurs in exactly one subsequence For each subsequence, all numbers are distinct. Elements in the array having the same value must be in different subsequences If it is...
i need code in javascript or htmlt convert 0 to 999 numbers into word
i need code in javascript or htmlt convert 0 to 999 numbers into word
Java: Simple 21 Game (Blackjack) In this game, the dealer deals two "cards" to each player,...
Java: Simple 21 Game (Blackjack) In this game, the dealer deals two "cards" to each player, one hidden, so that only the player who gets it knows what it is, and one face up, so that everyone can see it. There are four players: one human player (user) and three computer players. The players take turns requesting cards, trying to get as close to 21 as possible, but not going over 21. A player may pass. Once a player has...
Blackjack, or 21, is a popular casino game that begins with each player and the dealer...
Blackjack, or 21, is a popular casino game that begins with each player and the dealer being dealt two cards. The value of each hand is determined by the point total of the cards in the hand. Face cards and 10s count 10 points, aces can be counted as either 1 or 11 points, and all other cards count at their face value. For instance, the value of a hand consisting of a jack and an 8 is 18; the...
In the game of blackjack, the cards 2 through 10 are counted at their face values,...
In the game of blackjack, the cards 2 through 10 are counted at their face values, regardless of suit; all face cards (jack, queen, and king) are counted as 10; and an ace is counted as a 1 or 11, depending on the total count of all cards in a player’s hand. The ace is counted as 11 only if the resulting total value of all cards in a player’s hand doesn’t exceed 21; otherwise, it’s counted as 1. Using...
(General math) In the game of blackjack, the cards 2 through 10 are counted at their...
(General math) In the game of blackjack, the cards 2 through 10 are counted at their face values, regardless of suit; all face cards (jack, queen, and king) are counted as 10; and an ace is counted as a 1 or an 11, depending on the total count of all cards in a player’s hand. The ace is counted as 11 only if the resulting total value of all cards in a player’s hand doesn’t exceed 21; otherwise, it’s counted...
Need to fix this code for tc -tac-toe game .. see the code below and fix...
Need to fix this code for tc -tac-toe game .. see the code below and fix it #include <iostream> using namespace std; void display_board(); void player_turn(); bool gameover (); char turn ; bool draw = false; char board [3][3] = { {'1', '2', '3'}, { '4', '5', '6'}, { '7', '8', '9'}}; int main() { cout << " Lets play Tc- Tac- toe game " <<endl ; cout << " Player 1 [X] ----- player 2 [0] " <<endl <<endl;...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT