function Apple() {
this.x = 0;
this.y = 0;
this.show = function() {
fill(255, 0, 0);
noStroke();
rect(this.x, this.y, scl, scl);
}
this.create = function() {
var cols = fieldWidth/scl;
var rows = fieldHeight/scl;
do {
this.x = floor(random(cols))*scl+15;
this.y = floor(random(rows))*scl+30;
} while (!empty());
}
function empty() {
for (var i = 0; i < s.body.length; i++) {
if (this.x == s.body[i].x & this.y == s.body[i].y) {
return false;
}
}
return true;
}
}
这是我的贪吃蛇游戏中苹果对象的代码。 empty() 函数用于确保苹果不会在 create() 函数中的蛇内部生成。目前它不起作用我该如何修复它?
最佳答案
我相信您输错了逻辑 AND 运算符。
您应该使用 &&
而不是 &
您的代码应如下所示:
function Apple() {
this.x = 0;
this.y = 0;
this.show = function() {
fill(255, 0, 0);
noStroke();
rect(this.x, this.y, scl, scl);
}
this.create = function() {
var cols = fieldWidth/scl;
var rows = fieldHeight/scl;
do {
this.x = floor(random(cols))*scl+15;
this.y = floor(random(rows))*scl+30;
} while (!empty());
}
function empty() {
for (var i = 0; i < s.body.length; i++) {
if (this.x == s.body[i].x && this.y == s.body[i].y) {
return false;
}
}
return true;
}
}
关于javascript - 我应该如何确定苹果可以放置在特定位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52107562/