我做了一个蛇游戏,但是当我向右走并同时单击向下和向左时,它会认为它与自身相撞并死亡。
事件的代码是:
$(document).keydown(function(e){
var key = e.which;
if(key == "37" && dir!= "right") dir = "left";
else if (key == "38" && dir != "down") dir = "up";
else if (key == "39" && dir != "left") dir = "right";
else if (key == "40" && dir != "up") dir = "down";
})
我在每 60 毫秒重新绘制一次的绘制方法中有这段代码
var headX = snakeArray[0].x;
var headY = snakeArray[0].y;
//directions
if (dir == "right") headX++;
else if (dir == "left") headX--;
if(dir =="up") headY--;
else if (dir == "down") headY++;
//game over clause
if (headX == -1 || headX == w/cellSize || headY == -1 || headY == h/cellSize || CheckCollision(headX,headY, snakeArray))
{
//restart game
init();
return;
}