I am a beginner in progamming and just wrote my first game with HTML, CSS and vanilla JavaScript. It is working fine but now I am facing an issue while trying to implement a restart-function. I found similar questions and tried a lot but couldn't find a way to solve this: I wrapped the whole game in a function and added an event listener to a button to start the game:
game() { /*game code*/ }
gameButton.addEventListener("click", game);
Inside the code I got multiple functions and eventListeners. There are three ways to "die" and get an Game Over-message. This is when the game button reappears. However, when you click it, the game()-function is still running and the game isn't working, the way it should anymore. I tried to figure out how to stop the whole game-function in case one of these events happens but without success.
So, for example: if you click at the wrong place, a failed-function gets triggered and your score will be decreased by 1. If your score is below 1, you die and the game is over:
function failed() {
let x = parseInt(score.innerText) - 1;
score.innerText = x.toString();
if (x < 1) {
gameOverText.style.display = "block";
}
How I can I stop the game()-function from here?
Thank you very much in advance!
It really depends on the actual code and design. But the easiest way is a boolean. and in your methods check to make sure it is still running
var isActive = true
function failed() {
if (!isActive) return
...
so when the game is over, you set isActive to false
Did you try to attach/remove listener based on event output. Or you can check for condition and return early
pseudo code:
const game = () => {
// Do something here
if(isDisabled) {
return
}
// OR
if(something_to_stop) {
detachListeners()
}
}
function attachListeners() {
gameButton.addEventListener("click", game);
}
function detachListeners() {
gameButton.removeListener("click", game);
}
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.