我正在用JavaScript做蛇遊戲,所以如果按下箭頭鍵,'蛇頭'應該繼續朝這個方向移動。JavaScript settimeout繼續走得更快,更快?
我第一次按下按鍵就很好,但之後頭部的移動速度越來越快。
所以我想要的是每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);
}
我downvoting這一點,因爲你貼的代碼難以辨認的牆。請花一些時間回顧[常見問題],並**投入您的時間**寫出一個好問題,否則我不值得花時間寫出一個好的答案。 – zzzzBov
[縮進樣式](http://en.wikipedia.org/wiki/Indent_style) –
請注意:不要將字符串傳遞給'setTimeout',它會使用'eval'。傳遞函數:'t = setTimeout(init_game,100);'。 –