Increase a value if two results are identical

In a game of chance, players choose between heads or tails while the computer makes a random selection. The outcome determines whether points are awarded to the player, the computer, or both. The first one to accumulate five points wins. However, there seems to be an issue with updating the points for 'thePlayersPoints' and 'theComputerPoints'. The desired functionality is for a point to be added when the values are equal, but currently, it only updates if the value is already displayed on the screen. This means that selecting heads and having it come up won't immediately add a point until heads is selected again.

//Btns
let btn = document.querySelectorAll('button')
let HeadsBtn = document.querySelector('.heads')
let TailsBtn = document.querySelector('.talis')
let output = document.querySelector('.output')

//Player
let PlayersChoice = document.querySelector('.PlayersChoice')
let ThePlayersPoints = document.querySelector('.ThePlayersPoints')
//computer
let ComputerChoice = document.querySelector('.ComputerChoice')
let TheComputersPoints = document.querySelector('.TheComputersPoints')
//winner
let winner = document.querySelector('.winner')
//headsAndTails
let player = 0
let computer = 0

// Function to determine the output.
let btnContaner = document.querySelector('.btnCon')
btnContaner.addEventListener('click', pinkingOne)
function pinkingOne(TheOutput){
    let random = Math.floor(Math.random() * 2)

    if(random  === 0){
        TheOutput = 'Tails'
    }else{
        TheOutput = 'Heads'
    }
  
    output.innerText = `${ TheOutput}`
}

// Adds Heads to player's selection.
HeadsBtn.addEventListener('click', function(){
    PlayersChoice.innerHTML  = 'Heads'
})

// Adds Tails to player's selection.
TailsBtn.addEventListener('click',function(pick){
   pick ='Tails' 
    PlayersChoice.innerHTML = `${pick}` 
})

// Computer randomly selects heads or tails.
btnContaner.addEventListener('click', computersPick)
function computersPick(pick){
    let random = Math.floor(Math.random() * 2)
    
    if(random === 1){
    pick = 'Heads'
    }else{
    pick = 'Tails'
    }
    ComputerChoice.innerText = `${pick}`
}

// Adding points for the player and computer based on selections.

HeadsBtn.addEventListener('click',function(){
     if(PlayersChoice.innerHTML === output.innerHTML){
         ThePlayersPoints.innerHTML++
     }else{
         if (ComputerChoice.innerHTML === output.innerHTML){
            TheComputersPoints.innerHTML++
         }
     }
 })

TailsBtn.addEventListener('click',function(){
    if(PlayersChoice.innerHTML === output.innerHTML){
        ThePlayersPoints.innerHTML++
    }else{
        if (ComputerChoice.innerHTML === output.innerHTML){
           TheComputersPoints.innerHTML++
        }
    }
})
//^^^^^^^adding the points to the player and computer ^^^^^^^^

// Determining the winner.
function andTheWinnerIs(){
    let Tbtn = document.querySelector('#Tails')
    let Hbtn = document.querySelector('#Heads')
    Tbtn.addEventListener('click',addforplayer)
    Hbtn.addEventListener('click',addforplayer)
    
    // Selecting the winner
    if (ThePlayersPoints.innerHTML == 5 && TheComputersPoints.innerHTML == 5){
        winner.innerHTML = `It's a Tie`;
    } else if (ThePlayersPoints.innerHTML == 5){
        winner.innerHTML = `You Win!!!`;
    } else if (TheComputersPoints.innerHTML == 5){
        winner.innerHTML = `Computer Wins!!!`;
    }

}

html{
    background-color:rgba(128, 128, 128, 0.712);
    margin:0;
    padding:0;
    top:0;

}
// Additional CSS styles...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Light Switching</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Kaushan+Script&display=swap');
        </style>
        <style>
            @import url('https://fonts.googleapis.com/css2?family=Quantico&display=swap');
            </style>
            <style>
                @import url('https://fonts.googleapis.com/css2?family=Staatliches&display=swap');
                </style>
</head>
<body>
    <center>
    <h1 class='H1'>First Player to 5 points wins!</h1>
<h3 class='PlayerSelected'>Player selected:</h3>
<div id='PlayersChoice' class='PlayersChoice'></div>
... // Remaining HTML code
</body>
</html>

Answer №1

Initially, it is important to note that you are currently assigning two separate 'click' event listeners to the buttons, which should ideally be combined into a single event listener.

Furthermore, in the second event listener, the conditions inside the if statement will only be evaluated if the player's choice does not match the computer's choice. To rectify this, consider removing the 'else' statement and having two distinct 'if' statements for each player's choice evaluation.

Additionally, there are two excess event listeners associated with the '.btnContainer' element. It would be more efficient to call those functions within a single button click event handler.

It is also recommended to disable the buttons after a game has been won and include a reset button functionality to initiate a new game session.

I trust that these modifications will enhance the functionality of your code. Please refer to the snippet below for the updated changes:

// Modified Code Snippet Here

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

"Troubleshooting a problem with a missing CSS background image

I have followed numerous tutorials, all of which provide the same instructions. I have specified my background within the body tag in my CSS style sheet, but for some reason, the page continues to display a blank white background. The image is located in t ...

