ch.fritteli.maze.generator.renderer.json.JsonRenderer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of maze-generator Show documentation
Show all versions of maze-generator Show documentation
A-Maze-R, The Maze Generator. It is a library for generating mazes in various output formats.
The newest version!
package ch.fritteli.maze.generator.renderer.json;
import ch.fritteli.maze.generator.json.JsonCell;
import ch.fritteli.maze.generator.json.JsonMaze;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.renderer.Renderer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class JsonRenderer implements Renderer {
@NotNull
private final ObjectMapper objectMapper;
private JsonRenderer() {
this.objectMapper = new ObjectMapper()
.enable(SerializationFeature.INDENT_OUTPUT);
}
@NotNull
public static JsonRenderer newInstance() {
return new JsonRenderer();
}
@NotNull
private static JsonMaze createSingleCellMaze() {
// This is the only cell.
final JsonCell cell = new JsonCell();
cell.setRight(true);
cell.setLeft(true);
cell.setSolution(true);
// Wrap that in a nested list.
final List> rows = new ArrayList<>();
rows.add(new ArrayList<>());
rows.getFirst().add(cell);
// Wrap it all in an instance of JsonMaze.
final JsonMaze jsonMaze = new JsonMaze();
jsonMaze.setId("0");
jsonMaze.setGrid(rows);
return jsonMaze;
}
@NotNull
private String toString(@NotNull final JsonMaze jsonMaze) {
try {
return this.objectMapper.writeValueAsString(jsonMaze);
} catch (final JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@NotNull
@Override
public String render(@NotNull final Maze maze) {
final JsonMaze jsonMaze;
if (maze.getWidth() == 0 || maze.getHeight() == 0) {
jsonMaze = createSingleCellMaze();
} else {
final Generator generator = new Generator(maze);
jsonMaze = generator.generate();
}
return toString(jsonMaze);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy