我正在用 JavaScript 制作蛇游戏,所以如果我按下箭头键,“蛇头”应该会继续朝那个方向移动。
我第一次按下一个键时它做得很好,但在那之后头部移动得越来越快。
所以我想要的是每 100 毫秒移动一次头部的东西。如果你不明白我的意思,那么看看这个页面:http ://www.dbzweb.be/08/braetj08/snake.html
那么,有人可以告诉我如何更改我的代码以使其保持以相同的速度运行吗?
function init_game() {
if ((event ? event.keyCode : down) == (event ? 40 : 1)) /*down*/
{
if ((snakehead + z) < z * z) {
right = 0;
left = 0;
up = 0;
down = 1;
document.getElementsByClassName(snakehead, "div", document)[0].id = "gamebox";
snakehead = snakehead + z;
document.getElementsByClassName(snakehead, "div", document)[0].id = "gameboxsnake";
} else {
document.write("<h1>game over!</h1> press this button to try again.<br><input type='button' value='retry' onclick='window.open(\"http://www.dbzweb.be/08/braetj08/snake.html\",\"_self\")'>");
}
}
if ((event ? event.keyCode : up) == (event ? 38 : 1)) /*up*/
{
if ((snakehead - z) > -1) {
right = 0;
left = 0;
up = 1;
down = 0;
document.getElementsByClassName(snakehead, "div", document)[0].id = "gamebox";
snakehead = snakehead - z;
document.getElementsByClassName(snakehead, "div", document)[0].id = "gameboxsnake";
} else {
document.write("<h1>game over!</h1> press this button to try again.<br><input type='button' value='retry' onclick='window.open(\"http://www.dbzweb.be/08/braetj08/snake.html\",\"_self\")'>");
}
}
if ((event ? event.keyCode : right) == (event ? 39 : 1)) /*right*/
{
if ((snakehead + 1) % z !== 0) {
right = 1;
left = 0;
up = 0;
down = 0;
document.getElementsByClassName(snakehead, "div", document)[0].id = "gamebox";
snakehead = snakehead + 1;
document.getElementsByClassName(snakehead, "div", document)[0].id = "gameboxsnake";
} else {
document.write("<h1>game over!</h1> press this button to try again.<br><input type='button' value='retry' onclick='window.open(\"http://www.dbzweb.be/08/braetj08/snake.html\",\"_self\")'>");
}
}
if ((event ? event.keyCode : left) == (event ? 37 : 1)) /*left*/
{
if (snakehead % z !== 0) {
right = 0;
left = 1;
up = 0;
down = 0;
document.getElementsByClassName(snakehead, "div", document)[0].id = "gamebox";
snakehead = snakehead - 1;
document.getElementsByClassName(snakehead, "div", document)[0].id = "gameboxsnake";
} else {
document.write("<h1>game over!</h1> press this button to try again.<br><input type='button' value='retry' onclick='window.open(\"http://www.dbzweb.be/08/braetj08/snake.html\",\"_self\")'>");
}
}
t = 0;
t = setTimeout("init_game()", 100);
}