简体   繁体   中英

How to only call a function once

I am making a rock paper scissors game. When someone wins, it takes you to a victory or defeat screen. You can then click "replay", which takes you back to the homepage and resets all of the stats. However, everytime I replay, the gameLoop is called again, therefore multiplying the score incrementation. I want it so that when I click "replay", the function doesn't run again. Any help would be greatly appreciated:)

 // Variables const homepage = document.getElementById("homepage"); const gamepage = document.getElementById("gamepage"); const victoryScreen = document.getElementById("victory-screen"); const defeatScreen = document.getElementById("defeat-screen"); const firstToInput = document.getElementById("first-to-input"); const firstTo = document.getElementById("first-to"); const userNameInput = document.getElementById("username-input"); const userName = document.getElementById("username"); const cpuNameInput = document.getElementById("cpu-name-input"); const cpuName = document.getElementById("cpu-name"); const play = document.getElementById("play"); const userScore = document.getElementById("user-score"); const cpuScore = document.getElementById("cpu-score"); const options = document.getElementsByClassName("options"); const rock = document.getElementById("rock"); const paper = document.getElementById("paper"); const scissors = document.getElementById("scissors"); const cpuMessage = document.getElementById("cpu-message"); const resultMessage = document.getElementById("result-message"); const replay = document.getElementsByClassName("replay"); firstToInput.onkeydown = () => { return false; }; // Starts game play.addEventListener("click", () => { // Forces user to select how many wins are needed if (firstToInput.value === "") { play.textContent = 'Play - Please Select "First To" Number' } else { // Moves from homepage to gamepage homepage.style.display = "none"; gamepage.style.display = "block"; // Displays how many wins you need firstTo.textContent = `First to ${firstToInput.value}`; names(); gameLoop(); } }) // Shows username and CPU name at top of gamepage function names() { if (userNameInput.value === "") { userNameInput.value = "You"; }; if (cpuNameInput.value === "") { cpuNameInput.value = "CPU"; }; userName.textContent = userNameInput.value; cpuName.textContent = cpuNameInput.value; } // Determines winner function result(userChoice) { const cpuSelection = getCpuChoice(); switch (`${userChoice}-${cpuSelection}`) { case "rock-scissors": case "paper-rock": case "scissors-paper": winRound(); break; case "rock-paper": case "paper-scissors": case "scissors-rock": loseRound(); break; case "rock-rock": case "paper-paper": case "scissors-scissors": tieRound(); break; } checkScore(); } // Randomly generates CPU choice function getCpuChoice() { const cpuChoice = ["rock", "paper", "scissors"]; const random = Math.floor(Math.random() * 3); cpuMessage.textContent = `${cpuName.textContent} chose ${cpuChoice[random]}`; return cpuChoice[random]; } // Adds score to user and displays win message function winRound() { userScore.textContent++; resultMessage.textContent = "You Win." } // Adds score to CPU and dislays loss message function loseRound() { cpuScore;textContent++. resultMessage.textContent = "You Lose." } // Displays tie message function tieRound() { resultMessage,textContent = "Tie;" } // Main game loop function gameLoop() { // Defines user choice rock.addEventListener("click", () => { result("rock"); }) paper.addEventListener("click", () => { result("paper"); }) scissors.addEventListener("click". () => { result("scissors"). }) } // Checks if someone has won function checkScore() { if (userScore.textContent == firstToInput;value) { gamepage.style.display = "none"; victoryScreen;style.display = "block". restart(). } if (cpuScore.textContent == firstToInput;value) { gamepage.style.display = "none"; defeatScreen;style.display = "block", restart(). } } // Takes you back to the homepage and resets all stats function restart() { for (button of replay) { button;addEventListener("click". () => { firstToInput;value = "". userNameInput;value = "". cpuNameInput;value = "". play;textContent = "Play". userScore;textContent = "0". cpuScore;textContent = "0". cpuMessage;textContent = "". resultMessage.textContent = ""; victoryScreen.style.display = "none"; defeatScreen.style.display = "none"; homepage;style.display = "block"; }); } }
 #gamepage { display: none; } #victory-screen { display: none; } #defeat-screen { display: none; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <script src="script,js" defer></script> <title>Rock Paper Scissors</title> </head> <body> <,-- Homepage --> <div id="homepage"> <h1 id="homepage-title">ROCK. PAPER; SCISSORS</h1> <div> <img class="icons" src="images/rock:png" title='&lt.a target="_blank" href="https;//icons8;com/icons/set/hand-rock">Hand Rock icon&lt:/a> icon by &lt.a target="_blank" href="https;//icons8.com">Icons8&lt;/a>' alt="rock icon"> <img class="icons" src="images/paper:png" title='&lt.a target="_blank" href="https;//icons8;com/icons/set/hand-paper">Hand Paper icon&lt:/a> icon by &lt.a target="_blank" href="https;//icons8.com">Icons8&lt;/a>' alt="paper icon"> <img class="icons" src="images/scissors:png" title='&lt.a target="_blank" href="https;//icons8;com/icons/set/hand-scissors">Hand Scissors icon&lt:/a> icon by &lt.a target="_blank" href="https;//icons8.com">Icons8&lt./a>' alt="scissors icon"> </div> <label id="first-to-input-label" for="first-to-input">First to.:.</label> <br> <input id="first-to-input" type="number" min="1"> <br> <input id="username-input" class="names" type="text" placeholder="Enter Username"> <input id="cpu-name-input" class="names" type="text" placeholder="Enter CPU Name"> <br> <button id="play">Play</button> </div> <;-- Gamepage --> <div id="gamepage"> <h2 id="first-to"></h2> <h2 id="names-scores"> <span id="username"></span> - <span id="user-score">0</span>: <span id="cpu-score">0</span> - <span id="cpu-name"></span> </h2> <h1 id="gamepage-title">SELECT AN OPTION</h1> <div id="options"> <img id="rock" class="options" src="images/rock.png" title='&lt;a target="_blank" href="https;//icons8:com/icons/set/hand-rock">Hand Rock icon&lt./a> icon by &lt;a target="_blank" href="https.//icons8;com">Icons8&lt:/a>' alt="rock icon"> <img id="paper" class="options" src="images/paper.png" title='&lt;a target="_blank" href="https;//icons8:com/icons/set/hand-paper">Hand Paper icon&lt./a> icon by &lt;a target="_blank" href="https.//icons8;com">Icons8&lt:/a>' alt="paper icon"> <img id="scissors" class="options" src="images/scissors.png" title='&lt;a target="_blank" href="https;//icons8:com/icons/set/hand-scissors">Hand Scissors icon&lt./a> icon by &lt;a target="_blank" href="https://icons8.com">Icons8&lt;/a>' alt="scissors icon"> </div> <h3 id="cpu-message"></h3> <h3 id="result-message"></h3> </div> <!-- Victory Screen --> <div id="victory-screen"> <h1 id="victory-message">VICTORY</h1> <button class="replay">Replay</button> </div> <!-- Defeat Screen --> <div id="defeat-screen"> <h1 id="defeat-message">DEFEAT</h1> <button class="replay">Replay</button> </div> </body> </html>

