在我的代码中,蛇和它的运动由一个阵列组成。换句话说,蛇头是第一个数组,最后一个数字是蛇尾。我尝试使用array.pop和array.unshift实现移动。问题是蛇在移动时越来越大。我认为这是一个非常小的细节,我很想念。这是代码:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cWidth = canvas.width;
var cHeight = canvas.height;
var boxWidth = 10;
var boxHeight = 10;
var boxWH = 10; //One box width and height
var points = 0;
var score = document.getElementById("Score");
var foodImg = new Image();
var k;
foodImg.src = "Pictures/apple2.png";
var snake = [];
snake[0] = {
x: cWidth/2,
y: cHeight/2
};
var food = {
x: Math.floor(Math.random()*60)*boxWH,
y: Math.floor(Math.random()*60)*boxWH
}
document.addEventListener("keydown", direction);
function direction(event){
var key = event.keyCode;
if(key == 65 && k != "right"){
k = "left";
}
else if(key == 68 && k != "left"){
k = "right";
}
else if(key == 87 && k != "down"){
k = "up";
}
else if(key == 83 && k != "up"){
k = "down";
}
}
function SnakeGame(){
ctx.fillStyle = "green";
ctx.fillRect(0, 0, cWidth, cHeight);
var game = setInterval(Draw, 100);
}
function Draw(){
for(var i = 0; i<snake.length; i++){
ctx.fillStyle = (i == 0) ? "red" : "white";
ctx.fillRect(snake[i].x, snake[i].y, boxWH, boxWH);
ctx.strokeStyle = "yellow";
ctx.strokeRect(snake[i].x, snake[i].y, boxWH, boxWH);
}
ctx.drawImage(foodImg, food.x, food.y);
var snakeX = snake[0].x;
var snakeY = snake[0].y;
snake.pop();
if(k == "right") snakeX += boxWH;
if(k == "left") snakeX -= boxWH;
if(k == "up") snakeY -= boxWH;
if(k == "down") snakeY += boxWH;
var nHead = {
x: snakeX,
y: snakeY
}
snake.unshift(nHead);
}
问题是蛇在移动时变得越来越大
蛇的大小正确,发生的是它留下了“痕迹”。为避免这种情况,您需要清除每个Draw
调用的画布。
只需移动命令将画布从SnakeGame
函数填充到Draw
的开头,如下所示:
function SnakeGame(){
var game = setInterval(Draw, 100);
}
function Draw(){
ctx.fillStyle = "green";
ctx.fillRect(0, 0, cWidth, cHeight);
for(var i = 0; i<snake.length; i++){
ctx.fillStyle = (i == 0) ? "red" : "white";
ctx.fillRect(snake[i].x, snake[i].y, boxWH, boxWH);
//(...)
这个问题与你将蛇画在画布上而不是每次都重置它的事实有关。新的蛇瓷砖被绘制,但旧的仍然存在。
您可以通过将这些线移动到Draw函数的开头来修复它,因此每次要重绘蛇时都会执行它们:
ctx.fillStyle = "green";
ctx.fillRect(0, 0, cWidth, cHeight);