在Javascript中重写动态条件语句

时间:2018-02-21 09:22:32

标签: javascript conditional collision-detection

我正在构建一个网格,其中新项目必须适合下一个可用位置。项目可以是3:2或2:3,网格是12列宽。

如何重写此循环条件语句以删除硬编码限制并接受3:2或2:3(当前x:3,y:2)的输入?

        const check = (
            !grid[rowY + 0][columnX + 0] &&  // @TODO: Hard coded limit
            !grid[rowY + 0][columnX + 1] &&  // @TODO: Hard coded limit
            !grid[rowY + 0][columnX + 2] &&  // @TODO: Hard coded limit
            !grid[rowY + 1][columnX + 0] &&  // @TODO: Hard coded limit
            !grid[rowY + 1][columnX + 1] &&  // @TODO: Hard coded limit
            !grid[rowY + 1][columnX + 2]     // @TODO: Hard coded limit
        );
        if (check) {
            openX = columnX;
            openY = rowY;
            found = true;
        }
        return found;

enter image description here

2 个答案:

答案 0 :(得分:4)

您可以使用everysome数组方法。给定widthheight的值,您可以动态计算check,如下所示:

const check = !grid.slice(rowY, rowY + height).some( row =>
    row.slice(columnX, columnX + width).some(Boolean)
);

答案 1 :(得分:2)

对于网格检查,您可以使用循环来迭代密钥。

如果需要检查整个网格,只需将循环限制设置为相应数组的长度。

以下是硬编码限制的示例:

function unknown() {
  const check = (function() {
    var c = true;
    for (let y = 0; y <= 2; y++) {
      for (let x = 0; x <= 3; x++) {
        c = !grid[rowY + 0][columnX + 0];
        if (!c) {
          return c;
        }
      }
    }
    return c;
  })();
  if (check) {
    openX = columnX;
    openY = rowY;
    found = true;
  }
  return found;
}

如果您感觉舒服,可以使用ES6,您可以使用Array.prototype.some来获得更漂亮的代码:

var grid = [
  [true, true, true, true],
  [true, true, true, true],
  [true, true, true, true],
  [true, true, false, true],
  [true, true, true, true],
];
var openX = null;
var openY = null;
var found = grid
  .some((x, xi) => {
    return x
      .some((y, yi) => {
        if (!y) {
          openX = xi, openY = yi;
        }
        return !y;
      });
  });
console.log(found, openX, openY);

相关问题