0

I need to make reset button which makes Resetting Scores. Can anyone help me? I tried all my best but I don't know how to make it.

https://github.com/SandroGamrekelashvili/New-folder

const game = () => {
  let pScore = 0;
  let cScore = 0;

 });
const startGame = () => {
const playBtn = document.querySelector(".intro button");
const introScreen = document.querySelector(".intro");
const match = document.querySelector(".match");
Cindy Meister
  • 25,071
  • 21
  • 34
  • 43

2 Answers2

0

I think what you need to solve your problem is very well explained in this other questions here.

The idea is that instead of declaring your variable inside your main function, you would create a variable that refer to your functions related to your score outside of it that can then be called when you need it. To avoid global conflict, you would have that function return an object with functions inside for getters and setters. In your case, I would do something like this:

const scoreModule = () => {
  let pScore = 0;
  let cScore = 0;

  return {
    getPScore: () => pScore,
    getCScore: () => cScore,
    setPScore: value => pScore = value,
    setCScore: value => cScore = value,
  }
}

Because you defined the scoreModule as a global object, you can then use it wherever you want. And, because you returned only getters and setters (not the actual value, but rather a mean to get or change them) your object is protected and you avoid the bad practice of globally available variables. Then in any of your other functions, when you want to use them either to get or set them, you simply:

    const game = () => {
      // To get a score
      const currentPScore = scoreModule().getPScore()
      // To set a score
      scoreModule().setPScore(newScore)
});
SquallQL
  • 98
  • 1
  • 7
0

There were a few things you needed to get done to make the reset work.

1.) Assign reset button element to a const.

2.) Move your score elements to parent scope.

const game = () => {
   let pScore = 0;
   let cScore = 0;

   const resetBtn = gameContainer.querySelector("button.startOver");

   const playerScore = document.querySelector(".player-score p");
   const computerScore = document.querySelector(".computer-score p");
   // The rest of your code...

2.) Attach event listener to reset button.

const startGame = () => {

    playBtn.addEventListener("click", () => {
        introScreen.classList.add("fadeOut");
        match.classList.add("fadeIn");
    });

    resetBtn.addEventListener("click", () => {
        playerScore.innerText = '0';
        computerScore.innerText = '0';
        pScore = cScore = 0;
    });
};

Here is a JSFiddle with a working example.

jaredrethman
  • 512
  • 5
  • 16