Question

[JS] [HTML] wanting to add this logic to existing code(see below) of a blackjack game, where...

[JS] [HTML]

wanting to add this logic to existing code(see below) of a blackjack game, where it will show the Suit emblem instead of spelled out suit name. example: display 7 ♣ instead of 7 clubs.

//this is the logic, main obj is to display suits emblems to existing code

if (card.Suit == 'Hearts')

icon='♥';

else if (card.Suit == 'Spades')

icon = '♠';

else if (card.Suit == 'Diamonds')

icon = '♦';

else

icon = '♣';

//existing code blackjack.js


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

//DOM variables
let textArea= document.getElementById('text_area');
let newGameButton= document.getElementById('newGame_button');
let stayButton= document.getElementById('stay_button');
let hitButton= document.getElementById('hit_button');

//Game variables
let gameStarted = false,
gameOver= false,
playerWon= false,
push = false,
dealerCards = [],
playerCards = [],
dealerScore = 0,
playerScore = 0,
deck = [];


hitButton.style.display= 'none';
stayButton.style.display= 'none';
showStatus();


newGameButton.addEventListener('click',function() {
gameStarted = true;
gameOver = false;
playerWon = false;
push = false;

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

newGameButton.style.display='none';
hitButton.style.display='inline';
stayButton.style.display='inline';
showStatus();

});

hitButton.addEventListener('click', function() {
playerCards.push(getNextCard());
checkForEnd();
showStatus();
});

stayButton.addEventListener('click', function() {
gameOver = true;
checkForEnd();
showStatus();
});


function createDeck() {
let deck= [];
for (let i=0; i<suits.length; i++) {
for (let j=0; j<values.length; j++) {
let card = {
suit: suits[i],
value: values[j]
};
deck.push(card);
}
}
return deck;
}

function shuffleDeck(deck) {
for (let i=0; i<deck.length; i++) {
let swap= Math.trunc(Math.random() * deck.length);
let temp= deck[swap];
deck[swap] = deck[i];
deck[i]= temp;
}
}

function getCard(card) {
return card.value + " " + card.suit;
}

function getNextCard() {
return deck.shift();
}

//this function will determine an ace-9 and default jack,queen, king to 10
function getCardValue(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 'Eigth':
return 8;
case 'Nine':
return 9;
default:
return 10;
}
}

//this will get tally the scores by calling function getCardValue and adding to score
function getScore(cardArray) {
let score = 0;
let hasAce = false;
for (let i = 0; i <cardArray.length; i++) {
let card = cardArray[i];
score += getCardValue(card);
if (card.value === 'Ace') {
hasAce = true;
}
}
if (hasAce && score + 10 <= 21) {
return score + 10;
}
return score;
}

//this sets the scores for player and dealer variables
function updateScores() {
dealerScore = getScore(dealerCards);
playerScore = getScore(playerCards);
}

