【发布时间】:2015-11-07 10:12:29
【问题描述】:
拜托,我正在学习如何制作蛇游戏的教程,我了解了有关代码的所有内容,直到蛇必须移动的地方。我只是似乎不明白蛇是如何移动的逻辑。代码sn-p如下所示:
. . . //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"snake 调用paint() 后snake 的最后一个单元格的x 属性/坐标比调用该方法之前的原始值小1 时,snake 将如何向前移动,并且再次,两个单元格现在重叠因为snake_array 中的两个对象现在具有相同的坐标({x:1,y:0})
【问题讨论】:
标签: javascript logic game-physics