【问题标题】:Why the code doesn't work when the snake eats the apple?为什么当蛇吃苹果时代码不起作用?
【发布时间】:2023-01-25 19:36:59
【问题描述】:

大家下午好。我正在制作自己的贪吃蛇游戏。而当我实现蛇吃功能时,我遇到了一个问题(蛇吃苹果时应该启动的功能不起作用。)

我试图将苹果的位置等同于块的大小。当蛇吃掉苹果时,函数应该返回一个警告。

var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
var box = 10;

//Snake
var snake = [];
var px = canvas.width / 2;
var py = canvas.height / 2;
var dir = "right";
var maxCell = 10;
var can = canvas.getBoundingClientRect();

//Apple
var ax = Math.floor(Math.random() * ~~(canvas.width / box));
var ay = Math.floor(Math.random() * ~~(canvas.height / box));

document.addEventListener("keydown", function(e) {
  if (e.keyCode === 37 && dir !== "right") {
    dir = "left";
    //console.log('left')
  } else if (e.keyCode === 38 && dir !== "down") {
    dir = "up";
    //console.log('up')
  } else if (e.keyCode === 39 && dir !== "left") {
    dir = "right";
    //console.log('right')
  } else if (e.keyCode === 40 && dir !== "up") {
    dir = "down";
    //console.log('down')
  }
});

function direction() {
  if (dir == "right") {
    px += box;
  } else if (dir == "left") {
    px -= box;
  } else if (dir == "up") {
    py -= box;
  } else if (dir == "down") {
    py += box;
  }
}

//Closure )))
function Elems() {
  //! Spawn apple
  function Apple() {
    ctx.fillStyle = "green";
    ctx.fillRect(ax, ay, box, box);
  }

  //! Spawn snake
  function Snake() {
    direction();
    var head = {
      x: px,
      y: py,
    };
    snake.unshift(head);

    if (snake.length < maxCell) {
      snake.push({
        x: px,
        y: py
      });
    }

    if (px >= canvas.width) {
      px = 0;
    } else if (px < 0) {
      px = canvas.width;
    }
    if (py >= canvas.height) {
      py = 0;
    } else if (py < 0) {
      py = canvas.height;
    }
    snake.forEach(function(elem, index) {
      ctx.fillStyle = `red`;
      ctx.fillRect(elem.x, elem.y, box, box);
    });

    //BROKEN CODE
    if (head.x == ax && head.y == ay) {
      alert("HI");
    }
    snake.pop();
  }

  Snake();
  Apple();
}

function loop() {
  setInterval(() => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    Elems();
  }, 2000 / 30);
}

loop();
canvas {
  border: 1px solid #000;
  background-color: #000;
}
&lt;canvas id="game" width="450" height="450"&gt;&lt;/canvas&gt;

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

    您正在检查是否相等:

    if (head.x == ax && head.y == ay) {
      alert("HI");
    }
    

    您必须检查重叠。苹果不是一个点,它是一个区域。您需要检查这两个区域是否重叠。 (苹果的面积和蛇头的面积)

    【讨论】:

      猜你喜欢
      • 2023-01-26
      • 1970-01-01
      • 2023-04-10
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      • 2021-11-22
      相关资源
      最近更新 更多