function checkForEnd() {
  
updateScores();
if(gameOver){
//Let Dealer take card
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( dealerScore === playerScore){
push= true;
gameOver=true;
}
else if(gameOver){
if(playerScore > dealerScore){
playerWon = true;
}
else {
playerWon = false;
}
}
}

function showStatus() {
if(!gameStarted){
textArea.innerText = "Play Blackjack";
return;
}

let dealerCard = '';
var el = document.createElement('div');
var icon = '';
for(let i = 0; i < dealerCards.length; i++){
dealerCard += getCard(dealerCards[i]) + '\n';

}

let playerCard = '';
for(let i = 0; i < playerCards.length; i++){
playerCard += getCard(playerCards[i]) + '\n';
  
}
//call function that sets the scores
updateScores();

textArea.innerText =
'Dealer has:\n' +
dealerCard + '(score: '+ dealerScore + ') \n\n' +

'Player has:\n' +
playerCard +
'(score: ' + playerScore + ')\n\n';

if (gameOver) {
if (playerWon) {
textArea.innerText += "YOU WIN!";
}
else if (push) {
textArea.innerText += "PUSH!!";
}
else {
textArea.innerText += "YOU LOSE";
}
newGameButton.style.display = 'inline';
hitButton.style.display = 'none';
stayButton.style.display = 'none';
}
}

//existing HTML file

<!DOCTYPE html>
<html lang="en">
<head>
<title>BlackJack </title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content=" A simple blackjack game">
</head>
<body>
  
<main>
  
<h1>Blackjack</h1>


<p id="text_area">Let's play blackjack</p>
<button id="newGame_button">New Game</button>
<button id="hit_button">Hit</button>
<button id="stay_button">Stay</button>
  
<script src="blackjack.js"></script>
</main>
</body>
</html>

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Note: Done accordingly. Please comment for any problem. Please Uprate. Thanks.

Updated code is highlighted. First we are returning icon from getCard method but it was string. To convert it in html form we have created a temp div then setting value to that and finally extracting data from that div.

Code:

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

//DOM variables
let textArea= document.getElementById('text_area');
let newGameButton= document.getElementById('newGame_button');
let stayButton= document.getElementById('stay_button');
let hitButton= document.getElementById('hit_button');

//Game variables
let gameStarted = false,
gameOver= false,
playerWon= false,
push = false,
dealerCards = [],
playerCards = [],
dealerScore = 0,
playerScore = 0,
deck = [];


hitButton.style.display= 'none';
stayButton.style.display= 'none';
showStatus();


newGameButton.addEventListener('click',function() {
gameStarted = true;
gameOver = false;
playerWon = false;
push = false;

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

newGameButton.style.display='none';
hitButton.style.display='inline';
stayButton.style.display='inline';
showStatus();

});

hitButton.addEventListener('click', function() {
playerCards.push(getNextCard());
checkForEnd();
showStatus();
});

stayButton.addEventListener('click', function() {
gameOver = true;
checkForEnd();
showStatus();
});


function createDeck() {
let deck= [];
for (let i=0; i<suits.length; i++) {
for (let j=0; j<values.length; j++) {
let card = {
suit: suits[i],
value: values[j]
};
deck.push(card);
}
}
return deck;
}

function shuffleDeck(deck) {
for (let i=0; i<deck.length; i++) {
let swap= Math.trunc(Math.random() * deck.length);
let temp= deck[swap];
deck[swap] = deck[i];
deck[i]= temp;
}
}


function getCard(card) {
   if (card.suit == 'Hearts')
       icon='&hearts;';
   else if (card.suit == 'Spades')
       icon = '&spades;';
   else if (card.suit == 'Diamonds')
       icon = '&diams;';
   else
       icon = '&clubs;';
   return card.value + " " + icon;

}

function getNextCard() {
return deck.shift();
}

//this function will determine an ace-9 and default jack,queen, king to 10
function getCardValue(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 'Eigth':
return 8;
case 'Nine':
return 9;
default:
return 10;
}
}

//this will get tally the scores by calling function getCardValue and adding to score
function getScore(cardArray) {
let score = 0;
let hasAce = false;
for (let i = 0; i <cardArray.length; i++) {
let card = cardArray[i];
score += getCardValue(card);
if (card.value === 'Ace') {
hasAce = true;
}
}
if (hasAce && score + 10 <= 21) {
return score + 10;
}
return score;
}

//this sets the scores for player and dealer variables
function updateScores() {
dealerScore = getScore(dealerCards);
playerScore = getScore(playerCards);
}

