简体   繁体   English

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

[英]How should i determine of the apple can be placed in a specific location?

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;
  }
}

this is the code for the apple object in my snake game. 这是我的蛇游戏中苹果对象的代码。 the empty() function is used to ensure the apple doesn't spawn inside of the snake in the create() function. empty()函数用于确保在create()函数中苹果不会在蛇内产卵。 at the moment it does not work how would i fix it? 目前无法正常工作,我该如何解决?

I believe that you mistyped the Logical AND operator. 我相信您输入了逻辑AND运算符。 You should use && instead of & 您应该使用&&而不是&

Here is how your code should be: 这是您的代码应为的样子:

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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM