Search code examples
javascriptarraysfunctiongame-development

Why isn't my score updating in JavaScript


I have tried many ways to keep score but nothing seems to be working. I have had it as a separate function, in the start function and now in the createImage function to no avail. Can anyone please help me fix my code so that the score increases by 1 if the user clicks on the green ball (at array index 0)?

var imagesArray = new Array(5);
imagesArray[0] = "./green-ball.png";
imagesArray[1] = "./yellow-ball.png";
imagesArray[2] = "./blue-ball.png";
imagesArray[3] = "./light-pink-ball.png";
imagesArray[4] = "./purple-ball.png";

let score = 0;
let timer = 15;
var interval;
let timeLeft = 15;
let lastScore = 0;

var img = document.createElement("img")
const images = document.getElementsByClassName(imagesArray);
var game = document.getElementById("game");


function gameOver() {
    var lastScoreElement = document.getElementById("lastScore");
    clearInterval(timer);
    clearInterval(interval);

    $("#playAgainButton").show();
    $("#lastScore").show(
        lastScoreElement.textContent = " " + score
    );
    ResetGlobalVariables;
}

function random(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function createImage() {
    img.src = imagesArray[random(0, imagesArray.length - 1)];
    img.width = random(50, 200);
    img.height = random(50, 200);
    img.style.left = random(0, 800 - img.width) + "px";
    img.style.top = random(0, 600 - img.height) + "px";
    return img;
    for (i = 0; i < imagesArray.length; i++) {
        imagesArray[0].addEventListener("click", function() {
            score++;
            var scoreElement = document.getElementById("score");
            scoreElement.innerHTML = score;
        });
    };
}

function updateTimer() {
    timeLeft = timeLeft - 1;
    if(timeLeft >= 0)
        $("#timer").html(timeLeft);
    else {
        gameOver();
    }; 1000;
}

function start() {
    timer = setInterval(updateTimer, 1000);
    updateTimer();
    $("#playAgainButton").hide();
    interval = setInterval(function() {
        var img = createImage();
        game.appendChild(img);
    }, 1500);
}

function ResetGlobalVariables() {
    score = 0;
    timer = 15;
    timeLeft = 15;
}

const resetBtn = document.querySelector(".reset-button")
resetBtn.addEventListener("click", ResetGlobalVariables)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <tr>
        <td>
            <div id="game"></div>
        </td>
        <td id="text">
            <p id="gameTitle">Find Greenie!<img src="green-ball.png" alt="Logo"></p>
            <p id="score">Current Score: 0</p>
            <p> You have: <span id="timer">15</span> seconds remaining!</p>
            <button id="playAgainButton" onclick="start()">Go!</button>
            <input id="reset" type="button" class="reset-button" value="Reset">
            <p> You scored: <span id="lastScore"></span></p>
            <br>
            <br>
            <p>Click on Greenie the green ball to score points</p>
            <p>Click Reset and then Go! to restart</p>
            <script src="find.js"></script>
        </td>
    </tr>
</table>


Solution

  • You need to delegate the event listener to the game container. You need to check the clicked ball is green

    You can remove the code after the return img since nothing will be executed after a return

    game.addEventListener("click", function(e) {
      const tgt = e.target;
      if (!tgt.matches('img')) return; // not a ball
      if (!tgt.src.includes('green')) return; // not green
      score++;
      scoreElement.innerHTML = score;
    });
    

    var imagesArray = [
      "./green-ball.png",
      "./yellow-ball.png",
      "./blue-ball.png",
      "./light-pink-ball.png",
      "./purple-ball.png",
    ];
    let score = 0;
    let timer = 15;
    var interval;
    let timeLeft = 15;
    let lastScore = 0;
    
    var img = document.createElement("img")
    const images = document.getElementsByClassName(imagesArray);
    var game = document.getElementById("game");
    
    
    function gameOver() {
      var lastScoreElement = document.getElementById("lastScore");
      clearInterval(timer);
      clearInterval(interval);
    
      $("#playAgainButton").show();
      $("#lastScore").show(
        lastScoreElement.textContent = " " + score
      );
      ResetGlobalVariables;
    }
    
    function random(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    
    function createImage() {
      img.src = imagesArray[random(0, imagesArray.length - 1)];
      img.width = random(50, 200);
      img.height = random(50, 200);
      img.style.left = random(0, 800 - img.width) + "px";
      img.style.top = random(0, 600 - img.height) + "px";
      img.alt = img.src.split('/').pop(); // to show the colour 
      return img;
    }
    
    function updateTimer() {
      timeLeft = timeLeft - 1;
      if (timeLeft >= 0)
        $("#timer").html(timeLeft);
      else {
        gameOver();
      };
      1000;
    }
    
    function start() {
      timer = setInterval(updateTimer, 1000);
      updateTimer();
      $("#playAgainButton").hide();
      interval = setInterval(function() {
        var img = createImage();
        game.appendChild(img);
      }, 1500);
    }
    
    function ResetGlobalVariables() {
      score = 0;
      timer = 15;
      timeLeft = 15;
    }
    
    const resetBtn = document.querySelector(".reset-button")
    resetBtn.addEventListener("click", ResetGlobalVariables)
    const scoreElement = document.getElementById("score");
    
    game.addEventListener("click", function(e) {
      const tgt = e.target;
      if (!tgt.matches('img')) return; // not a ball
      if (!tgt.src.includes('green')) return; // not green
      score++;
      scoreElement.innerHTML = score;
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tr>
        <td>
          <div id="game"></div>
        </td>
        <td id="text">
          <p id="gameTitle">Find Greenie!<img src="green-ball.png" alt="Logo"></p>
          <p id="score">Current Score: 0</p>
          <p> You have: <span id="timer">15</span> seconds remaining!</p>
          <button id="playAgainButton" onclick="start()">Go!</button>
          <input id="reset" type="button" class="reset-button" value="Reset">
          <p> You scored: <span id="lastScore"></span></p>
          <br>
          <br>
          <p>Click on Greenie the green ball to score points</p>
          <p>Click Reset and then Go! to restart</p>
          <script src="find.js"></script>
        </td>
      </tr>
    </table>

    To improve the script, you could have all balls hidden on the page and toggle between one visible using the random number