在 JavaScript Memory Aid 游戏中设置一分钟计时器

setting a one minute timer in JavaScript memory aid game

本文关键字:设置 一分钟 计时器 游戏 JavaScript Memory Aid      更新时间:2023-09-26
<div id="counter">1:00</div>
function countdown() {
var secs = 60;
function tick() {
    var counter = document.getElementById("counter");
    secs--;
    counter.innerHTML = "0:" + (secs < 10 ? "0" : "") + String(secs);
    if( secs > 0 ) {
        setTimeout(tick, 1000);
    } else {
        alert("Game Over");
    }
}
tick();
}
countdown(60);

我对游戏的这一部分有问题。我正在尝试为游戏设置一个 60 秒计时器,该计时器从 60 开始,以 0 结束,当它达到 0 时,游戏停止并且警报显示游戏已结束。

我对编程很陌生,所以请给我尽可能多的反馈。我在互联网上找到了这段代码,我想出了大部分,你能告诉我 tick() 函数在这里做什么吗?

这里有一种方法可以做到这一点:

首先声明一个你将用于间隔的变量(应该是"全局",附加到窗口):

var countDownInterval = null;

然后,一个触发滴答间隔的函数,你应该在游戏准备开始时调用它:

function startCountDown()
{
    countDownInterval = setInterval(tick,1000); //sets an interval with a pointer to the tick function, called every 1000ms
}

它将每秒调用 tick 函数:

function tick()
{
    // Check to see if the counter has been initialized
    if ( typeof countDownInterval.counter == 'undefined' )
    {
        // It has not... perform the initialization
        countDownInterval.counter = 0; //or 60 and countdown to 0
    }
    else
    {
        countDownInterval.counter++; //or --
    }

    console.log(countDownInterval.counter); //You can always check out your count @ the log console.
    //Update your html/css/images/anything you need to do, e.g. show the count.
    if(60<= countDownInterval.counter) //if limit has been reached
    {
        stopGame(); //function which will clear the interval and do whatever else you need to do.
    }
}

然后是游戏结束后您可以执行所有需要执行的操作的功能:

function stopGame()
{
    clearInterval(countDownInterval);//Stops the interval
    //Then do anything else you want to do, call game over functions, etc.
}

您可以随时致电startCountDown();启动计数器

tick 的伪代码:

function tick() {
   reduce counter variable;
   if counter > 0
      wait for 1 second;  (This is what setTimeout(tick, 1000) means)
      call tick() again (recursively)
   }
   else {
     game over
   }
}

像这样的东西?

var countdown = function(sec, tick, done) {
    var interval = setInterval(function(){
        if(sec <= 0) {
            clearInterval(interval);
            done();
        } else {
            tick(sec)
            sec--;
        }
    }, 1000)
}
countdown(10, console.log, function(){console.log('done')})