在计时器停止后停止一个函数。

huangapple go评论85阅读模式
英文:

Stopping a function after a timer has stopped

问题

我正在制作一个游戏,希望在计时器达到0时停止游戏功能。
目前,游戏只有在按下重置按钮时才会重置。

计时器会重置,但用户可以继续点击方块并继续游戏,而不必再次按下开始游戏按钮。

这是我的游戏函数:

function startGame() {
    changedBox = null;
    let allBoxes = document.getElementsByClassName("box");
    for (let i = 0; i < allBoxes.length; i++) {
        allBoxes[i].style.backgroundColor = "#e7014c";
    }
    let randomBox = Math.floor(Math.random() * allBoxes.length);
    changedBox = allBoxes[randomBox].id;
    document.getElementById(changedBox).style.backgroundColor = randomColor();

    clearInterval(intervalId);
    intervalId = setInterval(function () {
        let randomBox = Math.floor(Math.random() * allBoxes.length);
        changedBox = allBoxes[randomBox].id;
        document.getElementById(changedBox).style.backgroundColor = randomColor();
    }, 2000);
    if (seconds < 0) {
        return;
    }
}

这是我的开始按钮函数,它也会停止计时器:

let startButton = document.getElementById("start-game");
startButton.addEventListener("click", function () {
    startGame();
    countDown = setInterval(function () {
        document.getElementById("timer").innerHTML = seconds;
        seconds--;
        if (seconds < 0) {
            clearInterval(countDown);
            document.getElementById("timer").innerHTML = "时间到!";
            resetGame();
        }
    }, 1000);
});

重置游戏函数:

function resetGame() {
    clearInterval(intervalId);
    clearInterval(countDown);
    clicks = 0;
    level = 1;
    seconds = 20;
    timer = 20;
    document.getElementById("clicks").innerText = 0;
    document.getElementById("level").innerText = level;
    document.getElementById("timer").innerText = seconds;
    let allBoxes = document.getElementsByClassName("box");
    for (let i = 0; i < allBoxes.length; i++) {
        allBoxes[i].style.backgroundColor = "#e7014c";
    }
}

改变游戏中方块的颜色:

function changeBackground(boxId) {
    if (seconds < 0) {
        return;
    }
    if (intervalId) {
        if (boxId === changedBox) {
            clearInterval(intervalId);
            increaseClicks();
            startGame();
            console.log('方块被点击');
        } else {
            clearInterval(intervalId);
            alert('抱歉,选择错误,请重试!');
            console.log('错误的方块');
        }
    }
}

我已经尝试了我能想到的一切,但游戏仍然继续进行。

我尝试将resetGame函数添加到startGame函数中。

非常感谢您的帮助!

英文:

I am making a game and I am wanting the game function to stop once the timer has reached 0.
Currently the game only resets when you press the reset button.

The timer resets however the user can keep clicking on the boxes and keep the game going, rather than having to press start game again.

This is my game function:

function startGame() {
    changedBox = null;
    let allBoxes = document.getElementsByClassName(&quot;box&quot;);
    for (let i = 0; i &lt; allBoxes.length; i++) {
        allBoxes[i].style.backgroundColor = &quot;#e7014c&quot;;
    }
    let randomBox = Math.floor(Math.random() * allBoxes.length);
    changedBox = allBoxes[randomBox].id;
    document.getElementById(changedBox).style.backgroundColor = randomColor();

    clearInterval(intervalId);
    intervalId = setInterval(function () {
        let randomBox = Math.floor(Math.random() * allBoxes.length);
        changedBox = allBoxes[randomBox].id;
        document.getElementById(changedBox).style.backgroundColor = randomColor();
    }, 2000);
    if (seconds &lt; 0) {
        return;
    }
}

This is my start button function which also stops the timer:

let startButton = document.getElementById(&quot;start-game&quot;);
startButton.addEventListener(&quot;click&quot;, function () {
    startGame();
    countDown = setInterval(function () {
        document.getElementById(&quot;timer&quot;).innerHTML = seconds;
        seconds--;
        if (seconds &lt; 0) {
            clearInterval(countDown);
            document.getElementById(&quot;timer&quot;).innerHTML = &quot;Times up!&quot;;
            resetGame();
        }
    }, 1000);
});

Reset game function

    function resetGame() {
        clearInterval(intervalId);
        clearInterval(countDown);
        clicks = 0;
        level = 1;
        seconds = 20;
        timer = 20;
        document.getElementById(&quot;clicks&quot;).innerText = 0;
        document.getElementById(&quot;level&quot;).innerText = level;
        document.getElementById(&quot;timer&quot;).innerText = seconds;
        let allBoxes = document.getElementsByClassName(&quot;box&quot;);
        for (let i = 0; i &lt; allBoxes.length; i++) {
            allBoxes[i].style.backgroundColor = &quot;#e7014c&quot;;
        }
    }

