maze-generator/src/main/java/ch/fritteli/maze/generator/renderer/json/Generator.java

59 lines
2.4 KiB
Java

package ch.fritteli.maze.generator.renderer.json;
import ch.fritteli.maze.generator.json.JsonCell;
import ch.fritteli.maze.generator.json.JsonCoordinates;
import ch.fritteli.maze.generator.json.JsonMaze;
import ch.fritteli.maze.generator.model.Direction;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Tile;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import java.util.ArrayList;
import java.util.List;
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
class Generator {
@NonNull
private final Maze maze;
@NonNull
JsonMaze generate() {
final JsonMaze result = new JsonMaze();
result.setId(String.valueOf(this.maze.getRandomSeed()));
result.setWidth(this.maze.getWidth());
result.setHeight(this.maze.getHeight());
final List<List<JsonCell>> rows = new ArrayList<>();
for (int y = 0; y < this.maze.getHeight(); y++) {
final ArrayList<JsonCell> row = new ArrayList<>();
for (int x = 0; x < this.maze.getWidth(); x++) {
// x and y are not effectively final and can therefore not be accessed from within the lambda. Hence, create the string beforehand.
final String exceptionString = "Failed to obtain tile at %dx%d, although maze has dimensoins %dx%d"
.formatted(x, y, this.maze.getWidth(), this.maze.getHeight());
final Tile tile = this.maze.getTileAt(x, y)
.getOrElseThrow(() -> new IllegalStateException(exceptionString));
final JsonCell cell = new JsonCell();
cell.setTop(tile.hasWallAt(Direction.TOP));
cell.setRight(tile.hasWallAt(Direction.RIGHT));
cell.setBottom(tile.hasWallAt(Direction.BOTTOM));
cell.setLeft(tile.hasWallAt(Direction.LEFT));
cell.setSolution(tile.isSolution());
row.add(cell);
}
rows.add(row);
}
result.setGrid(rows);
final JsonCoordinates start = new JsonCoordinates();
start.setX(this.maze.getStart().getX());
start.setY(this.maze.getStart().getY());
result.setStart(start);
final JsonCoordinates end = new JsonCoordinates();
end.setX(this.maze.getEnd().getX());
end.setY(this.maze.getEnd().getY());
result.setEnd(end);
return result;
}
}