【问题标题】:How do define a timeoutId in more than one scope如何在多个范围内定义 timeoutId
【发布时间】:2018-06-24 21:41:08
【问题描述】:

我使用 javascript 画布制作了一款经典的 Snake 街机游戏,我正在尝试构建功能以减少游戏动画运行的间隔。如果您不熟悉 Snake,一条蛇会在屏幕上移动并尝试吃掉随机出现的苹果,同时尽量不撞到自己或墙壁。蛇每吃一个苹果,它就变长,游戏变得更难。我试图通过每次蛇吃苹果时加快游戏速度来增加游戏的难度。我在下面的代码 sn-p 中实现了这一点:

//Animate the game
function gameLoop() {
  ctx.clearRect(0, 0, width, height);
  drawScore();
  snake.move();
  snake.draw();
  apple.draw();
  drawBorder();
  var timeoutID = setTimeout(function() {
    gameLoop();
  }, interval);
};
gameLoop(); //call the game loop

问题在于我有一个gameOver() 函数可以访问运行游戏的setTimeout 函数的timeoutId,但timeoutId 变量未在gameOver() 函数中定义。更令人困惑的是,gameOver 函数在它应该工作的时候仍然可以工作,但它会在控制台中产生一个错误,上面写着:

Uncaught ReferenceError: timeoutID is not defined
    at gameOver (snake.html:68)
    at Snake.move (snake.html:157)
    at gameLoop (snake.html:253)
    at snake.html:258

并且gameOver() 函数未按预期运行。它应该显示“游戏结束”并显示玩家的最后得分,并简单地显示蛇没有制造。相反,当调用gameOver() 函数时,它会擦除​​屏幕。这是gameOver() 函数:

function gameOver() {
  ctx.font = "60px monospace";
  ctx.fillStyle = "black";
  ctx.textAlign = "center";
  ctx.fillText("Game Over", width/2, height/2);
  clearTimeout(timeoutID);
};

我想知道是否有一种方法可以在游戏结束时停止gameLoop() 函数,而不会收到错误消息并且不会擦除屏幕。我尝试了几种不同的方法都无济于事。谢谢。

【问题讨论】:

    标签: javascript canvas


    【解决方案1】:

    您需要定义gameLooptimeoutID outside 以便它在其他地方可见,例如gameOver 函数:

    var timeoutID;
    function gameLoop() {
      // ...
      timeoutID = setTimeout( ...
      // ...
    }
    // ...
    function gameOver() {
      // referencing timeoutID here will now be possible
    

    但不是保存 timeoutID,在这种情况下,您可能会发现简单地使用一个外部 boolean 来指示 gameLoop 是否应该运行会更容易:

    var gameIsOver = false;
    function gameLoop() {
      if (gameIsOver) return;
      // ...
    }
    // ...
    function gameOver() {
      gameIsOver = true;
      // ...
    

    【讨论】:

    • 谢谢。我曾尝试在全局范围内定义timeoutID,但由于某种原因它以前不起作用。也许我搞砸了,因为这一次奏效了。非常感谢。
    猜你喜欢
    • 2016-07-24
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2021-08-18
    相关资源
    最近更新 更多