const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const unitSize = 25;
let score = 0;
let gameRunning = true;
let gameInterval;
let sheep = [];
const player = {
  x: 0,
  y: 0,
  dx: 0,
  dy: 0,
};
const barriers = [
  { x: 0, y: 0, width: unitSize * 5, height: canvas.height },
  {
    x: canvas.width - unitSize * 5,
    y: 0,
    width: unitSize * 5,
    height: canvas.height,
  },
];
document.addEventListener('keydown', changeDirection);

function gameStart() {
  createSheep();
  drawGame();
  updateGame();
}

function updateGame() {
  if (gameRunning) {
    gameInterval = setInterval(() => {
      gameLoop();
      drawGame();
    }, 200);
  } else {
    clearInterval(gameInterval);
    gameOver();
  }
}

function changeDirection(event) {
  if (!gameRunning) return;
  const keyPressed = event.keyCode;
  const goingUp = player.dy === -unitSize;
  const goingDown = player.dy === unitSize;
  const goingRight = player.dx === unitSize;
  const goingLeft = player.dx === -unitSize;

  switch (keyPressed) {
    case 37:
      if (!goingRight) {
        player.dx = -unitSize;
        player.dy = 0;
      }
      break;
    case 38:
      if (!goingDown) {
        player.dy = -unitSize;
        player.dx = 0;
      }
      break;
    case 39:
      if (!goingLeft) {
        player.dx = unitSize;
        player.dy = 0;
      }
      break;
    case 40:
      if (!goingUp) {
        player.dy = unitSize;
        player.dx = 0;
      }
      break;
  }
}

function gameLoop() {
  if (!gameRunning) return;
  movePlayer();
  checkCollision();
}

function movePlayer() {
  player.x += player.dx;
  player.y += player.dy;
}

function checkCollision() {
  if (
    player.x < 0 ||
    player.y < 0 ||
    player.x >= canvas.width ||
    player.y >= canvas.height
  ) {
    gameRunning = false;
    gameOver();
  }

  sheep.forEach((sheepItem, index) => {
    if (player.x === sheepItem.x && player.y === sheepItem.y) {
      score++;
      sheep.splice(index, 1);
      createSheep();
    }
  });
}

function createSheep() {
  while (sheep.length < 3) {
    let newSheep = {
      x:
        Math.floor(Math.random() * ((canvas.width - unitSize * 3) / unitSize)) *
        unitSize,
      y: Math.floor(Math.random() * (canvas.height / unitSize)) * unitSize,
    };

    let collision = sheep.some(
      (sheepItem) => sheepItem.x === newSheep.x && sheepItem.y === newSheep.y
    );
    let playerCollision = player.x === newSheep.x && player.y === newSheep.y;

    if (!collision && !playerCollision) {
      sheep.push(newSheep);
    }
  }
}

function drawGame() {
  if (!gameRunning) return;

  ctx.fillStyle = '#000000';
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.fillStyle = '#888888';
  barriers.forEach((barrier) => {
    ctx.fillRect(barrier.x, barrier.y, barrier.width, barrier.height);
  });

  ctx.fillStyle = 'purple';
  ctx.fillRect(player.x, player.y, unitSize, unitSize);

  ctx.fillStyle = 'aqua';
  sheep.forEach((sheepItem) => {
    ctx.fillRect(sheepItem.x, sheepItem.y, unitSize, unitSize);
  });

  ctx.font = '20px Arial';
  ctx.fillStyle = 'white';
  ctx.fillText('Poeng: ' + score, canvas.width - 100, 20);
}

function gameOver() {
  gameRunning = false;
  ctx.font = '48px Arial';
  ctx.fillStyle = 'red';
  ctx.textAlign = 'center';
  ctx.fillText('Spillet er slutt', canvas.width / 2, canvas.height / 2);
}

gameStart();

这是我的代码,我希望羊产卵的羊在右边的障碍,我需要有3.这里是我认为需要改变的函数,以及X值是准确的.

