如何重置游戏分数和按钮文本

How to reset game score and button text

我正在为一个学校项目制作一个打地鼠游戏,我已经让实际的游戏运行,但是一旦 30 秒计时器用完,我在重置游戏时遇到了问题。游戏是用 javascript 和 p5.js 制作的,现在当您加载页面时,游戏 div 显示设置为隐藏,但是当您单击 "begin"显示更改为方块并开始计时(游戏在 github 供参考 https://abm96testgithub.github.io/whackamole/)。当 30 秒结束时,"begin" 按钮变为 "reset",游戏显示返回 "none"(均使用 document.getElementByID 完成)。

有没有办法让它在玩家点击 "reset" 时重新加载整个页面,或者让按钮再次显示 "begin" 并重置分数?

我知道我可以制作一个带有此功能的单独重置按钮,但我觉得有两个按钮会破坏页面的美感。 页面首次加载时按钮的 html 是

<button id="startButton" onclick="startGame();startTimer()">Begin!</button>

而 javascript 是

function startGame() {    
    document.getElementById('sketch-holder').style.display = "block";
}

function countdown () {
    var startCountdown = setInterval(function() {
        document.getElementById('timerVar').innerHTML = counter + "s";
        counter--;

        if (counter < 0) {
            clearInterval(startCountdown);
            document.getElementById('sketch-holder').style.display = "none";
            document.getElementById('startButton').innerHTML = "Reset";
        }
    }, 1000)
}

function startTimer() {   

    if (timerOn === false) {
        timerOn = true;
        countdown();
    }
}

当您使用 P5.js 时使用 setInterval() 有点奇怪。 P5.js 有自己的内部计时机制,我们在您的 .

中谈到了这一点

我不使用 setInterval(),而是使用 millis() 函数或 frameCount 变量来执行时序逻辑。在我对你最后一个问题的回答中查看我的代码:

function setup() {
  createCanvas(200,200);
    background(32);
}

function draw(){
    // 60 frames is 1 second
    if(frameCount % 60 == 0){
      ellipse(random(width), random(height), 25, 25);   
    }
}

此代码每秒绘制一次圆圈。这只是一个示例,但您可以执行非常相似的操作以在 30 秒后重置您的游戏。

然后要重置您的游戏,您真正需要做的就是将您正在使用的所有变量设置回它们的默认值。尝试编写一个 reset() 函数来完全做到这一点。

如果我理解正确,您可以使用带有 void href 的 a 标签,而不是 Button,然后单击您可以添加 href="javascript:window.location.href=window.location.href",这将重新加载页面.

function startGame() {

    document.getElementById('sketch-holder').style.display = "block";
}



        function countdown () {
          var startCountdown = setInterval(function(){
            document.getElementById('timerVar').innerHTML = counter + "s";
            counter--;

            if (counter < 0) {
              clearInterval(startCountdown);
              document.getElementById('sketch-holder').style.display = "none";
              document.getElementById('startButton').innerHTML = "Reset";
              document.getElementById('startButton').setAttribute("href", 'javascript:window.location.href=window.location.href"');
        }
    }, 1000)
}
       function startTimer() {

         if (timerOn === false) {
         timerOn = true;
         countdown();
    }
}
<a href="javascript:void(0)"id="startButton" onclick="startGame();startTimer()">Begin!</a>