0
我通過javascript製作蛇遊戲,我來到了2個問題。沒有工作條件殺死蛇加上不是對象的工作屬性
第一個問題:當他的X和Y碰到畫布的邊界時,我設置了「殺死」蛇的條件,我無法弄清它爲什麼不工作。
問題二:我的方法「畫」的「蛇」,它是怎麼寫的是工作正常,但如果我把而不是「變種I = snake.dlzka」「變種I = snake.snake_body.length」它的類型錯誤:無法讀取未定義的屬性'x'。
var canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 650;
var ctx = canvas.getContext("2d");
var dotW = 10;
var dotH = 10;
var direction = "right"; //smer pohybu hadika
var snake = {
dlzka: 5,
snake_body: [],
arraySpawn: function(){
for(var i = snake.dlzka; i >= 0; i--){
this.snake_body.push({
x: i*dotW,
y: 0
});
}
},
draw: function(){
ctx.clearRect(0,0, canvas.width, canvas.height);
for(var i = snake.dlzka; i>0; i--){
//alert(snake.snake_body.length);
ctx.fillStyle = "blue";
ctx.fillRect(snake.snake_body[i].x, snake.snake_body[i].y, dotW, dotH);
}
snake.move();
},
move: function(){
var first = snake.snake_body[0];
var first_x = first.x;
var first_y = first.y;
switch(direction){
case "right":
first_x += 10;
break;
case "left":
first_x -= 10;
break;
case "up":
first_y -= 10;
break;
case "down":
first_y += 10;
break;
}
this.snake_body.pop();
this.snake_body.unshift({
x: first_x,
y: first_y
});
if((first_x == canvas.width || 0) || (first_y == canvas.height || 0)){
var restart = confirm("Do you want to play again?");
if(restart){
clearInterval(intervalID);
snake.snake_body = [];
snake.arraySpawn();
intervalID = setInterval(function(){snake.draw()}, 33);
}
}
},
update_direction: function(e){
var key = e.keyCode;
if(key == 37 && direction !== "right"){
direction = "left";
}else if(key == 38 && direction !== "down"){
direction = "up";
}else if(key == 39 && direction !== "left"){
direction = "right";
}else if(key == 40 && direction !== "up"){
direction = "down";
}
}
};
snake.arraySpawn();
var intervalID = setInterval(function(){snake.draw()}, 33);
window.onkeydown = snake.update_direction;
canvas{
border: 1px solid black;
}
<canvas id="canvas"></canvas>
小提琴:http://jsfiddle.net/scarface/pdz4k8dj/20/