Tips for managing player rounds updates

How can I make the number of rounds increase by 1 every time a card is clicked, rather than jumping to 4 and staying there? The initial value is set at 'let rounds = 0;' in my code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="index.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=BioRhyme:wght@800&display=swap" rel="stylesheet">
    <title>Card Game</title>
</head>
<body>
    <h1>Card Game</h1> 
    <p>Choose a card and get a random point. <br> First player to get 20 points in the least amount of rounds wins</p>
    
<div class="scoreboard">
    <div class="user-score">Points: 0</div>
    <button>Play Again</button>
    <div class="winner"></div>
    <div class="computer-score">Points: 0</div>
    <div class="rounds">Rounds: 0</div>
</div>

<div class="cards"> 
    <div class="card1">
        <div class="button">
            <img class="card1" src="bluecard.png" height=250px width=250px>
            <div class="overlay1"></div>
        </div>
    </div>
    
    <div class="card2">
        <div class="button">
            <img class="card2" src="bluecard.png" height=250px width=250px>
            <div class="overlay2"></div>
        </div>
    </div>
    
    <div class="card3">
        <div class="button">
            <img class="card3" src="bluecard.png" height=250px width=250px>
            <div class="overlay3"></div>
        </div>
    </div>

    <div class="card4">
        <div class="button">
            <img class="card4" src="bluecard.png" height=250px width=250px>
            <div class="overlay4"></div>
        </div>
    </div>
</div>

<div class="numbers">
    <div class="user-numbers">Your numbers: </div>
    <div class="computer-numbers">My numbers: </div>
</div>

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

</html>

// Global variables
const btn = document.querySelectorAll(".button");
const userScore = document.querySelector(".user-score");
const computerScore = document.querySelector(".computer-score");
const userChoice = document.querySelector(".user-choice");
const computerChoice = document.querySelector(".computer-choice");
const userNumbers = document.querySelector(".user-numbers");
const computerNumbers = document.querySelector(".computer-numbers");
const winner_div = document.querySelector(".winner"); 
const rounds_div = document.querySelector(".rounds"); 
const buttonAppear = document.querySelector(".button"); 

// Initialize variables to 0
let total = 0; 
let totalc = 0;
let usertotal = 0;  
let computertotal = 0;
let ranNum = 0;
let ranNumC = 0;
let rounds = 0;
const userArray = [];
const computerArray = [];

btn.forEach(function(button){
    button.addEventListener('click', usergetNumber);
    rounds++
    rounds_div.innerHTML = "Rounds: " + rounds;
});

// Run a randomized number from 1-10 whenever user clicks a button and add it 
// to the previous number and display the new total
function usergetNumber(){
    const ranNum = Math.floor(Math.random() * 10)
    usertotal = parseInt(total += ranNum);
    userNumbers.innerHTML = "Your numbers: " + ranNum;

    userArray.push(" " + ranNum);
    userNumbers.innerHTML = "Your numbers: " + userArray;
    
    userScore.innerHTML = "Your total: " + usertotal;
    computergetNumber();
    checkWinner();
};

function computergetNumber(){
    const ranNumC = Math.floor(Math.random() * 10)
    computertotal = parseInt(totalc += ranNumC);
    computerNumbers.innerHTML =  "My numbers:" + " " + ranNumC; 

    computerArray.push(" " + ranNumC);
    computerNumbers.innerHTML = "My numbers: " + computerArray;
    
    computerScore.innerHTML = "My total: " + computertotal;
    
}

function checkWinner(){
    if(usertotal === 20) {
        winner_div.innerHTML = "YOU WIN!"   
    }
    else if(usertotal > 20) {
        winner_div.innerHTML = "Too high!"   
    }
    else{
        winner_div.innerHTML = ""   
    }
};

Answer №1

Within this snippet of code:

btn.forEach(function(button){
    button.addEventListener('click', usergetNumber);
    rounds++
    rounds_div.innerHTML = "Rounds: " + rounds;
});

The value of rounds is calculated based on the number of elements with the ‘button’ class that are clicked. I suggest removing rounds++ and

rounds_div.innerHTML = "Rounds: " + rounds;
from the above block and incorporating them into the usergetNumber function instead.

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

Learning to extract URL parameters in ReactJS is a valuable skill

I am facing an issue with my React components - App and Contact. I need to display the ID on the contacts page that is passed through the route. However, when I use console.log(this.props) in the Contact component, it returns an empty object. import React ...

What is the best way to ensure that all of my images are the same size?

I've been working on making my pictures of varying resolutions the same size here, but no matter what I try, it just doesn't seem to work. Here is what I'm getting: . When I change the state to 1, 2, 3, or 4, I want it to look like this: her ...

The charAt function in a basic JavaScript if statement is failing to execute

