我正在尝试创建一个蛇游戏。我的问题是当蛇遇到食物时,没有匹配。请在我的代码中检查功能eat()
,其中x
需要相同food_position_x
和y
需要等于food_position_y
。尝试比较两个位置时不匹配
(function() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
x = 0,
y = 0,
speed = 1;
x_move = speed,
y_move = 0,
food_position_x = Math.floor(Math.random() * canvas.width);
food_position_y = Math.floor(Math.random() * canvas.height);
function eat() {
if (x == food_position_x && y == food_position_y) {
alert('Match!');
}
}
// Drawing
function draw() {
eat();
requestAnimationFrame(function() {
draw();
});
// Draw the snake
ctx.beginPath();
ctx.rect(Math.floor(x/10)*10, Math.floor(y/10)*10, 10, 10);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#ffffff';
ctx.fill();
ctx.closePath();
// Draw the food
ctx.beginPath();
ctx.rect(Math.floor(food_position_x/10)*10, Math.floor(food_position_y/10)*10, 10, 10);
ctx.fillStyle = "blue";
ctx.fill();
ctx.closePath();
// Increase the value of x and y in order to animate
x = x + x_move;
y = y + y_move;
}
draw();
// Key Pressing
document.addEventListener('keydown', function(event) {
switch(event.keyCode) {
case 40: // Moving down
if (x_move != 0 && y_move != -1) {
x_move = 0;
y_move = speed;
}
break;
case 39: // Moving right
if (x_move != -1 && y_move != 0) {
x_move = speed;
y_move = 0;
}
break;
case 38: // Moving top
if (x_move != 0 && y_move != 1) {
x_move = 0;
y_move = -speed;
}
break;
case 37: // Moving left
if (x_move != 1 && y_move != 0) {
x_move = -speed;
y_move = 0;
}
break;
}
});
})();
canvas { background-color: red; }
<canvas width="500" height="300" id="canvas">
我在做什么错?
它看起来像'food_position_x'和'food_position_y'可以在画布上任意整数坐标,但你的蛇的位置总是整除10.您正在绘制的食物放在同一像蛇一样的10像素网格,但它的实际位置是在两个单元之间的某处。作为第一步,当你设置它时,强迫食物的位置被10整除。 –
您的蛇的位置也是一样,您正在以10像素的网格绘制它,但其实际位置可能是任何整数。因此,当(82,129)蛇和(85,124)食物时,你看起来像是在(80,120)所画的食物之上。 –