发现编写 JS 游戏(Snake)时出现问题。无法在蛇体内分离 div。现在我实现了蛇身的几个部分在一个方向上移动,但一个在另一个方向上移动(每个块的顶部左侧位置更新相同)。我想像蛇一样将它们分开,但不知道该怎么做。有人可以给一些建议吗?这是我的 js 代码(仅适用于 chrome):
// field object
var fieldObj = {
field: document.getElementById( "field" ),
w: 480,
h: 580
},
// snake object
snakeObj = {
snakeBody: document.getElementsByClassName( "snake-body" ),
p: {
x: 0, // position x
y: 0 // position y
},
v: {
x: 1, // velocity( here you can change speed)
y: 1
},
keys: {
up: null,
l: null,
r: null,
down: null
},
update: function() {
// this.snake.style.top = this.p.x + "px";
// this.snake.style.left = this.p.y + "px";
if ( this.keys.down ) {
this.p.x += this.v.x;
} else if ( this.keys.up ) {
this.p.x -= this.v.x;
} else if ( this.keys.r ) {
this.p.y += this.v.y;
}else if ( this.keys.l ) {
this.p.y -= this.v.y;
}
for (var i = this.snakeBody.length - 1; i >= 0; i--) {
this.snakeBody[i].style.top = this.p.x + "px";
this.snakeBody[i].style.left = this.p.y + "px";
}
}
},
// game object
gameObj = {
getRandom: function( num ) {
return Math.floor( Math.random() * num );
},
createSnakeTarget: function() {
var snakeTarget = document.createElement( "div" );
snakeTarget.className = "snake-target";
snakeTarget.style.top = this.getRandom( fieldObj.h ) + "px";
snakeTarget.style.left = this.getRandom( fieldObj.w ) + "px";
fieldObj.field.appendChild( snakeTarget );
},
stopGame: function() {
var stopMessage = document.createElement("div");
stopMessage.className = "stop-message";
stopMessage.style.background = "white";
fieldObj.field.appendChild( stopMessage );
//TODO: write message to stopGame
}
};
gameObj.createSnakeTarget();
//gameObj.stopGame();
// Crome works only with keydown and keyup
window.addEventListener('keydown', function() {
// before changing direction you have to put previous direction to false
if ( event.keyCode == 38 ) {
snakeObj.keys.up = true;
snakeObj.keys.down = false;
} else if ( event.keyCode == 40 ) {
snakeObj.keys.down = true;
snakeObj.keys.up = false;
} else if ( event.keyCode == 39 ) {
snakeObj.keys.r = true;
snakeObj.keys.up = false;
snakeObj.keys.down = false;
} else if ( event.keyCode == 37 ) {
snakeObj.keys.l = true;
snakeObj.keys.r = false;
snakeObj.keys.up = false;
snakeObj.keys.down = false;
}
}, false);
//TODO: add event hendler to click to some button
window.addEventListener( "load", function gameLoop() {
snakeObj.update();
requestAnimationFrame( gameLoop );
}, false);
这是codepen http://codepen.io/Kuzyo/pen/esFbf
提前致谢。