如何暂停并恢复一个用香草javascript编写的简单蛇游戏?

如何暂停并恢复一个用香草javascript编写的简单蛇游戏?,javascript,html,Javascript,Html,我用JavaScript制作了一个简单的蛇游戏 我想添加一个功能,游戏可以暂停和恢复时 单击某个图像 我对函数应该是什么有困难 这是我想添加的函数,但仍然是空的: function gamepaused(){ } function gameResume(){ } const pause = document.getElementById('pause').addEventListener('click', gamePaused) const resume = document.getElem

我用JavaScript制作了一个简单的蛇游戏

我想添加一个功能,游戏可以暂停和恢复时 单击某个图像

我对函数应该是什么有困难

这是我想添加的函数,但仍然是空的:

function gamepaused(){

}
function gameResume(){

}
const pause = document.getElementById('pause').addEventListener('click', gamePaused)
const resume = document.getElementById('play').addEventListener('click', gameResume)
这是我的gameLoop函数的内部,它显示了蛇是如何移动的:

function gameLoop(){

position.x += movement.x
position.y += movement.y

//if snake eats the snack
if (snack.x == position.x && snack.y == position.y) {
    snake.push({...position})
    position.x += movement.x
    position.y += movement.y
    drawSnack()
    score ++
}

//if head bump with body
if (movement.x || movement.y) {
    for (let body of snake) {
        if( body.x == position.x && body.y == position.y){
            return init()
        }
    }
    //this is what makes the snake moves forward
    snake.push({...position})
    snake.shift()

  }

  drawScore(score)



 // if head hits the wall, still in game.

  if (position.x < 0 ){
      position.x = TILE
  }
  else if (position.y < 0){
      position.y = TILE
  }
  else if (position.x > TILE)  {
      position.x = -1
  }
  else if (position.y > TILE){
      position.y = -1
  }


}
setInterval (function (){
    requestAnimationFrame (gameLoop)
}, INTERVAL)
函数gameLoop(){
位置.x+=移动.x
位置.y+=移动.y
//如果蛇吃了零食
if(snack.x==position.x&&snack.y==position.y){
snake.push({…位置})
位置.x+=移动.x
位置.y+=移动.y
速食
得分++
}
//如果头部与身体碰撞
if(movement.x | | movement.y){
为了(让蛇的身体){
if(body.x==position.x&&body.y==position.y){
返回init()
}
}
//这就是蛇向前移动的原因
snake.push({…位置})
snake.shift()
}
抽签分数(分数)
//如果头部撞到墙上,仍在游戏中。
如果(位置x<0){
位置x=平铺
}
否则如果(位置y<0){
位置y=平铺
}
else if(position.x>平铺){
位置x=-1
}
else if(position.y>平铺){
位置y=-1
}
}
setInterval(函数(){
requestAnimationFrame(gameLoop)
},间隔时间)
如果需要查看完整的代码,您可以单击查看此游戏的github repo


谢谢

当有人按下暂停按钮时,检查将var的值设置为暂停(真/假) 然后在游戏循环中检查游戏是否暂停并停止设置间隔。 单击恢复后,您可以再次设置间隔(无延迟),当然也可以将暂停的var设置为false


另一种方法是像以前一样暂停var,并将除interval之外的所有游戏循环代码放入if语句中,该语句检查var是否为true或false(暂停或未暂停)

将您的setInterval值保留在变量中,然后调用clearInterval暂停。 比如:

let interval

interval = setInterval (function (){
    requestAnimationFrame (gameLoop)
}, INTERVAL)
并在暂停和恢复功能中添加代码

function gamepaused(){
  clearInterval(interval);
}

function gameResume(){
   interval = setInterval (function (){
        requestAnimationFrame (gameLoop)
    }, INTERVAL)
}