javascript - 如何正确检测邻区

标签 javascript html canvas

作为一个学习项目,我正在编写一个简单的逻辑游戏,其中用户有 html Canvas 网格,他需要在其中连接相同颜色的方 block 。

我一直在检测相邻单元格的属性(它的颜色),如果条件匹配(相邻颜色与我的不同),则不应填充该单元格。

我的问题是: 1)有没有更好的方法来检查目标方 block 是否可以填充颜色?

2) 如果有,如何正确处理对新单元格的点击?

function checkNeighbourTiles(aX, aY) {
  var coords = [
    [(aX - 1), (aY - 1)],
    [(aX - 1), (aY)],
    [(aX - 1), (aY + 1)],
    [(aX), (aY - 1)],
    [(aX), (aY + 1)],
    [(aX + 1), (aY - 1)],
    [(aX + 1), (aY - 1)],
    [(aX + 1), (aY + 1)]
  ]

  for (i = 0; i < coords.length; i++) {
    var x = coords[i][0]
    var y = coords[i][1]
    var b = cells[x][y]
  }
}

到目前为止我的代码 - jsfiddle

最佳答案

这取决于复杂性和性能限制。正如您所做的那样,直接查找表的效率与简单网格查找的效率差不多,但不是每次都创建查找数组,只需创建一次偏移数组即可。

// an array of offset coordinates in pairs x,y 8 pairs skipping the center
const NEIGHBOURS = [-1, -1, 0, -1, 1, -1, -1, 0, 1, 0, -1, 1, 0, 1, 1, 1];

const GIRD_SIZE = 10; // 10 by ten grid
function checkNeighbourTiles(x,y){
    var lx, ly, cellResult;
    var i = 0;
    while(i < 16){  // check for each offset
        lx = x + NEIGHBOURS[i++]; // get the x offset
        ly = y + NEIGHBOURS[i++]; // get the y offset
        // ensure you are inside the grid
        if( ly >= 0 && ly < GRID_SIZE && lx >= 0 && lx < GRID_SIZE ){
             cellResult = cell[lx][ly];
             // do what is needed with the result;
        }
    }
}

对于二维数组的类型,这是最简单的方法。

另一种方法是链接数组,每个单元格都包含对相邻单元格的引用数组。 因此(考虑到简单性)只有左上角和右下角。然后每个单元格看起来像

cell = {
    top : undefined,
    left : undefined,
    right : undefined,
    bottom : undefined,
    ... other data
}

然后当您添加单元格时,您将引用设置为适当的单元格

// first add all the cells to the array 
// then for each cell call this
function AddCell(cell,x,y){
    cell.top = cells[x][y-1];
    cell.left = cells[x-1][y];
    cell.right = cells[x+1][y];
    cell.bottom = cells[x][y+1];
    // also the cells you just reference should also reference back
    // where top refs botton and left refs right and so fourth.
    cells.top.bottom = cell;
    cells.bottom.top = cell;
    cells.left.right = cell;
    cells.right.left = cell;

}

然后在任何时候如果你想找到哪个单元格在上面

//x and y are the cell
var cellAbove = cell[x][y].top;

当您开始获得复杂的链接(例如死单元格、跳过单元格,甚至插入单元格以更改网格的拓扑结构)时,此方法有很多优势。

你也可以进行复杂的搜索,比如左二一下

resultCall = cell[x][y].left.left.bottom; // returns the cell two left one down

但是维护链接很痛苦,因为涉及很多额外的代码,所以对于简单的 2D 网格,您的方法是最好的。

关于javascript - 如何正确检测邻区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36404941/

相关文章:

javascript - 嵌套 .then() 的 Promise

javascript - 为什么不能直接设置 "style"

html - 将 HTML anchor 嵌入到在 SAS 中使用 ODS HTML 创建的标题

javascript - Canvas 绘制错误(HTML5 和 JavaScript)

javascript - 正确使用 .tagName

javascript - Electron <webview> 使用退格键返回

javascript - 如何获取鼠标坐标并调用.push()?

javascript - 为什么上下文描边会重绘 Canvas 上的旧图

javascript - 带有 Pandoc 的完全独立的 HTML 文件

html - 我应该将我的 SASS 输出(多个文件)合并到一个文件中吗?如果是这样,如何?