javascript - 我应该如何确定苹果可以放置在特定位置?

标签 javascript

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/

相关文章:

javascript - 如何在 lodash 版本 4 中获得 _.pick 功能

javascript - 用于服务器控件的 jquery

javascript - 如何撤销 element.style 属性的设置?

javascript - jquery 从 html 方法中排除元素

javascript - 字符串中的函数

javascript - 在 JavaScript 中使用 Chrome 中的系统打印对话框

javascript - JS反序列化PHP序列化数组

javascript - 有没有一种补充方法来获得鼠标事件之类的东西?

javascript - 使用dialogflow将多个参数写入firestore数据库

javascript - 尝试让粘性栏悬停在滚动页脚上方