开发者

Looking for an efficient way to sum the surrounding values of a 3D array

I'm writing a 3D Minesweeper-type game, so given an a[x][y][z], I need to calculate the sum of the surrounding values assuming they aren't out of bounds.

My question is how can I do this without having a zillion checks for:

if ((开发者_JAVA百科x>0)&&(x<ARRAY_SIZE)) 

for x, y, and z?

Thanks


Very easy: make your erray 2 elements bigger in every dimension and then make a 0-frame around it. Your loops all run from 1 to ARRAY_SIZE-1 and accesss to index-1 and index+1 do not make any longer trouble in case you are at the bounds.


How about writing your own customized class for the game board, something like

    class Minesweeper3DBoard {
      public MinesweeperField getField(int x, int y, int z) {
        if (x < 0 || x >= ARRAY_SIZE || y < 0 || y >= ARRAY_SIZE || z < 0 || z >= ARRAY_SIZE)  {
   return NullMineSweeperField.Instance(); 
}
   else {
     return Fields_[x][y][z];
   }

      }
    };

with NullMineSweeperField implementing the Null Object and Singleton patterns, and Fields_ containing the "real" fields?
This way, you'll have only one place where the checking takes place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