A Step-by-Step Guide to Mocking a jQuery Function Using Jasmine in an Angular Directive Specification

When working with an angular directive, I am currently using $(element).fdatepicker(). How can I mock or stub this function in a jasmine test for the directive? If I don't stub it, I encounter the following error: TypeError: 'undefined' is ...

What is the right way to utilize Fetch in JavaScript and Django?

I am currently working on creating a METAR decoder similar to the one shown in this image: https://i.stack.imgur.com/P40uG.png For this project, I am implementing the use of the fetch function in Vanilla JavaScript. The goal is to send the inputted code t ...

Utilizing static HTML, CSS, and JavaScript for secure backend administrative control

Seeking a solution for my static html, CSS, and JS website which includes some Jquery elements. I want to implement a user-friendly backend system that allows non-developer admins to log in, easily edit sections or change images with their own preferences. ...

Mastering the Art of Binding Option Data from API Responses in Vue.js

Just starting out with Vue.js and attempting to bind option data from an API response. I've made an axios call in the mounted() hook and assigned the companies data from the response, but I'm encountering errors as shown below. 373:11 error ...

What is the best way to save a parsed JSON value to a variable in Express?

I am currently utilizing the body-parser module to parse incoming JSON objects within a POST request. My goal is to extract and store a specific value from the JSON data into a variable for later database insertion. Below is a fragment of the code: var h ...

The scaling of the viewport does not seem to be functioning properly on the mobile device

As a beginner in website development, I am currently working on a new project that is still in the early stages of development. My goal is to ensure that this website is responsive for mobile devices. I have added the following meta tag <meta name="view ...

Join multiple arrays to create an array containing objects in JavaScript

Consider the scenario where I have three arrays representing names, number of books read, and levels of awesomeness: let names = ["Mary", "Joe", "Kenan"]; let numberOfBooks = [2, 1, 4]; let awesomenessLevel = ["pretty cool", "meh", "super-reader"]; I att ...

Pure CSS tab system that prevents label propagation using anchors

I am in the process of creating a tab system using only CSS with the help of the :target and :checked pseudo classes. However, I have encountered an issue where an anchor inside the label is not triggering the :checked. When clicking on the anchor, the :c ...

Deleting sections of a string using JavaScript

I've encountered a rather unique issue where I need to address a bug on a website. The problem is that when a string is generated dynamically, it automatically adds 5 spaces before and after the string. Ideally, this should be fixed in the backend cod ...

Incorporating HTML into C++: A Guide to Seamlessly

I am fairly new to html and c++, but I have a strong background in c#. Recently, I created my very first c++ program - a basic banking system. Now, I am seeking guidance on how to incorporate html into this project. Specifically, I need help displaying the ...

Show an image sourced from a URL, and continue this process for a total of three pictures

I have been attempting to figure out a way to repeat the script so that I can display 3 photos on click and insert a URL. The code below successfully works for the first picture, but I am struggling to make it display the second picture. Currently, the U ...

Cannot hide the minimize/maximize button row in split pane editor layout on Eclipse Neon

Exploring the new features of Eclipse Neon has been a pleasant surprise. One notable improvement is the ability to reclaim wasted space from the UI with minimal effort. For instance, Gtk 3.20 (on Linux) has optimized scrollbars and gutters so well that cu ...

Unpacking objects within an array in the backend of a Next.js application

How can I resolve this issue? I am passing the req.query parameter with an array but I am unable to destructure or use items from the array. In my Next.js API backend, I only get [object Object] or undefined. How can I access and select specific values fro ...

The Jquery function for selecting a div added by an Ajax call is not functioning properly, but it works fine without the need for an

I have a unique checkbox that I created using an Ajax call. The issue I'm facing is that the jQuery to select the checked input in the second div #test_checkbox_ajax isn't working, while it works perfectly fine in the first div #test_checkbox. Cr ...

Utilizing CSS Grid to create a modern layout design featuring a fullwidth header and footer,

I have a traditional website layout with a header, main content area with a sidebar, and a footer. I want the header and footer to span the entire width on wider screens, while the main content and sidebar are fixed width, surrounded by whitespace. When th ...

What steps should I follow to properly set up my tsconfig.json in order to ensure that only the essential files are included when executing npm run build

Introduction I am seeking guidance on how to correctly set up my tsconfig.json file to ensure only the necessary files are included when running npm run build for my projects. I want to avoid any unnecessary files being imported. Query What steps should ...

What could be causing the JavaScript/jquery code in my Functions.php file to only function properly on the initial post that loads on my WordPress website?

Currently, I am in the process of developing a WordPress website where the content is refreshed weekly. This means that all posts, media, and files are removed from the WP environment every week and replaced with new content. One of the key components of ...

Unable to send a parameter in HTML while utilizing PHP inside

I am currently facing a challenge with a piece of code. I have successfully retrieved the results of an SQL query and displayed them in an HTML table, which is functioning perfectly. However, within each row, there is a button that should change the status ...

Objective: Remove all soft items from array stored in MongoDb using Mongoose

I have a unique Array property in my document that is filled with lovely fluffy objects. Now, I am looking to remove all objects within a specific range -> qdate:20210225. The property in the database is named weeks and appears as follows: [ { ...