When a user inputs a number that does not start with 6 or 9, an error occurs: console.log($(this).val().charAt(0)); if($(this).val().charAt(0) != 6 || $(this).val().charAt(0) != 9){ x=false; }else { x=true; } The console.log function corre ...

Managing extensive amounts of data with server-side scripting in a Datatable

I am exploring the use of the datatable plugin to effectively manage a large amount of data. Currently, I am interested in implementing "server side processing in datatables" with the help of server-side scripting. Since I have limited experience with AJA ...

How is it possible for TypeScript to enable the importing of dependencies that it ultimately cannot utilize during runtime?

Take a look at my sample project by following this link: https://github.com/DanKaplanSES/typescript-stub-examples/tree/JavaScript-import-invalid I have developed a file named main.ts: import uuid from "uuid"; console.log(uuid.v4()); While type ...

Delete all offspring nodes from the Google organization chart

I am currently utilizing the Google Organization Chart to create a chart that resembles the attached screenshot. There is a specific method called removeRow(nodeIndex) that I am using to eliminate a node from the chart. However, one issue I faced is that ...

Iterating through the startPrivateConversation method in Botkit for a multitude of users

In order to send an update to all my users, I created a new bot controller in a separate js file. To achieve this successfully, I needed to implement a notification function inside the controller's rtm_open function. The goal was to iterate through th ...

Troubleshooting MODULE NOT FOUND Error in my First NodeJS Application: A guide to resolving common issues

Welcome to My NodeJS Learning Project! Embarking on my first NodeJS application journey, this project serves as a stepping stone for me to grasp the fundamentals. The goal is to create a basic CRUD web app for item management. Drawing from my experience i ...

Having trouble with Wookmark not working in Jquery UI?

Hey there, just wanted to share that I'm currently utilizing the Wookmark jQuery plugin $.post('get_category',data={type:'All'},function(data) { $.each(data,function(item,i){ var image_ ...

Issue with popup display in React Big Calendar

I'm currently working on a calendar project using React-Big-Calendar, but I've run into an issue with the popup feature not functioning properly. <div className={styles.calendarContainer} style={{ height: "700px" }}> <C ...

Using type annotations is restricted to TypeScript files only, as indicated by error code ts(8010)

I encountered an issue with React.MouseEvent<HTMLElement> const handleOpenNavMenu = (event: React.MouseEvent<HTMLElement>) => { setAnchorElNav(event.currentTarget); }; const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement ...

Exploring the isolated scopes of AngularJS directives

Exploring directives in AngularJS led me to this interesting code snippet: var app = angular.module('app', []); //custom directive creation app.directive("myDir", function () { return { restrict: "E", scope: { title: '@ ...

What is the best way to assign or convert an object of one type to another specific type?

So here's the scenario: I have an object of type 'any' and I want to assign it an object of type 'myResponse' as shown below. public obj: any; public set Result() { obj = myResponse; } Now, in another function ...

Populate modal form with database information without using Bootstrap

As I work on populating a form with data from an sqlite database, I've come across a stumbling block. My code is available for reference on JSFiddle: https://jsfiddle.net/daikini/e71mvg7n/ One important note: Bootstrap isn't being utilized in t ...

Highlight particular terms (key phrases) within text contained in a <td> tag

I am currently working on a project and facing a challenge that I am unfamiliar with. My task is to highlight specific keywords within text located inside a <td> element. I cannot manually highlight the keywords as the texts are dynamic, originating ...

An issue has arisen: It seems that properties of null cannot be accessed, particularly the 'toISOString' property

After upgrading the dependencies in my package.json to their latest versions, I encountered an error while accessing a page that calls this data. Given that the dependencies were outdated by at least 2 years or more, I suspect the issue lies with the updat ...

Is there a way to determine if jQuery Mobile has already been loaded?

I am dynamically loading jqm and I'm trying to determine if it has been previously loaded in certain scenarios. Is there a method to check for the presence of jqm? ...

Toggling checkboxes using Angular framework

Within my form, there is a table with checkboxes in each column. The table consists of 3 <tr> elements, and each <tr> uses ng-repeate to call the webservice and display clone data (in JSON format). Upon clicking a checkbox, I create a JavaScrip ...

Creating a table in HTML using the innerHTML property

document.getElementById("outputDiv").innerHTML = ""; document.getElementById("outputDiv").innerHTML += "<table border=1 width=100%><tr>"; for(j=1;j<=10;j++) { document.getElementById("outputDiv").innerHTML += "<td align=center>"+St ...

Select a single radio button containing values that can change dynamically

<input type="radio" on-click="checkDefaultLanguage" id="checkbox" > [[names(name)]] This custom radio input field contains dynamic values and I am attempting to create a functionality where only one radio button can be selected at a time while dese ...