蛇游戏问题

时间:2019-02-26 14:49:42

标签: javascript canvas draw move

为什么蛇会残留在画布上,为什么它们会塌陷到第一个物体中?我希望对象移动的方式是复制对象在其前面的位置。抱歉,如果我的代码难以执行,我确定问题出在update()函数上,并且我已经思考了一段时间,无法解决。我认为第一步是正确的,但在冲突之后。

const c = document.querySelector("canvas");
const ctx = c.getContext("2d");

const width = (c.width = 800);
const height = (c.height = 400);
var length = 4;
var parts = new Array();

class SnakePart {
  constructor() {
    this.x = width / 2;
    this.y = height / 2;
    this.isFirst = 1;
    this.direction = 39;
    this.id = 0
  }
  show() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, 5, 0, 2 * Math.PI);
    ctx.stroke();
  }
  update(other) {

    if (this.isFirst == 1) {
      if (this.direction == 37)
        this.x -= 10;
      if (this.direction == 39)
        this.x += 10;
      if (this.direction == 38)
        this.y -= 10;
      if (this.direction == 40)
        this.y += 10;
    } else if (this.isFirst == 0) {

      this.other = other;

      this.x = this.other.x;
      this.y = this.other.y;

    }
  }
}
for (var i = 0; i < length; i++) {
  let snakePart = new SnakePart();
  parts.push(snakePart);
  if (i > 0) {
    parts[i].x = parts[i - 1].x - 10;
    parts[i].isFirst = 0;
  }
  parts[i].id = i;
  parts[i].show();
}

setInterval(function() {

  ctx.clearRect(parts[length - 1].x - 5, parts[length - 1].y - 5, 10, 10);
  for (var i = 0; i < length; i++) {
    if (parts[i].isFirst == 1) {
      parts[i].update();
    }
    if (parts[i].isFirst == 0) {
      parts[i].update(parts[i - 1]);
    }
    parts[i].show();
  }
}, 1000);
<!DOCTYPE html>
<html>

<head>

  <title></title>
</head>

<body>
  <canvas id="canvas" width="800" height="400" style="border:1px solid #000000;">
	</canvas>
  <script src="snake.js"></script>
  <button onclick="parts[0].direction = 38">UP</button>
  <button onclick="parts[0].direction = 39">RIGHT</button>
  <button onclick="parts[0].direction = 40">DOWN</button>
  <button onclick="parts[0].direction = 37">LEFT</button>
</body>

</html>

0 个答案:

没有答案