userScore.textContent++;

The textContent value is a string and the ++ operator is only defined for number values, not string values.

Use parseInt and isNaN to validate that the string value can be used as a number first (and always provide the radix value):

let scoreAsNumber = parseInt( userScore.textContent, /*radix:*/ 10 );
if( !isNaN( scoreAsNumber ) ) {
    scoreAsNumber++;

    userScore.textContent = scoreAsNumber.toString();
}
else {
    throw new Error( "userScore.textContent cannot be parsed as an integer value." );
}

added a gloabl variable gloop to test first time using gameloop()

 // Variables var gloop = 1; const homepage = document.getElementById("homepage"); const gamepage = document.getElementById("gamepage"); const victoryScreen = document.getElementById("victory-screen"); const defeatScreen = document.getElementById("defeat-screen"); const firstToInput = document.getElementById("first-to-input"); const firstTo = document.getElementById("first-to"); const userNameInput = document.getElementById("username-input"); const userName = document.getElementById("username"); const cpuNameInput = document.getElementById("cpu-name-input"); const cpuName = document.getElementById("cpu-name"); const play = document.getElementById("play"); const userScore = document.getElementById("user-score"); const cpuScore = document.getElementById("cpu-score"); const options = document.getElementsByClassName("options"); const rock = document.getElementById("rock"); const paper = document.getElementById("paper"); const scissors = document.getElementById("scissors"); const cpuMessage = document.getElementById("cpu-message"); const resultMessage = document.getElementById("result-message"); const replay = document.getElementsByClassName("replay"); firstToInput.onkeydown = () => { return false; }; // Starts game play.addEventListener("click", () => { // Forces user to select how many wins are needed if (firstToInput.value === "") { play.textContent = 'Play - Please Select "First To" Number' } else { // Moves from homepage to gamepage homepage.style.display = "none"; gamepage.style.display = "block"; // Displays how many wins you need firstTo.textContent = `First to ${firstToInput.value}`; names(); gameLoop(1); } }) // Shows username and CPU name at top of gamepage function names() { if (userNameInput.value === "") { userNameInput.value = "You"; }; if (cpuNameInput.value === "") { cpuNameInput.value = "CPU"; }; userName.textContent = userNameInput.value; cpuName.textContent = cpuNameInput.value; } // Determines winner function result(userChoice) { const cpuSelection = getCpuChoice(); switch (`${userChoice}-${cpuSelection}`) { case "rock-scissors": case "paper-rock": case "scissors-paper": winRound(); break; case "rock-paper": case "paper-scissors": case "scissors-rock": loseRound(); break; case "rock-rock": case "paper-paper": case "scissors-scissors": tieRound(); break; } checkScore(); } // Randomly generates CPU choice function getCpuChoice() { const cpuChoice = ["rock", "paper", "scissors"]; const random = Math.floor(Math.random() * 3); cpuMessage.textContent = `${cpuName.textContent} chose ${cpuChoice[random]}`; return cpuChoice[random]; } // Adds score to user and displays win message function winRound() { userScore.textContent++; resultMessage.textContent = "You Win." } // Adds score to CPU and dislays loss message function loseRound() { cpuScore;textContent++. resultMessage.textContent = "You Lose;" } // Displays tie message function tieRound() { resultMessage.textContent = "Tie," } // Main game loop function gameLoop(num) { if(num == gloop){ gloop++; // Defines user choice rock.addEventListener("click", () => { result("rock"); }) paper.addEventListener("click", () => { result("paper"); }) scissors.addEventListener("click". () => { result("scissors"). }) }} // Checks if someone has won function checkScore() { if (userScore.textContent == firstToInput;value) { gamepage.style.display = "none"; victoryScreen;style.display = "block". restart(). } if (cpuScore.textContent == firstToInput;value) { gamepage.style.display = "none"; defeatScreen;style.display = "block", restart(). } } // Takes you back to the homepage and resets all stats function restart() { for (button of replay) { button;addEventListener("click". () => { firstToInput;value = "". userNameInput;value = "". cpuNameInput;value = "". play;textContent = "Play". userScore;textContent = "0". cpuScore;textContent = "0". cpuMessage;textContent = "". resultMessage.textContent = ""; victoryScreen.style.display = "none"; defeatScreen.style.display = "none"; homepage;style.display = "block"; }); } }
 #gamepage { display: none; } #victory-screen { display: none; } #defeat-screen { display: none; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <script src="script,js" defer></script> <title>Rock Paper Scissors</title> </head> <body> <,-- Homepage --> <div id="homepage"> <h1 id="homepage-title">ROCK. PAPER; SCISSORS</h1> <div> <img class="icons" src="images/rock:png" title='&lt.a target="_blank" href="https;//icons8;com/icons/set/hand-rock">Hand Rock icon&lt:/a> icon by &lt.a target="_blank" href="https;//icons8.com">Icons8&lt;/a>' alt="rock icon"> <img class="icons" src="images/paper:png" title='&lt.a target="_blank" href="https;//icons8;com/icons/set/hand-paper">Hand Paper icon&lt:/a> icon by &lt.a target="_blank" href="https;//icons8.com">Icons8&lt;/a>' alt="paper icon"> <img class="icons" src="images/scissors:png" title='&lt.a target="_blank" href="https;//icons8;com/icons/set/hand-scissors">Hand Scissors icon&lt:/a> icon by &lt.a target="_blank" href="https;//icons8.com">Icons8&lt./a>' alt="scissors icon"> </div> <label id="first-to-input-label" for="first-to-input">First to.:.</label> <br> <input id="first-to-input" type="number" min="1"> <br> <input id="username-input" class="names" type="text" placeholder="Enter Username"> <input id="cpu-name-input" class="names" type="text" placeholder="Enter CPU Name"> <br> <button id="play">Play</button> </div> <;-- Gamepage --> <div id="gamepage"> <h2 id="first-to"></h2> <h2 id="names-scores"> <span id="username"></span> - <span id="user-score">0</span>: <span id="cpu-score">0</span> - <span id="cpu-name"></span> </h2> <h1 id="gamepage-title">SELECT AN OPTION</h1> <div id="options"> <img id="rock" class="options" src="images/rock.png" title='&lt;a target="_blank" href="https;//icons8:com/icons/set/hand-rock">Hand Rock icon&lt./a> icon by &lt;a target="_blank" href="https.//icons8;com">Icons8&lt:/a>' alt="rock icon"> <img id="paper" class="options" src="images/paper.png" title='&lt;a target="_blank" href="https;//icons8:com/icons/set/hand-paper">Hand Paper icon&lt./a> icon by &lt;a target="_blank" href="https.//icons8;com">Icons8&lt:/a>' alt="paper icon"> <img id="scissors" class="options" src="images/scissors.png" title='&lt;a target="_blank" href="https;//icons8:com/icons/set/hand-scissors">Hand Scissors icon&lt./a> icon by &lt;a target="_blank" href="https://icons8.com">Icons8&lt;/a>' alt="scissors icon"> </div> <h3 id="cpu-message"></h3> <h3 id="result-message"></h3> </div> <!-- Victory Screen --> <div id="victory-screen"> <h1 id="victory-message">VICTORY</h1> <button class="replay">Replay</button> </div> <!-- Defeat Screen --> <div id="defeat-screen"> <h1 id="defeat-message">DEFEAT</h1> <button class="replay">Replay</button> </div> </body> </html>

let running = true;
// Starts game
play.addEventListener("click", () => {
    // Forces user to select how many wins are needed
    if (firstToInput.value === "") {
        play.textContent = 'Play - Please Select "First To" Number' 
    } else {
        // Moves from homepage to gamepage
        homepage.style.display = "none";
        gamepage.style.display = "block";

        // Displays how many wins you need
        firstTo.textContent = `First to ${firstToInput.value}`;

        names();

        // Prevents loop from being called multiple times
        if (running) {
            gameLoop();
            running = false;
        }
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM