Flood algorithm added and (basic) tests performed.
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
package ca.recrown.islandsurvivalcraft.floodfill;
|
||||
|
||||
import ca.recrown.islandsurvivalcraft.types.Point2;
|
||||
|
||||
public interface Floodable {
|
||||
/**
|
||||
* Called for every block. If it shouldn't be flooded, return false.
|
||||
* Code to execute for flooding should be placed here.
|
||||
* @param x the x coordinate.
|
||||
* @param y the y coordinate.
|
||||
* @return if this was a successful flooding.
|
||||
*/
|
||||
public boolean flood(Point2 point);
|
||||
}
|
@@ -0,0 +1,43 @@
|
||||
package ca.recrown.islandsurvivalcraft.floodfill;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
|
||||
import ca.recrown.islandsurvivalcraft.types.Point2;
|
||||
|
||||
public class Flooder {
|
||||
private final HashSet<Point2> checked = new HashSet<>();
|
||||
private final Point2 start;
|
||||
private final Floodable floodable;
|
||||
|
||||
public Flooder(Point2 start, Floodable floodable) {
|
||||
this.start = start;
|
||||
this.floodable = floodable;
|
||||
}
|
||||
|
||||
public Flooder(int xStart, int yStart, Floodable floodable) {
|
||||
this(new Point2(xStart, yStart), floodable);
|
||||
}
|
||||
|
||||
public void start() {
|
||||
if (!checked.add(start)) return;
|
||||
if (!floodable.flood(start)) return;
|
||||
LinkedList<Point2> queue = new LinkedList<>();
|
||||
queue.add(start);
|
||||
while (!queue.isEmpty()) {
|
||||
Point2 p = queue.pop();
|
||||
|
||||
Point2 pE = new Point2(p.x + 1, p.y);
|
||||
if (floodable.flood(pE)) queue.add(pE);
|
||||
|
||||
Point2 pW = new Point2(p.x - 1, p.y);
|
||||
if (floodable.flood(pW)) queue.add(pW);
|
||||
|
||||
Point2 pN = new Point2(p.x, p.y + 1);
|
||||
if (floodable.flood(pN)) queue.add(pN);
|
||||
|
||||
Point2 pS = new Point2(p.x, p.y - 1);
|
||||
if (floodable.flood(pS)) queue.add(pS);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user