[英]Let function inside if isn't working. (there is no error message)
Im making a snake game. 我正在做蛇游戏。 I got the problem that if the snake gets into the same position as the food the food respawns to a different place.
我遇到的问题是,如果蛇与食物处于同一位置,则食物会重生到另一个地方。
Nophing, I can't find the error anywhere in internet. Nophing,我在互联网上的任何地方都找不到错误。
function draw (){
if(snakeX == food.x && snakeY == food.y){
score++;
eat.play();
let food = {
x : Math.floor(Math.random()*17+1) * box,
y : Math.floor(Math.random()*15+3) * box
}
It is supposed to add a point to the score, make a sound, replace the food. 应该在分数上加分,发出声音,更换食物。
Now it is adding a point and making a sound. 现在,它正在添加一个点并发出声音。
You need to remove the let
statement , because you create a new local variable with a scope only in the block. 您需要删除
let
语句 ,因为您创建了一个仅在块中具有作用域的新局部变量。 Outside the variable keeps the same value without changing to the new value. 变量外部保持相同的值,而不会更改为新值。
if (snakeX == food.x && snakeY == food.y) {
score++;
eat.play();
food = { // without let
x: Math.floor(Math.random() * 17 + 1) * box,
y: Math.floor(Math.random() * 15 + 3) * box
};
}
Please have a look to this example: 请看这个例子:
x
gets a new local scope with an own value. x
获得具有自己值的新本地范围。 The outer variable x
stays. 外部变量
x
保持不变。
let x = { a: 42 }; if (true) { let x = { b: 0 }; console.log(x); // b ... } console.log(x); // a ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.