Changes the colours of the boxes in the game:

    function changeBackground(boxId) {
        if (seconds &lt; 0) {
            return;
        }
        if (intervalId) {
            if (boxId === changedBox) {
                clearInterval(intervalId);
                increaseClicks();
                startGame();
                console.log(&#39;box clicked&#39;);
            } else {
                clearInterval(intervalId);
                alert(&#39;Sorry Wrong Box, Try again!&#39;);
                console.log(&#39;wrong box&#39;);
            }
        }
    }

I've tried everything I can think of and the game just keeps going.

I've tried adding the resetGame function into the startGame function.

Any help would really be appreciated!

答案1

得分: 0

我看到,如果你在玩游戏时时间到了,你仍然可以继续点击游戏表格中的方框。你会收到一个错误提示,但是是的,你可以继续点击(即继续玩)。

你可以在时间到了(即游戏结束)时,除了在屏幕上显示时间到了之外,还可以移除游戏表格的div,这样用户就无法继续玩了。所以在"开始游戏"按钮的Click事件监听器中,你可以将调用resetGame()的部分替换为document.getElementById("game-table").style.display = 'none';,以使游戏表格消失。

let startButton = document.getElementById("start-game");
startButton.addEventListener("click", function () {
  startGame();
  countDown = setInterval(function () {
      document.getElementById("timer").innerHTML = seconds;
      seconds--;
      if (seconds < 0) {
        clearInterval(countDown);
        document.getElementById("timer").innerHTML = "时间到!";
        document.getElementById("game-table").style.display = 'none';
      }
  }, 1000);
});

然后在resetGame()函数中添加一个代码块,使游戏表格的div重新出现:

if (document.getElementById('game-table').style.display == 'none') {
  document.getElementById('game-table').style.display = 'flex';
}

还可以在StartGame()函数中添加一个检查,在changedBox = null;的下方添加一个检查,并在需要时调用resetGame函数进行适当的重置。

if (document.getElementById('game-table').style.display == 'none') {
  resetGame();
}
英文:

I see that if you play your game and the time is up, that you can keep clicking boxes in your game table. You get an error but yes you can keep clicking (i.e. playing).

One thing you could do is when the time is up (i.e. game over), in addition to indicating the time is up on the screen, you could remove the game table div so the user can no longer play. So within your Click eventListener on the "Start Game" button you replace the call to resetGame(); with document.getElementById("game-table".style.display = 'none'; to make the game table disappear.

let startButton = document.getElementById(&quot;start-game&quot;);
startButton.addEventListener(&quot;click&quot;, function () {
  startGame();
  countDown = setInterval(function () {
      document.getElementById(&quot;timer&quot;).innerHTML = seconds;
      seconds--;
      if (seconds &lt; 0) {
        clearInterval(countDown);
        document.getElementById(&quot;timer&quot;).innerHTML = &quot;Times up!&quot;;
        document.getElementById(&quot;game-table&quot;.style.display = &#39;none&#39;;
      }
  }, 1000);
});

Then in your restGame() function add a block to make game table Div to reappear:

if (document.getElementById(&#39;game-table&#39;).style.display == &#39;none&#39;) {
  document.getElementById(&#39;game-table&#39;).style.display = &#39;flex&#39;;
}

Also within your StartGame() function add a check as well right below changedBox = null; and call the resetGame function to reset appropriately if already played.

if (document.getElementById(&#39;game-table&#39;).style.display == &#39;none&#39;) {
  resetGame();
}

答案2

得分: 0

我已经查看了代码并运行了它。这段代码应该修复了游戏无法停止和用户仍然能够点击方块的问题。

我使用了一个名为gameActive的标志变量来检查游戏是否处于活动状态,并相应地禁用了4x4网格,并修改了相应的函数。已经删除了**stopBoxes()**函数,因为它是多余的。你可以试一下。不过,你的游戏可能还有其他可能的错误,比如如果用户点击了一个已经被突出显示的旧方块,他会收到一个不正确的消息,这在逻辑上是不合理的。

英文:

I've had a look through the code and ran it. This code should fix your issue with the game not stopping and the user being still able to click the boxes.

// Variables
let intervalId;
let changedBox = null;
let level = 1;
let clicks = 0;
let seconds = 20;
let countDown;
let totalClicks = 0;
let gameActive = false;

/** COLOUR ARRAY
 * List of colours that the game can choose from to keep the site design with pastel colours
 */
let colors = [&quot;#ffb5e8&quot;, &quot;#d5aaff&quot;, &quot;#6eb5ff&quot;, &quot;#faf99d&quot;, &quot;#bffcc6&quot;,
    &quot;#ffabab&quot;, &quot;#ff9cee&quot;, &quot;#ffcf9e&quot;, &quot;#b28dff&quot;, &quot;#c4faf8&quot;, &quot;#fff5ba&quot;, &quot;#ffbebc&quot;, &quot;#c4faf8&quot;];

/** WHICH BOX HAS CHANGED
 * This if statement checks if the box that has been clicked matches the box that has changed colour
 * If the correct box is clicked, the increaseClicks function is called.
 * If user clicks on the wrong box the below message will appear
 */
function changeBackground(boxId) {
    if (!gameActive) {
        return;
    }

    if (seconds &lt; 0) {
        return;
    }
    if (intervalId) {
        if (boxId === changedBox) {
            clearInterval(intervalId);
            increaseClicks();
            startGame();
            console.log(&#39;box clicked&#39;);
        } else {
            clearInterval(intervalId);
            alert(&#39;Sorry Wrong Box, Try again!&#39;);
            console.log(&#39;wrong box&#39;);
        }
    }
}

/** RANDOM COLOURS
 * This function runs through the array of colours outlined in the variable &#39;colors&#39;
 * So that they are randomly selected
 */
function randomColor() {
    let randomColors = Math.floor(Math.random() * colors.length);
    return colors[randomColors];
}

/** START GAME FUNCTION
 * This function begins by making sure the changedBox is resert to null at the beginning of each round.
 * The for loop goes through each box and makes sure its background is set to the original pink colour.
 * The randomBox will change colour, and calls the randomColor function written above.
 * The clear interval clears the previouis internal is stoped before starting a new one.
 * This was impliments so that the colours did not all change together.
 * An internvial is set to change the boxes every 2 seconds
 */
function startGame() {
    changedBox = null;
    let allBoxes = document.getElementsByClassName(&quot;box&quot;);
    for (let i = 0; i &lt; allBoxes.length; i++) {
        allBoxes[i].style.backgroundColor = &quot;#e7014c&quot;;
        allBoxes[i].disabled = false; // Enable grid buttons
    }
    let randomBox = Math.floor(Math.random() * allBoxes.length);
    changedBox = allBoxes[randomBox].id;
    document.getElementById(changedBox).style.backgroundColor = randomColor();
    clearInterval(intervalId);
    intervalId = setInterval(function () {
        let randomBox = Math.floor(Math.random() * allBoxes.length);
        changedBox = allBoxes[randomBox].id;
        document.getElementById(changedBox).style.backgroundColor = randomColor();
    }, 2000);
}

// SCORE SECTION
function increaseClicks() {
    let currentClicks = parseInt(document.getElementById(&quot;clicks&quot;).innerText);
    let newClicks = currentClicks + 1;
    document.getElementById(&quot;clicks&quot;).innerText = newClicks;
    totalClicks++;
    document.getElementById(&quot;total-clicks&quot;).innerText = totalClicks;
}

// START GAME WITH CLICK
let startButton = document.getElementById(&quot;start-game&quot;);
startButton.addEventListener(&quot;click&quot;, function () {
    if (!gameActive) {
        startGame();
        countDown = setInterval(function () {
            document.getElementById(&quot;timer&quot;).innerHTML = seconds;
            seconds--;

            if (seconds &lt; 0) {
                clearInterval(countDown);
                document.getElementById(&quot;timer&quot;).innerHTML = &quot;Times up!&quot;;
                gameActive = false;
                resetButton.disabled = false; // Enable reset button when game ends
            }
        }, 1000);
        resetButton.disabled = false; // Enable reset game if start button is clicked
        gameActive = true;
    }
});

// RESET GAME
function resetGame() {
    clearInterval(intervalId);
    clearInterval(countDown);
    clicks = 0;
    level = 1;
    seconds = 20;
    document.getElementById(&quot;clicks&quot;).innerText = 0;
    document.getElementById(&quot;level&quot;).innerText = level;
    let allBoxes = document.getElementsByClassName(&quot;box&quot;);
    for (let i = 0; i &lt; allBoxes.length; i++) {
        allBoxes[i].style.backgroundColor = &quot;#e7014c&quot;;
        allBoxes[i].disabled = true; // Disable grid buttons
    }
    gameActive = false; // Set the game state to inactive
    resetButton.disabled = true; // Disable Reset button after resetting the game
    startButton.disabled = false; // Enable the Start button
}

// LEVEL
function addLevel() {
    let currentLevel = parseInt(document.getElementById(&quot;level&quot;).innerText);
    let newLevel = currentLevel + 1;
    document.getElementById(&quot;level&quot;).innerText = newLevel;
}

// RESET BUTTON
let resetButton = document.getElementById(&quot;reset&quot;);
resetButton.addEventListener(&quot;click&quot;, resetGame);

I've used a flag variable gameActive to check if the game is active and disable the 4x4 grid accordingly and modified the functions accordingly. The stopBoxes() function has been removed since it was redundant. Try it out. Although your game has other possible bugs such as if the user clicks on an old box that had been highlighted, he gets an incorrect message, which does not make logical sense.

huangapple
  • 本文由 发表于 2023年8月9日 02:25:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定