The_Sketch
@The_Sketch
Веб разработчик x)

Почему этот код срабатывает всегда а не только когда змея откусывает себя?

Я создаю мини игру чтобы отточить навыки.
Но при реализации функции которая должна срабатывать только когда змею откусывает свой хвост, срабатывается и при движении хвоста змейки и при съедании яблока.
Простите, мне очень стыдно за то что уже третий раз не смог решить баг (Просто до этого я никогда не создавал игры на js) :(
Вот код:
var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
var box = 10;

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

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

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);
    });
    if (head.x == ax && head.y == ay) {
      maxCell += 1;
      ax = Math.floor(Math.random() * ~~(canvas.width / box)) * 10;
      ay = Math.floor(Math.random() * ~~(canvas.height / box)) * 10;
    }
    //***************BUG******************
    for (let i = 1; i < snake.length; i++) {
      if (head.x === snake[i].x && head.y === snake[i].y) {
        console.log("hii");
      }
    }
    //**************************************
    snake.pop();
  }

  Snake();
  Apple();
}

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

loop();

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid #000;
        /* background-color: #000; */
      }
    </style>
  </head>
  <body>
    <canvas id="game" width="450" height="450"> </canvas>
    <script src="./snake.js"></script>
  </body>
</html>
  • Вопрос задан
  • 78 просмотров
Решения вопроса 1
@yari_check
Как я понимаю, этот метод нужен только для того, чтобы удлиннить змею, и данное значение потом никуда не передается и просто удаляется в конце
if (snake.length < maxCell) {
  snake.push({ x: px, y: py });
}

Баг выскакивает из-за того, что ты закидываешь значение head в конец массива, а потом весь массив на совпадение с head проверяешь
for (let i = 1; i < snake.length; i++) {
  if (head.x === snake[i].x && head.y === snake[i].y) {
    console.log("hii");
  }
}

Добавляй другое значение в конец и все будет работать :)
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы