In my game I have a set of tiles placed in a 2D array marked by their Xs and Zs ([1,1],[1,2], etc).
Now, I want a sort of "Paint Bucket" mechanism: Selecting a tile will destroy all adjacent tiles until a condition stops it, let's say, if it hits an object with hasFlag
.
Here's what I have so far, I'm sure it's pretty bad, it also freezes everything sometimes:
void destroyAdjacentTiles(int x, int z) {
int GridSize = Cubes.GetLength(0);
int minX = x == 0 ? x : x-1;
int maxX = x == GridSize - 1 ? x : x+1;
int minZ = z == 0 ? z : z-1;
int maxZ = z == GridSize - 1 ? z : z+1;
Debug.Log(string.Format("Cube: {0}, {1}; X {2}-{3}; Z {4}-{5}", x, z, minX, maxX, minZ, maxZ));
for (int curX = minX; curX <= maxX; curX++) {
for (int curZ = minZ; curZ <= maxZ; curZ++) {
if (Cubes[curX, curZ] != Cubes[x, z]) {
Debug.Log(string.Format(" Checking: {0}, {1}", curX, curZ));
if (Cubes[curX,curZ] && Cubes[curX,curZ].GetComponent<CubeBehavior>().hasFlag) {
Destroy(Cubes[curX,curZ]);
destroyAdjacentTiles(curX, curZ);
}
}
}
}
}
Update: I'm trying the recursive version of the Flood-fill algorithm, but I'm having trouble. In order to check the west adjacent tile, I use x-1, for the east, x+1 etc. Problem is, as soon as x = 0, it will infinitely loop between 0 and 1. I also have to check that that tile exists, so I'm using if
s to figure it out in order to not get an IndexOutOfRangeException
(I tried using try/catch, but it's pretty much the same result, I figured this would be simpler). Here's my code right now (yes, I'm reproducing mineSweeper):
bool destroyAdjacentTiles(int x, int z) {
int GridSize = Cubes.GetLength(0);
int minX = x == 0 ? x : x-1;
int maxX = x == GridSize - 1 ? x : x+1;
int minZ = z == 0 ? z : z-1;
int maxZ = z == GridSize - 1 ? z : z+1;
Debug.Log(string.Format("Cube: {0}, {1}; X {2}-{3}; Z {4}-{5}", x, z, minX, maxX, minZ, maxZ));
CubeBehavior thisCube = Cubes[x, z].GetComponent<CubeBehavior>();
if (thisCube.isMine) { Destroy(thisCube); Cubes[x,z] = null; return false; } // TO DO: Make this = game over
// BELOW: Always, no matter what, causes the object to destroy, dunno why. So I removed it for the time being.
//if (thisCube.surroundingMines >= 1) Destroy(thisCube); return true;
// if the function doesn't return by now, means it's a to-be-destroyed cube, so destroy it
//Destroy(thisCube.gameObject);
//Cubes[x,z] = null;
//
if (x > 0) {
if (Cubes[x-1,z].gameObject) destroyAdjacentTiles(x-1, z);
if (x < GridSize - 1)
if (Cubes[x+1,z].gameObject) destroyAdjacentTiles(x+1, z);
}
if (z > 0) {
if (Cubes[x,z-1].gameObject) destroyAdjacentTiles(x, z-1);
if (z < GridSize - 1)
if (Cubes[x,z+1].gameObject) destroyAdjacentTiles(x, z+1);
}
return true;
}