蛇游戏-使用array.pop和array.unshift进行蛇移动

时间:2018-12-06 14:06:52

标签: javascript arrays

在我的代码中,蛇及其运动由一个数组组成。换句话说,蛇头是第一个数组编号,最后一个数字是蛇的尾部。我尝试使用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);
}

2 个答案:

答案 0 :(得分:0)

问题与以下事实有关:您将蛇绘制到画布上而不每次都将其重置。绘制了新的蛇形砖,但旧的蛇形砖仍然存在。

您可以通过将这些行移动到Draw函数的开头来进行修复,因此每次您要重画蛇时都会执行它们:

ctx.fillStyle = "green";
ctx.fillRect(0, 0, cWidth, cHeight);

答案 1 :(得分:0)

  

问题在于,三叉戟随着其移动而变得越来越大

这条蛇的大小正确,发生的事情是它留下了一条“足迹”。为避免这种情况,您需要在每次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);
    //(...)