javascript - 如何暂停和恢复用香草 javascript 编写的简单蛇游戏?
问题描述
我用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)
如果您需要查看完整代码,可以单击此处查看此游戏的 github 存储库。
谢谢!
解决方案
当有人按下暂停按钮时,检查将 var 的值设置为暂停(真/假)然后在游戏循环中检查游戏是否暂停并停止设置间隔。单击恢复后,您可以再次设置间隔(没有延迟),当然也可以将 paused var 设置为 false。
另一种方法是让 var 像以前一样暂停,并将除间隔之外的所有游戏循环代码放在 if 语句中,检查 var 是真还是假(暂停与否)
推荐阅读
- angular - 哪个库最适合在 Angular 8 中一次绘制 150000 个数据点
- maven - Maven 中不存在 Java_Home
- python - 我创建了用户并尝试登录,然后弹出此错误。“NoneType”对象不可调用
- android - JSON Array可以通过android中的Url发送吗
- ios - 苹果提交说明
- android-studio - Android Studio 不检测 nox 播放器作为模拟器
- r - 分组或汇总和计数
- python - 如何只用左右两个键控制蛇
- wso2 - 如何在单页网站中单次注销
- javascript - 我怎样才能减少chartjs甜甜圈图表的边框宽度