ほとんど解決策を見つけたと感じていますが、助けが必要です。私は2つの配列を持っています.1つはsnakeBody(ヘビの本体になるdivを含む)で、2番目の配列にはsnakeBody(snakeBody[0])からの最初の要素の座標を持つ配列が含まれています。 0]、[40、0]、[60、0]......] (ここでは [coordX, coordY])。各ステップは 20px です。
pastCoord 配列の座標を snakeBody 配列の要素に適用する方法がわかりません。
double for ループについて考えていますが、このループで何をすべきかわかりません:
for (var i = this.snakeBody.length - 1; i >= 0; i--) {
for (var j = gameObj.pastCoord.length - 1; j >= 0; j--) {
};
ここにすべての私のコード:
// field object
var fieldObj = {
field: document.getElementById( "field" ),
w: 480,
h: 580
},
gameObj = {
pastCoord: [],
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();
// snake object
snakeObj = {
snakeBody: document.getElementsByClassName( "snake-body" ),
p: {
x: 0, // position x
y: 0 // position y
},
v: {
x: 20, // velocity ( one loop move one unit of snake body)
y: 20
},
keys: {
up: null,
l: null,
r: null,
down: null
},
update: function() {
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[0].style.top = this.p.x + "px";
this.snakeBody[0].style.left = this.p.y + "px";
}
gameObj.pastCoord.push([this.p.x, this.p.y]);
console.log( gameObj.pastCoord );
}
}
},
//TODO: addEventListener helper function
// after eating snakes become diger and adding to array
//that you can see the length ag snake
//TODO: find out how to improve correctnes of collision
// 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() {
setTimeout( function() {
snakeObj.update();
requestAnimationFrame( gameLoop );
}, 1000);
});
これがcodepenです(CHROMEでのみ機能します)http://codepen.io/Kuzyo/pen/pamzC
助けてくれてありがとう