我在尝试用Java编写一个小游戏,其中有盒子相互碰撞并弹开,但有时它们在被生成时会重叠,从而导致它们被卡住。我已经切换到HTML和JavaScript,创建了一个子项目来解决这个问题,通过创建一个2D数组来包含所有可能的位置,位于画布元素的边界内。最后我成功解决了这个问题,但因为我的程序在一个大数组中试图去掉一大堆位置,导致程序加载需要几分钟的时间。我现在卡住了,因为我想不出更好的解决方案,我会把我的代码贴出来,以防有更好的方法来解决这个问题。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>矩阵</title>
</head>
<body>
<canvas id="myCanvas" style="border-style: solid; border-color: red;" width="512" height="512"></canvas>
<script>
const myCanvas = document.getElementById("myCanvas");
const paint = myCanvas.getContext("2d");
const allowedPositions = [];
const blocks = [];

function startGame() {
  const size = 48;
  constructAllowedPositions(size);
  for (let i = 0; i < 10; i++) {
    createBlock(size);
  }
  renderBlocks();
}

function constructAllowedPositions(size) {
  for (let y = 0; y < 512 - size; y++) {
    for (let x = 0; x < 512 - size; x++) {
      allowedPositions.push(JSON.stringify([x, y]));
    }
  }
}

function createBlock(size) {
  const pMax = allowedPositions.length;
  if (pMax === 0) {
    return;
  }
  const string = allowedPositions[Math.floor(Math.random() * (pMax))];
  const point = JSON.parse(string);
  const x = point[0];
  const y = point[1];
  destroyPositions(point, size);
  blocks.push(new Block(x, y, size));
}

class Block {
  constructor(x, y, size) {
    this.x = x;
    this.y = y;
    this.size = size;
  }
}

function destroyPositions(point, size) {
  const startX = point[0];
  const startY = point[1];
  for (let y = startY - size - 1; y < startY + size - 1; y++) {
    for (let x = startX - size - 1; x < startX + size - 1; x++) {
      if (allowedPositions.includes(JSON.stringify([x, y]))) {
        const index = allowedPositions.indexOf(JSON.stringify([x, y]));
        allowedPositions.splice(index, 1);
      }
    }
  }
}

function renderBlocks() {
  paint.font = "25px Arial";
  for (let i = 0; i < blocks.length; i++) {
    const block = blocks[i];
    const x = block.x;
    const y = block.y;
    const size = block.size;
    paint.font = (size - 7) + "px Arial";
    paint.globalAlpha = 0.5;
    paint.fillStyle = "rgb(255, 0, 0)";
    paint.fillRect(x - size, y - size, size * 2, size * 2);
    paint.globalAlpha = 1;
    paint.fillStyle = "rgb(" + x + ", " + y + ", " + i + ")";
    paint.fillRect(x, y, size, size);
    paint.fillStyle = "rgb(0, 0, 0)";
    paint.fillRect(x, y, size / 4, size / 4);
    paint.fillStyle = "rgb(0, 0, 0)";
    paint.fillText(i, x + size / 2, y + size / 2);
  }
}

startGame();
</script>
</body>
</html>