我用 HTML5 + CSS3 + JS 制作了我的第一款游戏,但我遇到了一些问题。这是一个简单的贪吃蛇游戏(http://5nake.ugu.pl/)。
让我们开始解决问题。当您打开动画进入游戏(“Gra jednoosobowa”)(您可以在设置中打开/关闭它们(“Ustawienia”))时,一切都被正确绘制,但没有被清除,所以一切都结束了到处都有蛇的部分。当然,玩这样的游戏是不可能的。但是在 Firefox 或 Opera 中一切正常。
另一个存在的问题是,当你输掉比赛时,应该有一个快速动画,其中蛇分裂成单个片段并沿着画布元素向下移动。然后应该显示一个文本(“Koniec gry”)2 秒,游戏应该要求玩家写下他的名字,并且应该显示一个高分屏幕(“Wyniki”)。再一次,谷歌浏览器对此没有做任何事情,当你输掉游戏时,它就会死机。JS 控制台中没有报告。以下是相关代码:
function gameOver() {
stopGame();
storage.set("activeGameData", null);
display.gameOver(function() {
announce("Koniec gry");
setTimeout(function() {
snake.game.showScreen("hiscore", board.getScore());
}, 2500);
});
}
和display.gameOver()
:
function gameOver(callback) {
addAnimation(1000, {
render : function(pos) {
canvas.style.left =
0.2 * pos * (Math.random() - 0.5) + "em";
canvas.style.top =
0.2 * pos * (Math.random() - 0.5) + "em";
},
done : function() {
canvas.style.left = "0";
canvas.style.top = "0";
explode(callback);
}
});
}
这是explode()
功能:
function explode(callback) {
// At the beginning there are many lines of some Math.random() with position,
// velocity and rotation of every fragment of the snake which I skipped.
addAnimation(3000, {
before : function(pos) {
ctx.clearRect(0,0,cols,rows);
},
render : function(pos, delta) {
explodePieces(pieces, pos, delta);
},
done : callback
});
}
并且explodePieces()
:
function explodePieces(pieces, pos, delta) {
// Some calculations on every fragment's position, velocity
// and rotation skipped.
ctx.save();
ctx.translate(piece.pos.x, piece.pos.y);
ctx.rotate(piece.rot * pos * Math.PI * 4);
ctx.translate(-piece.pos.x, -piece.pos.y);
drawObject(piece.type,
piece.pos.x - 0.5,
piece.pos.y - 0.5,
1, piece.rotation
);
ctx.restore();
}
}
动画系统是这样工作requestAnimationFrame()
的:正在做动画循环。的第一个参数addAnimation()
是动画应该持续多长时间的时间。第二个是一个可能有 3 个属性的对象:
- before:它正在为每一帧动画准备画布
- render:它与显示动画的每一帧相关(`pos` 是动画中 0-1 范围内的位置)
- done:动画结束后正在做的事情。
当您尝试在移动设备上玩游戏时,还会出现一个奇怪的问题。该游戏在 Safari (iOS) 和 Firefox Mobile (Android) 中(几乎)正常运行。我还没有在任何其他操作系统上检查过它。然而,即使在 Safari 和 Firefox 中,当你在输掉比赛后切换到高分屏幕时,底部的按钮(“菜单”),本应让你回到主菜单,也不起作用,尽管它在桌面浏览器。这是应该做的事情的代码:
dom.bind(backButton, "click", function(e) {
game.showScreen("main-menu"); // The showScreen function is working for sure.
});
这是dom.bind()
:
function bind(element, event, handler) {
if (typeof element == "string") {
element = $(element)[0];
}
element.addEventListener(event, handler, false)
}
我将不胜感激任何帮助。
这是一个 github 链接供您查看代码:https ://github.com/lewapkon/HTML5Snake 。
负责图形的文件:scripts/display.canvas.js。
gameOver 函数所在的文件:scripts/screen.game.js。
高分菜单文件:scripts/screen.hiscore.js。