I'm working on a city building simulation game, and I have reached the point where I need to check whether tiles are connected to a power source. I decided on a flood fill for this, since it seemed simple enough to implement. For reference, I used this flood fill algorithm, and I also found this question on code review about flood fill in java. My code is largely similar to the code in those links, but it is slightly different because I am not filling an image with color but rather marking tiles connected to power plants as isPowered
.
I know that recursion is dangerous, and the efficiency of the code may be suspect. With the map mostly filled up, this method gets called a couple of thousand times per cycle. With just a snaky path, about 200 times.
Here is an example to show that the algorithm is working:
The visible tiles are powered.
Here is the code:
private void calculatePower() {
for (Tile tile : this.tilesForSort) {
tile.hasBeenSearched = false;
}
for (Tile tile : this.tilesForSort) {
if (tile.getBuildingType() == IsoTileType.POWER) {
this.powerFill(tile.getPosition().x, tile.getPosition().y);
}
}
}
public void powerFill(int x, int y) {
if (this.isNotInsideGrid(x, y)) {
return;
}
Tile tile = this.levelData[x][y];
if (tile.hasBeenSearched || tile.zoneType.getLevel() < 1) {
return;
}
tile.isPowered = true;
tile.hasBeenSearched = true;
this.powerFill(x - 1, y);
this.powerFill(x + 1, y);
this.powerFill(x, y - 1);
this.powerFill(x, y + 1);
}
private boolean isNotInsideGrid (int x, int y) {
return x < 0 || y < 0 || x >= World.WORLD_WIDTH || y >= World.WORLD_HEIGHT;
}
zoneType.getLevel()
is less than 1, that means that the tile is an empty tile. Power is transferred between all connected, non-empty tiles. \$\endgroup\$