function createSheep() {
  while (sheep.length < 3) {
    let newSheep = {
      x:
        Math.floor(Math.random() * ((canvas.width - unitSize * 3) / unitSize)) *
        unitSize,
      y: Math.floor(Math.random() * (canvas.height / unitSize)) * unitSize,
    };

我试过将X值更改为不同的东西,但每次我几乎有进展,它最终都是bug,它在障碍的右侧产生了不到3只羊.

推荐答案

你需要创建适当的边界,也就是说,x应该在某个地方,从偏移量等于右侧面板的左边界开始,我们随机化的大小是面板的宽度—绵羊的宽度,y是0和canvas height—绵羊的高度之间的某个地方,或者,把它放在编码的Angular :

    let newSheep = {
      x:
        Math.floor(Math.random() * ((canvas.width - barriers[1].x - unitSize)) + barriers[1].x),
      y: Math.floor(Math.random() * (canvas.height - unitSize)),
    };

工作实例:

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const unitSize = 25;
let score = 0;
let gameRunning = true;
let gameInterval;
let sheep = [];
const player = {
  x: 0,
  y: 0,
  dx: 0,
  dy: 0,
};
const barriers = [
  { x: 0, y: 0, width: unitSize * 5, height: canvas.height },
  {
    x: canvas.width - unitSize * 5,
    y: 0,
    width: unitSize * 5,
    height: canvas.height,
  },
];
document.addEventListener('keydown', changeDirection);

function gameStart() {
  createSheep();
  drawGame();
  updateGame();
}

function updateGame() {
  if (gameRunning) {
    gameInterval = setInterval(() => {
      gameLoop();
      drawGame();
    }, 200);
  } else {
    clearInterval(gameInterval);
    gameOver();
  }
}

function changeDirection(event) {
  if (!gameRunning) return;
  const keyPressed = event.keyCode;
  const goingUp = player.dy === -unitSize;
  const goingDown = player.dy === unitSize;
  const goingRight = player.dx === unitSize;
  const goingLeft = player.dx === -unitSize;

  switch (keyPressed) {
    case 37:
      if (!goingRight) {
        player.dx = -unitSize;
        player.dy = 0;
      }
      break;
    case 38:
      if (!goingDown) {
        player.dy = -unitSize;
        player.dx = 0;
      }
      break;
    case 39:
      if (!goingLeft) {
        player.dx = unitSize;
        player.dy = 0;
      }
      break;
    case 40:
      if (!goingUp) {
        player.dy = unitSize;
        player.dx = 0;
      }
      break;
  }
}

function gameLoop() {
  if (!gameRunning) return;
  movePlayer();
  checkCollision();
}

function movePlayer() {
  player.x += player.dx;
  player.y += player.dy;
}

function checkCollision() {
  if (
    player.x < 0 ||
    player.y < 0 ||
    player.x >= canvas.width ||
    player.y >= canvas.height
  ) {
    gameRunning = false;
    gameOver();
  }

  sheep.forEach((sheepItem, index) => {
    if (player.x === sheepItem.x && player.y === sheepItem.y) {
      score++;
      sheep.splice(index, 1);
      createSheep();
    }
  });
}

function createSheep() {
  while (sheep.length < 3) {
    let newSheep = {
      x:
        Math.floor(Math.random() * ((canvas.width - barriers[1].x - unitSize)) + barriers[1].x),
      y: Math.floor(Math.random() * (canvas.height - unitSize)),
    };

    let collision = sheep.some(
      (sheepItem) => sheepItem.x === newSheep.x && sheepItem.y === newSheep.y
    );
    let playerCollision = player.x === newSheep.x && player.y === newSheep.y;

    if (!collision && !playerCollision) {
      sheep.push(newSheep);
    }
  }
}

function drawGame() {
  if (!gameRunning) return;

  ctx.fillStyle = '#000000';
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.fillStyle = '#888888';
  barriers.forEach((barrier) => {
    ctx.fillRect(barrier.x, barrier.y, barrier.width, barrier.height);
  });

  ctx.fillStyle = 'purple';
  ctx.fillRect(player.x, player.y, unitSize, unitSize);

  ctx.fillStyle = 'aqua';
  sheep.forEach((sheepItem) => {
    ctx.fillRect(sheepItem.x, sheepItem.y, unitSize, unitSize);
  });

  ctx.font = '20px Arial';
  ctx.fillStyle = 'white';
  ctx.fillText('Poeng: ' + score, canvas.width - 100, 20);
}

function gameOver() {
  gameRunning = false;
  ctx.font = '48px Arial';
  ctx.fillStyle = 'red';
  ctx.textAlign = 'center';
  ctx.fillText('Spillet er slutt', canvas.width / 2, canvas.height / 2);
}

gameStart();
<canvas id="gameCanvas"></canvas>

Javascript相关问答推荐

如何将拖放功能添加到我已自定义为图像的文件输入HTML标签中?

Cypress -使用commands.js将数据测试id串在一起失败,但在将它们串在一起时不使用命令有效

没有输出到带有chrome.Devtools扩展的控制台

字节数组通过echo框架传输到JS blob

如何将连续的十六进制字符串拆分为以空间分隔的十六进制块,每个十六进制块包含32个二元组?

GrapeJS -如何保存和加载自定义页面

如何从JSON数组添加Google Maps标记—或者如何为数组添加参数到标记构造器

无法在nextjs应用程序中通过id从mongoDB删除'

D3 Scale在v6中工作,但在v7中不工作

v—自动完成不显示 Select 列表中的所有项目

我的角模板订阅后不刷新'

删除加载页面时不存在的元素(JavaScript)

在验证和提交表单后使用useNavigate()进行react 重定向,使用带有加载器和操作的路由

在渲染turbo流之后滚动到元素

在没有任何悬停或其他触发的情况下连续交换图像

Chrome上的印度时区名S有问题吗?

正则表达式以确定给定文本是否不只包含邮箱字符串

当一条路由在Reaction路由中命中时,如何有条件地渲染两个组件或更改两个插座?

如果我将高度设置为其内容的100%,则在Java脚本中拖动以调整面板大小时会冻结

如何在单击Search按钮时更新Reaction组件?