What is the best way to display the outcome of shuffling a deck of blackjack cards?

Looking to improve my blackjack game, I've implemented a card shuffle function. However, I'm struggling with getting the shuffled card results to display in the innerText after clicking the new game button.

Despite reviewing and fine-tuning the code, checking variable placement and semicolons, the issue persists without any visible effect.

/*
  Custom Blackjack Game
*/

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

//DOM Variables
let textArea = document.getElementById('text-area'),
  newGameButton = document.getElementById('new-game-button'),
  hitButton = document.getElementById('hit-button'),
  stayButton = document.getElementById('stay-button');

//Game Variables
let gameStarted = false,
  gameOver = false,
  playerWon = 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;

  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() { //Create a deck of 52 cards
  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;
  }
}

function getCardString(card) {
  return card.value + ' of ' + card.suit;
}

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

function showStatus() {
  if (!gameStarted) {
    textArea.innerText = 'Welcome to Blackjack!';
    return;
  }
}

for (var i = 0; i < deck.length; i++) {
  textArea.innerText = "\n" + getCardString(deck[i]);
}
<h1 id="title">Welcome to Blackjack!</h1>
<h4>by Andrean Hendy</h4>

<p id="text-area">Welcome to Blackjack!</p>
<button id="new-game-button">New Game!</button>
<button id="hit-button">Hit!</button>
<button id="stay-button">Stay</button>

Check out the code on plunkr: http://embed.plnkr.co/rAzcbmTyH8vIRBI3appX/

The expectation is to display the shuffled result of the 52-deck card after shuffling.

Answer №1

Within the event listener for the "new-game-button" button, you are not updating the innerText of the "text-area". Currently, the only method that could potentially update it is showStatus, but the if(!gameStarted) condition prevents this from happening.

It seems like there may be a misunderstanding in your logic, but making the following update will display the result after clicking on the "New game" button:

newGameButton.addEventListener('click', function(){
  // ...
  setDeckText();
});

// ...

function setDeckText() {
  for(var i = 0; i < deck.length; i++){
    textArea.innerText = "\n" + getCardString(deck[i]);
  }
}

Answer №2

Issue resolved! Moving forward, the loop on the final lines needs to be included within the showStatus() function block, which I neglected to do previously.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method for obtaining the link URL using JavaScript?

Below is the code I am currently working with: <?php $i = 0; foreach($this->list as $l) { $link = JRoute::_("index.php?option=com_ecommerce&view=detail&id=$l->id"); <div class="quickview" id="quickview_<?php echo $i;?>"> < ...

The presentation of my HTML file is not being maintained in the output text file generated by HTML/JS

After clicking the save button to output my form data to a file, I noticed that the saved file has no formatting at all. https://i.sstatic.net/fbqJI.png https://i.sstatic.net/ZcnP0.png I'm encountering an issue where the saved log file lacks any for ...

Incorporating lazy loading for diverse content to enhance pagination

I'm currently using jpaginate for pagination on a large dataset, but I've noticed that all the content loads at once. Is there a jQuery plugin available that will only load the content for the current page? ...

JavaScript function containing a jQuery post operation

Consider this code snippet: function verifyDuplicate(value, colname) { var invoiceLineId = $('tr[editable="1"]').attr('id'); var invoiceLine = { InvoiceLineId: invoiceLineId, ...

Utilizing the OrientDB HTTP API within an Angular platform - a comprehensive guide

When trying to query OrientDB from an Angular service method, authentication-related errors are encountered. It appears that two GET requests are required for successful querying of OrientDB. An Authentication call: Requesting http://localhost:2480/conne ...

When using NextJS components, they function properly in development mode but encounter issues in production mode

I have encountered a problem with the 'Highlight' component from the 'react-highlight' library while working on a project using NextJS in both development and production modes. During development mode, the component appears as expected ...

Using TypeScript and webpack 2 to integrate typeahead.js into your project

I am encountering an error message coming from webpack. ERROR in ./wwwroot/js/admin/infrastructure/typeaheadComponent.ts Module not found: Error: Can't resolve 'typeahead' in ... I have the following dependencies installed npm install ...

Have you considered utilizing "call for('express')()" instead?

When creating a simple Web server with NodeJS and Express, most tutorials provide examples like the following: const express = require('express'); const app = express(); app.listen(3000, () => console.log("Started")) app.get(' ...

Utilizing vanilla JavaScript to sort selected checkboxes into a JSON object

I've been trying to implement a difficulty filter based on checked checkboxes, but despite my ongoing search for solutions, I haven't been able to find any promising results or clear directions. Exploration I came across a code snippet that see ...

Breaking down a number using JavaScript

Similar Question: JavaScript Method for Separating Thousands I'm looking to find a way to separate numbers by a thousand using JavaScript. For example, I would like to turn "1243234" into "1 243 234", or "1000" into "1 000" and so on. (sorry for ...

Aligning event with angular (similar to the 'join()' function in threads)

I am searching for a straightforward equivalent to join() for threads in Angular. In my Controller: vehiclesService.getVehicles().then(function(sth){ $scope.vehicles = sth.data; $scope.isend();//this call is not ideal }); vehiclesService.getFitme ...

I'm facing some uncertainties with a couple of AngularJS code snippets

At my workplace, I am tasked with making modifications to an angularjs project. However, I find the code quite complex and challenging to fully comprehend: app.controller("complementsController", function($scope, $rootScope, $mdSidenav, $timeout, $localSt ...

Formik Alert: Update depth limit reached

Currently, I am working on an EDIT formik form that is displayed as a MODAL. The issue arises when the setState function is triggered with setState(true), causing the form to appear without any onClick event. Despite changing onClick={editStory} to onClick ...

Is it possible to create multiple text input components using the "each" function, and how can I update the state by combining all of them together?

I am looking to create a text-based word game where the length of each word changes with every level. Each letter will be placed in its own box, forming a matrix (e.g. 10 words, length: 10 => 10x10 matrix). How can I generate multiple text input compone ...

Reorganizing data with JSON using JavaScript

I have a JSON data that I am parsing with NodeJS and I need to restructure it into a different JSON format. The original JSON includes multiple "pages" objects within the "rows" object, each containing similar keys and values except for the "values" and "d ...

Launch a new pop-up window with a specific size to display the form

I need to implement functionality for a Submit button on my new form that passes parameters to another page and opens a new pop-up window sized to specific dimensions. I already have this working with a hyperlink, but now I need the same functionality fo ...

Issue encountered while declaring a constant in a React TypeScript component

Recently, I attempted to transform a search bar CSS control that was originally written in React JS which I found online into React TS. However, as I am relatively new to TypeScript, I am facing challenges when it comes to identifying what exactly is causi ...

Trouble Loading TypeScript Class in Cast Situation

I've encountered an issue with my TypeScript model while using it in a cast. The model does not load properly when the application is running, preventing me from accessing any functions within it. Model export class DataIDElement extends HTMLElement ...

Unable to load JavaScript file twice dynamically in Internet Explorer

I recently created this page where users can click on rows in a table to load data via an ajax request and dynamically generate a graph. While this functionality works smoothly in Chrome and Firefox, I'm experiencing issues with Internet Explorer 8. S ...

JavaScript is sending a variable to a .php file, which then returns data based on the variable. The information is displayed using JavaScript and AJAX, along with triggers set using the bind('input', function

Currently, I am attempting to create a form that automatically populates some input fields when there is a change. However, I am struggling to understand how to send the #url field to my PHP script. Any insights or suggestions would be greatly appreciated. ...