请看,我正在跟随一个关于如何制作贪吃蛇游戏的教程,并且我已经理解了代码的所有内容,直到蛇移动的部分。我似乎无法理解蛇移动的逻辑。以下是代码片段:
我的问题是:我上面概述的代码部分如何使蛇前进?因为当我尝试在浏览器控制台中跟踪代码时,在调用
. . . //the code block to setup the canvas and other basic stuff for the game
//creating the snake
var snake_array; //an array of cells to make up the snake
function create_snake(){
var length = 5; //length of the snake
snake_array = [] //starting with an empty array
for (var i = 0; i < length; i++) {
//this will create a horizontal snake starting from top left
snake_array.push({x:i,y:0});
}
}
create_snake() // invoking the method
//painting the snake
function paint(){
. . . // code block to clear the trail of the snake on the canvas before the snake moves
var nx = snake_array[0].x;
var ny = snake_array[0].y;
if(d == "right") nx++; //d is a variable updated by the keydown event listener code(not shown here)
else if(d == "left") nx--;
if(d == "up") ny--;
if(d == "down") ny++;
var tail = snake_array.pop(); // pops out the last cell
tail.x = nx;
tail.y = ny;
snake_array.unshift(tail)
. . . // code block to paint the snake cells
}
}
paint() // invoking the method
我的问题是:我上面概述的代码部分如何使蛇前进?因为当我尝试在浏览器控制台中跟踪代码时,在调用
create_snake()
后,我得到了一个包含五个对象(代表蛇身体单元格)的数组,它们具有以下属性和值:{x:0,y:0}
、{x:1,y:0}
、{x:2,y:0}
、{x:3,y:0}
、{x:4,y:0}
。在调用paint方法之后,我仍然有五个对象的数组,但是它们的属性和值如下:{x:1,y:0}
、{x:0,y:0}
、{x:1,y:0}
、{x:2,y:0}
、{x:3,y:0}
。现在,当d = "right"
时,蛇如何向前移动,因为在调用paint()
之后,蛇的最后一个单元格的x属性/坐标比调用该方法之前少了1,并且再次出现两个重叠的单元格,因为蛇数组中的两个对象现在具有相同的坐标({x:1,y:0}
).