function checkForEnd() {
  
updateScores();
if(gameOver){
//Let Dealer take card
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( dealerScore === playerScore){
push= true;
gameOver=true;
}
else if(gameOver){
if(playerScore > dealerScore){
playerWon = true;
}
else {
playerWon = false;
}
}
}

function showStatus() {
if(!gameStarted){
textArea.innerText = "Play Blackjack";
return;
}

let dealerCard = '';
var el = document.createElement('div');
var icon = '';
for(let i = 0; i < dealerCards.length; i++){
   dealerCard += getCard(dealerCards[i]) + '\n';
}

let playerCard = '';
for(let i = 0; i < playerCards.length; i++){
   playerCard += getCard(playerCards[i]) + '\n';
}
//call function that sets the scores
updateScores();

var tempPlayer = document.createElement('div');
tempPlayer.innerHTML = playerCard;
var playerHtmlObject = tempPlayer.firstChild;

var tempDealer = document.createElement('div');
tempDealer.innerHTML = dealerCard;
var dealerHtmlObject = tempDealer.firstChild;


textArea.innerText =
'Dealer has:\n' +
dealerHtmlObject.textContent + '(score: '+ dealerScore + ') \n\n' +

'Player has:\n' +
playerHtmlObject.textContent +
'(score: ' + playerScore + ')\n\n';

if (gameOver) {
if (playerWon) {
textArea.innerText += "YOU WIN!";
}
else if (push) {
textArea.innerText += "PUSH!!";
}
else {
textArea.innerText += "YOU LOSE";
}
newGameButton.style.display = 'inline';
hitButton.style.display = 'none';
stayButton.style.display = 'none';
}
}

Output:

Add a comment
Know the answer?
Add Answer to:
[JS] [HTML] wanting to add this logic to existing code(see below) of a blackjack game, where...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import...

    Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class Project3 extends JFrame implements ActionListener { private static int winxpos = 0, winypos = 0; // place window here private JButton exitButton, hitButton, stayButton, dealButton, newGameButton; private CardList theDeck = null; private JPanel northPanel; private MyPanel centerPanel; private static JFrame myFrame = null; private CardList playerHand = new CardList(0); private CardList dealerHand = new CardList(0);...

  • HELP NEED!! Can some modified the program Below in C++ So that it can do what the Problem below asked it today???? #include <iostream> #include <stdlib.h> #include <string> #include...

    HELP NEED!! Can some modified the program Below in C++ So that it can do what the Problem below asked it today???? #include <iostream> #include <stdlib.h> #include <string> #include <time.h> /* time */ #include <sstream> // for ostringstream using namespace std; // PlayingCard class class PlayingCard{ int numRank; int numSuit; string rank; string suit; public: PlayingCard(); PlayingCard(int numRank,int numSuit); void setRankString(); void setSuitString(); void setRank(int numRank); void setSuit(int numSuit); string getRank(); string getSuit(); int getRankNum(); int getSuitNum(); string getCard(); };...

  • HELP NEED!! Can some modified the program Below in C++ So that it can do what...

    HELP NEED!! Can some modified the program Below in C++ So that it can do what the Problem below asked it today???? #include <iostream> #include <stdlib.h> #include <string> #include <time.h> /* time */ #include <sstream> // for ostringstream using namespace std; // PlayingCard class class PlayingCard{ int numRank; int numSuit; string rank; string suit; public: PlayingCard(); PlayingCard(int numRank,int numSuit); void setRankString(); void setSuitString(); void setRank(int numRank); void setSuit(int numSuit); string getRank(); string getSuit(); int getRankNum(); int getSuitNum(); string getCard(); };...

  • How do I start this c++ code homework? Write a code in C++ for a BlackJack...

    How do I start this c++ code homework? Write a code in C++ for a BlackJack card game using the following simplified rules: Each card has a numerical value. Numbered cards are counted at their face value (two counts as 2 points, three, 3 points, and so on) An Ace count as either 1 point or 11 points (whichever suits the player best) Jack, queen and king count 10 points each The player will compete against the computer which represents...

  • Given a starting sphere code, modify the Java and HTML code to create multiple spheres that...

    Given a starting sphere code, modify the Java and HTML code to create multiple spheres that will rotate in different positions at different speeds. basicSphere.js: "use strict"; var canvas; var gl; var numTimesToSubdivide = 3; var index = 0; var pointsArray = []; var va = vec4(0.0, 0.0, -1.0,1); var vb = vec4(0.0, 0.942809, 0.333333, 1); var vc = vec4(-0.816497, -0.471405, 0.333333, 1); var vd = vec4(0.816497, -0.471405, 0.333333,1); var program; var program1; function triangle(a, b, c) {    pointsArray.push(a);...

  • Add JavaScript code in the “find_primeV2.js” to allow users to enter a number, and then based...

    Add JavaScript code in the “find_primeV2.js” to allow users to enter a number, and then based on the number of user enters, to find out how many prime numbers there are up to and including the user inputted number and then display them on the web page. The following are the detailed steps to complete this assignment: Step 1. [30 points] In “find_primeV2.js”, complete isPrime() function by (1) Adding one parameter in function header. That parameter is used to accept...

  • Form Processing HTML One of the most ubiquitous uses of JavaScript is validating form data on...

    Form Processing HTML One of the most ubiquitous uses of JavaScript is validating form data on the client side before it is submitted to the server. It is done everywhere because it is fast and it gives you a great deal of flexibility in how you handle errors insofar as the GUI is concerned. Attached is an image of some code I wrote (so Blackboard can't mess it up). Some things to notice that will help you with the lab....

  • One example of computer-aided design (CAD) is building geometric structures inter- actively. In Chapter 4, we...

    One example of computer-aided design (CAD) is building geometric structures inter- actively. In Chapter 4, we will look at ways in which we can model geometric objects comprised of polygons. Here, we want to examine the interactive part. Let’s start by writing an application that will let the user specify a series of axis- aligned rectangles interactively. Each rectangle can be defined by two mouse positions at diagonally opposite corners. Consider the event listener canvas.addEventListener("mousedown", function() { gl.bindBuffer(gl.ARRAY_BUFFER, vBuffer); if...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT