70 lines
2.1 KiB
Java
70 lines
2.1 KiB
Java
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 lombok.NonNull;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
public class JsonRenderer implements Renderer<String> {
|
|
|
|
@NonNull
|
|
private final ObjectMapper objectMapper;
|
|
|
|
private JsonRenderer() {
|
|
this.objectMapper = new ObjectMapper()
|
|
.enable(SerializationFeature.INDENT_OUTPUT);
|
|
}
|
|
|
|
@NonNull
|
|
public static JsonRenderer newInstance() {
|
|
return new JsonRenderer();
|
|
}
|
|
|
|
@NonNull
|
|
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<List<JsonCell>> rows = new ArrayList<>();
|
|
rows.add(new ArrayList<>());
|
|
rows.get(0).add(cell);
|
|
// Wrap it all in an instance of JsonMaze.
|
|
final JsonMaze jsonMaze = new JsonMaze();
|
|
jsonMaze.setId("0");
|
|
jsonMaze.setGrid(rows);
|
|
return jsonMaze;
|
|
}
|
|
|
|
@NonNull
|
|
private String toString(@NonNull final JsonMaze jsonMaze) {
|
|
try {
|
|
return this.objectMapper.writeValueAsString(jsonMaze);
|
|
} catch (final JsonProcessingException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
@NonNull
|
|
@Override
|
|
public String render(@NonNull 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);
|
|
}
|
|
}
|