我正在用JavaScript开发一个Snake游戏,我希望Snake只能垂直或水平移动,但它会一直沿对角线移动。例如,如果我向上按,它会向上移动,但如果我向右按,它将沿对角线移动,而不是仅向右移动。

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
const length_width = 15;
let snakeCoord = [
  {x:300,y:150},
  {x:315,y:150},
  {x:330,y:150},
  {x:345,y:150},
  {x:360,y:150},
  {x:375,y:150}
];

function drawSnakePart(snakePart) {
  ctx.beginPath();
  ctx.fillRect(snakePart.x, snakePart.y, length_width, length_width);
  ctx.strokeRect(snakePart.x, snakePart.y, length_width, length_width);
  ctx.closePath();
}

function drawSnake() {
  snakeCoord.forEach(drawSnakePart);
}

function moveSnake(dx, dy) {
  const head = {
    x: snakeCoord[0].x + dx,
    y: snakeCoord[0].y + dy
  };
  snakeCoord.unshift(head);
  snakeCoord.pop();
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawSnake();
  setTimeout(function() {
    moveSnake(dx, dy)
  }, 100);
}

function keyPress(e) {
  let key = e.key;

  if (key == "ArrowUp") {
    if (snakeCoord[0].y - length_width !== snakeCoord[1].y) {
      moveSnake(0, -length_width);
    }
  } else if (key == "ArrowDown") {
    if (snakeCoord[0].y + length_width !== snakeCoord[1].y) {
      moveSnake(0, length_width);
    }
  } else if (key == "ArrowLeft") {
    if (snakeCoord[0].x - length_width !== snakeCoord[1].x) {
      moveSnake(-length_width, 0);
    }
  } else if (key == "ArrowRight") {
    if (snakeCoord[0].x + length_width !== snakeCoord[1].x) {
      moveSnake(length_width, 0);
    }
  }
}

drawSnake();
document.addEventListener("keyup", keyPress);

<canvas width="500" height="500"></canvas>

最佳答案

在每次按键时,然后递归地设置新的超时setTimeout(function(){ moveSnake(dx,dy) }, 100);。你最终会接到越来越多的有争议的电话。
您应该将超时保存到一个变量,并在调用moveSnake之前用键盘上的clearTimeout()清除它。

08-25 16:08