Compare commits

..

No commits in common. "master" and "v0.0.4" have entirely different histories.

68 changed files with 1063 additions and 2806 deletions
.drone.ymlREADME.mdmaven-settings.xmlmaze-generator.imlpom.xml
src
main
test/java/ch/fritteli

View file

@ -3,7 +3,7 @@ type: docker
name: default
steps:
- name: build
image: maven:3.9-eclipse-temurin-21
image: maven:3.8-openjdk-18-slim
commands:
- mvn clean install -DskipTests=true -Dmaven.javadoc.skip=true -B -V
when:
@ -13,7 +13,7 @@ steps:
- refs/head/feature/**
- refs/tags/**
- name: test
image: maven:3.9-eclipse-temurin-21
image: maven:3.8-openjdk-18-slim
commands:
- mvn test -B
when:
@ -22,12 +22,10 @@ steps:
- master
- feature/*
- name: deploy
image: maven:3.9-eclipse-temurin-21
image: maven:3.8-openjdk-18-slim
environment:
REPO_TOKEN:
from_secret: repo-token
REPO_TOKEN_OSSRH:
from_secret: repo-token-ossrh
commands:
- mvn -s maven-settings.xml deploy -DskipTests=true
when:

View file

@ -1 +1,2 @@
# maze-generator
# labyrinth-generator

View file

@ -8,10 +8,5 @@
<username>ci</username>
<password>${env.REPO_TOKEN}</password>
</server>
<server>
<id>ossrh</id>
<username>4etdRvZF</username>
<password>${env.REPO_TOKEN_OSSRH}</password>
</server>
</servers>
</settings>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="AdditionalModuleElements">
<content url="file://$MODULE_DIR$" dumb="true">
<sourceFolder url="file://$MODULE_DIR$/target/generated-sources/jsonschema2pojo" isTestSource="false" generated="true" />
</content>
</component>
</module>

190
pom.xml
View file

@ -5,24 +5,26 @@
<parent>
<groupId>ch.fritteli</groupId>
<artifactId>fritteli-build-parent</artifactId>
<version>5.1.0</version>
<version>2.0.4</version>
</parent>
<groupId>ch.fritteli.a-maze-r</groupId>
<artifactId>maze-generator</artifactId>
<version>0.3.1-SNAPSHOT</version>
<groupId>ch.fritteli.labyrinth</groupId>
<artifactId>labyrinth-generator</artifactId>
<version>0.0.4</version>
<description>The Labyrinth generator, a library for generating Labyrinths in various output formats.</description>
<url>https://manuel.friedli.info/labyrinth.html</url>
<description>A-Maze-R, The Maze Generator. It is a library for generating mazes in various output formats.
</description>
<url>https://manuel.friedli.info/maze.html</url>
<inceptionYear>2022</inceptionYear>
<licenses>
<license>
<name>GNU Affero General Public License</name>
<url>https://www.gnu.org/licenses/agpl-3.0.html</url>
</license>
</licenses>
<properties>
<java.source.version>17</java.source.version>
<java.target.version>17</java.target.version>
<jetbrains-annotations.version>24.0.1</jetbrains-annotations.version>
<junit-jupiter.version>5.9.2</junit-jupiter.version>
<logback.version>1.4.6</logback.version>
<lombok.version>1.18.26</lombok.version>
<pdfbox.version>2.0.27</pdfbox.version>
<slf4j.version>2.0.7</slf4j.version>
<vavr.version>0.10.4</vavr.version>
</properties>
<developers>
<developer>
@ -39,28 +41,6 @@
</developer>
</developers>
<scm>
<connection>scm:git:https://gittr.ch/java/maze-generator.git</connection>
<developerConnection>scm:git:ssh://git@gittr.ch/java/maze-generator.git</developerConnection>
<url>https://gittr.ch/java/maze-generator</url>
<tag>HEAD</tag>
</scm>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<name>Sonatype Maven Repository - Snapshots</name>
<url>https://s01.oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
</distributionManagement>
<properties>
<jackson.version>2.17.1</jackson.version>
<jsonschema2pojo-maven-plugin.version>1.2.1</jsonschema2pojo-maven-plugin.version>
<maven-site-plugin.version>4.0.0-M8</maven-site-plugin.version>
<pdfbox.version>3.0.2</pdfbox.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
@ -74,33 +54,20 @@
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.2.1-jre</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>${pdfbox.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
@ -109,27 +76,31 @@
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.24.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>${jsonschema2pojo-maven-plugin.version}</version>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>ch.fritteli.labyrinth.generator.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<phase>generate-sources</phase>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>generate</goal>
<goal>single</goal>
</goals>
<configuration>
<sourcePaths>
<sourcePath>src/main/resources/maze.schema.json</sourcePath>
</sourcePaths>
</configuration>
</execution>
</executions>
</plugin>
@ -149,55 +120,52 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>${maven-site-plugin.version}</version>
<version>4.0.0-M6</version>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<scm>
<connection>scm:git:https://gittr.ch/java/labyrinth-generator.git</connection>
<developerConnection>scm:git:ssh://git@gittr.ch/java/labyrinth-generator.git</developerConnection>
<url>https://gittr.ch/java/labyrinth-generator</url>
<tag>v0.0.4</tag>
</scm>
<distributionManagement>
<repository>
<id>repo.gittr.ch</id>
<name>gittr.ch</name>
<url>https://repo.gittr.ch/releases/</url>
</repository>
<snapshotRepository>
<id>repo.gittr.ch</id>
<name>gittr.ch</name>
<url>https://repo.gittr.ch/snapshots/</url>
</snapshotRepository>
</distributionManagement>
<repositories>
<repository>
<id>repo.gittr.ch.releases</id>
<url>https://repo.gittr.ch/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
<repository>
<id>repo.gittr.ch.snapshots</id>
<url>https://repo.gittr.ch/snapshots/</url>
<releases>
<enabled>false</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
</repositories>
</project>

View file

@ -0,0 +1,51 @@
package ch.fritteli.labyrinth.generator;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.renderer.html.HTMLRenderer;
import ch.fritteli.labyrinth.generator.renderer.htmlfile.HTMLFileRenderer;
import ch.fritteli.labyrinth.generator.renderer.pdffile.PDFFileRenderer;
import ch.fritteli.labyrinth.generator.renderer.text.TextRenderer;
import ch.fritteli.labyrinth.generator.renderer.textfile.TextFileRenderer;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import java.nio.file.Path;
import java.nio.file.Paths;
@Slf4j
public class Main {
public static void main(@NonNull final String[] args) {
final int width = 20;
final int height = 30;
final Labyrinth labyrinth = new Labyrinth(width, height/*, 0*/);
final TextRenderer textRenderer = TextRenderer.newInstance();
final HTMLRenderer htmlRenderer = HTMLRenderer.newInstance();
final Path userHome = Paths.get(System.getProperty("user.home"));
final String baseFilename = getBaseFilename(labyrinth);
final TextFileRenderer textFileRenderer = TextFileRenderer.newInstance()
.setTargetLabyrinthFile(userHome.resolve(baseFilename + ".txt"))
.setTargetSolutionFile(userHome.resolve(baseFilename + "-solution.txt"));
final HTMLFileRenderer htmlFileRenderer = HTMLFileRenderer.newInstance()
.setTargetFile(userHome.resolve(baseFilename + ".html"));
final PDFFileRenderer pdfFileRenderer = PDFFileRenderer.newInstance()
.setTargetFile(userHome.resolve(baseFilename + ".pdf"));
log.info("Labyrinth-ID: {}", labyrinth.getRandomSeed());
// Render Labyrinth to stdout
log.info("Text rendering:\n{}", textRenderer.render(labyrinth));
// Render Labyrinth solution to stdout
log.info("Text rendering with solution:\n{}", textRenderer.setRenderSolution(true).render(labyrinth));
// Render HTML to stdout
log.info("HTML rendering:\n{}", htmlRenderer.render(labyrinth));
// Render Labyrinth and solution to (separate) files
log.info("Text rendering to file:\n{}", textFileRenderer.render(labyrinth));
// Render HTML to file
log.info("HTML rendering to file:\n{}", htmlFileRenderer.render(labyrinth));
// Render PDF to file
log.info("PDF rendering to file:\n{}", pdfFileRenderer.render(labyrinth));
}
private static String getBaseFilename(@NonNull final Labyrinth labyrinth) {
return "labyrinth-" + labyrinth.getWidth() + "x" + labyrinth.getHeight() + "-" + labyrinth.getRandomSeed();
}
}

View file

@ -0,0 +1,23 @@
package ch.fritteli.labyrinth.generator.model;
public enum Direction {
TOP,
RIGHT,
BOTTOM,
LEFT;
public Direction invert() {
switch (this) {
case TOP:
return BOTTOM;
case RIGHT:
return LEFT;
case BOTTOM:
return TOP;
case LEFT:
return RIGHT;
default:
throw new IllegalStateException("Programming error: Not all enum values covered in enum Direction#invert()!");
}
}
}

View file

@ -0,0 +1,169 @@
package ch.fritteli.labyrinth.generator.model;
import io.vavr.control.Option;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.ToString;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Random;
@EqualsAndHashCode
@ToString
public class Labyrinth {
private final Tile[][] field;
@Getter
private final int width;
@Getter
private final int height;
@Getter
private final long randomSeed;
@EqualsAndHashCode.Exclude
private final Random random;
@Getter
private final Position start;
@Getter
private final Position end;
public Labyrinth(final int width, final int height) {
this(width, height, System.nanoTime());
}
public Labyrinth(final int width, final int height, final long randomSeed) {
if (width <= 1 || height <= 1) {
throw new IllegalArgumentException("width and height must be >1");
}
this.width = width;
this.height = height;
this.randomSeed = randomSeed;
this.random = new Random(randomSeed);
this.field = new Tile[width][height];
this.start = new Position(0, 0);
this.end = new Position(this.width - 1, this.height - 1);
this.initField();
this.generate();
}
/**
* INTERNAL API.
* Exists only for deserialization. Not to be called from user code.
*/
private Labyrinth(@NonNull final Tile[][] field, final int width, final int height, final long randomSeed) {
this.field = field;
this.width = width;
this.height = height;
this.randomSeed = randomSeed;
this.random = new Random(randomSeed);
this.start = new Position(0, 0);
this.end = new Position(this.width - 1, this.height - 1);
}
@NonNull
public Option<Tile> getTileAt(@NonNull final Position position) {
return this.getTileAt(position.getX(), position.getY());
}
@NonNull
public Option<Tile> getTileAt(final int x, final int y) {
if (x < 0 || y < 0 || x >= this.width || y >= this.height) {
return Option.none();
}
return Option.of(this.field[x][y]);
}
@NonNull
Tile getStartTile() {
return this.getTileAt(this.start).get();
}
@NonNull
Tile getEndTile() {
return this.getTileAt(this.end).get();
}
private void initField() {
for (int x = 0; x < this.width; x++) {
this.field[x] = new Tile[this.height];
for (int y = 0; y < this.height; y++) {
final Tile tile = new Tile();
this.hardenWalls(tile, x, y);
this.field[x][y] = tile;
}
}
}
private void hardenWalls(@NonNull final Tile tile, final int x, final int y) {
if (x == 0) {
tile.preventDiggingToOrFrom(Direction.LEFT);
}
if (x == this.width - 1) {
tile.preventDiggingToOrFrom(Direction.RIGHT);
}
if (y == 0) {
tile.preventDiggingToOrFrom(Direction.TOP);
}
if (y == this.height - 1) {
tile.preventDiggingToOrFrom(Direction.BOTTOM);
}
}
private void generate() {
new Generator().run();
}
private class Generator {
private final Deque<Position> positions = new LinkedList<>();
void run() {
this.preDig();
this.dig();
this.postDig();
}
private void preDig() {
final Tile endTile = Labyrinth.this.getEndTile();
endTile.enableDiggingToOrFrom(Direction.BOTTOM);
endTile.digFrom(Direction.BOTTOM);
this.positions.push(Labyrinth.this.end);
}
private void dig() {
while (!this.positions.isEmpty()) {
final Position currentPosition = this.positions.peek();
final Tile currentTile = Labyrinth.this.getTileAt(currentPosition).get();
final Option<Direction> directionToDigTo = currentTile.getRandomAvailableDirection(Labyrinth.this.random);
if (directionToDigTo.isDefined()) {
final Direction digTo = directionToDigTo.get();
final Direction digFrom = digTo.invert();
final Position neighborPosition = currentPosition.move(digTo);
final Tile neighborTile = Labyrinth.this.getTileAt(neighborPosition).get();
if (currentTile.digTo(digTo) && neighborTile.digFrom(digFrom)) {
// all ok!
this.positions.push(neighborPosition);
if (neighborPosition.equals(Labyrinth.this.start)) {
this.markSolution();
}
} else {
// Hm, didn't work.
currentTile.undigTo(digTo);
currentTile.preventDiggingToOrFrom(digTo);
}
} else {
this.positions.pop();
}
}
}
private void markSolution() {
this.positions.forEach(position -> Labyrinth.this.getTileAt(position).get().setSolution());
}
private void postDig() {
final Tile startTile = Labyrinth.this.getStartTile();
startTile.enableDiggingToOrFrom(Direction.TOP);
startTile.digTo(Direction.TOP);
}
}
}

View file

@ -0,0 +1,27 @@
package ch.fritteli.labyrinth.generator.model;
import lombok.NonNull;
import lombok.Value;
import lombok.With;
@Value
@With
public class Position {
int x;
int y;
public Position move(@NonNull final Direction direction) {
switch (direction) {
case BOTTOM:
return this.withY(this.y + 1);
case LEFT:
return this.withX(this.x - 1);
case RIGHT:
return this.withX(this.x + 1);
case TOP:
return this.withY(this.y - 1);
default:
throw new IllegalStateException("Programming error: Not all Direction enum values covered in Position#move(Direction)!");
}
}
}

View file

@ -1,13 +1,13 @@
package ch.fritteli.maze.generator.model;
package ch.fritteli.labyrinth.generator.model;
import io.vavr.collection.Vector;
import io.vavr.collection.Stream;
import io.vavr.control.Option;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.ToString;
import lombok.experimental.FieldDefaults;
import org.jetbrains.annotations.NotNull;
import java.util.EnumSet;
import java.util.Random;
@ -17,7 +17,6 @@ import java.util.Random;
@ToString
public class Tile {
final Walls walls = new Walls();
@EqualsAndHashCode.Exclude
boolean visited = false;
@Getter
boolean solution = false;
@ -33,24 +32,24 @@ public class Tile {
* @param walls
* @param solution
*/
private Tile(@NotNull final EnumSet<Direction> walls, final boolean solution) {
private Tile(@NonNull final EnumSet<Direction> walls, final boolean solution) {
for (final Direction direction : walls) {
this.walls.set(direction);
this.walls.seal(direction);
this.walls.harden(direction);
}
this.visited = true;
this.solution = solution;
}
public void preventDiggingToOrFrom(@NotNull final Direction direction) {
this.walls.seal(direction);
public void preventDiggingToOrFrom(@NonNull final Direction direction) {
this.walls.harden(direction);
}
public void enableDiggingToOrFrom(@NotNull final Direction direction) {
this.walls.unseal(direction);
public void enableDiggingToOrFrom(@NonNull final Direction direction) {
this.walls.unharden(direction);
}
public boolean digFrom(@NotNull final Direction direction) {
public boolean digFrom(@NonNull final Direction direction) {
if (this.visited) {
return false;
}
@ -58,34 +57,24 @@ public class Tile {
return this.walls.clear(direction);
}
public boolean digTo(@NotNull final Direction direction) {
public boolean digTo(@NonNull final Direction direction) {
return this.walls.clear(direction);
}
public void undigTo(@NotNull final Direction direction) {
public void undigTo(@NonNull final Direction direction) {
this.walls.set(direction);
}
@NotNull
public EnumSet<Direction> getOpenDirections() {
return this.walls.getOpen();
}
@NotNull
public Option<Direction> getRandomAvailableDirection(@NotNull final Random random) {
final EnumSet<Direction> availableDirections = this.walls.getUnsealedSet();
public Option<Direction> getRandomAvailableDirection(@NonNull final Random random) {
final Stream<Direction> availableDirections = this.walls.getUnhardenedSet();
if (availableDirections.isEmpty()) {
return Option.none();
}
if (availableDirections.size() == 1) {
return Option.some(availableDirections.iterator().next());
}
final Vector<Direction> directions = Vector.ofAll(availableDirections);
final int index = random.nextInt(directions.size());
return Option.of(directions.get(index));
final int index = random.nextInt(availableDirections.length());
return Option.of(availableDirections.get(index));
}
public boolean hasWallAt(@NotNull final Direction direction) {
public boolean hasWallAt(@NonNull final Direction direction) {
return this.walls.isSet(direction);
}

View file

@ -0,0 +1,54 @@
package ch.fritteli.labyrinth.generator.model;
import io.vavr.collection.Stream;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.ToString;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
@EqualsAndHashCode
@ToString
public class Walls {
private final SortedSet<Direction> directions = new TreeSet<>();
private final Set<Direction> hardened = new HashSet<>();
public void set(@NonNull final Direction direction) {
this.directions.add(direction);
}
public void setAll() {
this.directions.addAll(EnumSet.allOf(Direction.class));
}
public boolean clear(@NonNull final Direction direction) {
if (this.hardened.contains(direction)) {
return false;
}
return this.directions.remove(direction);
}
public boolean isSet(@NonNull final Direction direction) {
return this.directions.contains(direction);
}
public Stream<Direction> getUnhardenedSet() {
return Stream.ofAll(this.directions)
.removeAll(this.hardened);
}
public void harden(@NonNull final Direction direction) {
if (!this.directions.contains(direction)) {
throw new IllegalStateException("Trying to harden cleared Direction: " + direction);
}
this.hardened.add(direction);
}
public void unharden(@NonNull final Direction direction) {
this.hardened.remove(direction);
}
}

View file

@ -0,0 +1,9 @@
package ch.fritteli.labyrinth.generator.renderer;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import lombok.NonNull;
public interface Renderer<T> {
@NonNull
T render(@NonNull final Labyrinth labyrinth);
}

View file

@ -1,27 +1,27 @@
package ch.fritteli.maze.generator.renderer.html;
package ch.fritteli.labyrinth.generator.renderer.html;
import ch.fritteli.maze.generator.model.Direction;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Tile;
import ch.fritteli.labyrinth.generator.model.Direction;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.model.Tile;
import io.vavr.collection.HashSet;
import io.vavr.collection.Set;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
class Generator {
private final Maze maze;
private final Labyrinth labyrinth;
private int y = 0;
boolean hasNext() {
return this.y < this.maze.getHeight();
return this.y < this.labyrinth.getHeight();
}
String next() {
StringBuilder sb = new StringBuilder("<tr>");
for (int x = 0; x < this.maze.getWidth(); x++) {
final Tile currentTile = this.maze.getTileAt(x, this.y).get();
for (int x = 0; x < this.labyrinth.getWidth(); x++) {
final Tile currentTile = this.labyrinth.getTileAt(x, this.y).get();
sb.append("<td class=\"");
sb.append(this.getClasses(currentTile).mkString(" "));
sb.append("\">&nbsp;</td>");
@ -31,7 +31,7 @@ class Generator {
return sb.toString();
}
private Set<String> getClasses(@NotNull final Tile tile) {
private Set<String> getClasses(@NonNull final Tile tile) {
Set<String> result = HashSet.empty();
if (tile.hasWallAt(Direction.TOP)) {
result = result.add("top");

View file

@ -0,0 +1,65 @@
package ch.fritteli.labyrinth.generator.renderer.html;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.renderer.Renderer;
import lombok.NonNull;
public class HTMLRenderer implements Renderer<String> {
private static final String POSTAMBLE = "</body></html>";
private HTMLRenderer() {
}
@NonNull
public static HTMLRenderer newInstance() {
return new HTMLRenderer();
}
@NonNull
@Override
public String render(@NonNull final Labyrinth labyrinth) {
if (labyrinth.getWidth() == 0 || labyrinth.getHeight() == 0) {
return this.getPreamble(labyrinth) + POSTAMBLE;
}
final Generator generator = new Generator(labyrinth);
final StringBuilder sb = new StringBuilder(this.getPreamble(labyrinth));
sb.append("<table>");
while (generator.hasNext()) {
sb.append(generator.next());
}
sb.append("</table>");
sb.append(POSTAMBLE);
return sb.toString();
}
private String getPreamble(@NonNull final Labyrinth labyrinth) {
return "<!DOCTYPE html><html lang=\"en\">" +
"<head>" +
"<title>Labyrinth " + labyrinth.getWidth() + "x" + labyrinth.getHeight() + ", ID " + labyrinth.getRandomSeed() + "</title>" +
"<meta charset=\"utf-8\">" +
"<style>" +
"table{border-collapse:collapse;}" +
"td{border:0 solid black;height:1em;width:1em;}" +
"td.top{border-top-width:1px;}" +
"td.right{border-right-width:1px;}" +
"td.bottom{border-bottom-width:1px;}" +
"td.left{border-left-width:1px;}" +
"</style>" +
"<script>" +
"let solution = false;" +
"function toggleSolution() {" +
"let stylesheet = document.styleSheets[0];" +
"if(solution){" +
"stylesheet.deleteRule(0);" +
"}else{" +
"stylesheet.insertRule(\"td.solution{background-color:lightgray;}\", 0);" +
"}" +
"solution = !solution;" +
"}" +
"</script>" +
"</head>" +
"<body>" +
"<input type=\"checkbox\" onclick=\"toggleSolution()\">show solution</input>";
}
}

View file

@ -1,12 +1,12 @@
package ch.fritteli.maze.generator.renderer.htmlfile;
package ch.fritteli.labyrinth.generator.renderer.htmlfile;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.renderer.Renderer;
import ch.fritteli.maze.generator.renderer.html.HTMLRenderer;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.renderer.Renderer;
import ch.fritteli.labyrinth.generator.renderer.html.HTMLRenderer;
import io.vavr.control.Option;
import io.vavr.control.Try;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
@ -17,19 +17,19 @@ import java.util.NoSuchElementException;
@Slf4j
public class HTMLFileRenderer implements Renderer<Path> {
@NotNull
@NonNull
private static final HTMLRenderer HTML_RENDERER = HTMLRenderer.newInstance();
@NotNull
@NonNull
private Option<Path> targetFile;
private HTMLFileRenderer() {
this.targetFile = Try
.of(() -> Files.createTempFile("maze_", ".html"))
.of(() -> Files.createTempFile("labyrinth_", ".html"))
.onFailure(ex -> log.error("Unable to set default target file.", ex))
.toOption();
}
@NotNull
@NonNull
public static HTMLFileRenderer newInstance() {
return new HTMLFileRenderer();
}
@ -40,15 +40,15 @@ public class HTMLFileRenderer implements Renderer<Path> {
.exists(File::canWrite);
}
@NotNull
public HTMLFileRenderer setTargetFile(@NotNull final Path targetFile) {
@NonNull
public HTMLFileRenderer setTargetFile(@NonNull final Path targetFile) {
this.targetFile = Option.of(targetFile);
return this;
}
@NotNull
@NonNull
@Override
public Path render(@NotNull final Maze maze) {
public Path render(@NonNull final Labyrinth labyrinth) {
if (!this.isTargetFileDefinedAndWritable()) {
try {
Files.createFile(this.targetFile.get());
@ -56,7 +56,7 @@ public class HTMLFileRenderer implements Renderer<Path> {
throw new IllegalArgumentException("Cannot write to target file.", e);
}
}
final String html = HTML_RENDERER.render(maze);
final String html = HTML_RENDERER.render(labyrinth);
final Path targetFile = this.targetFile.get();
try {
Files.writeString(targetFile, html, StandardCharsets.UTF_8);

View file

@ -1,10 +1,15 @@
package ch.fritteli.maze.generator.renderer.pdf;
package ch.fritteli.labyrinth.generator.renderer.pdf;
import ch.fritteli.maze.generator.model.Direction;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import ch.fritteli.maze.generator.model.Tile;
import ch.fritteli.labyrinth.generator.model.Direction;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.model.Position;
import ch.fritteli.labyrinth.generator.model.Tile;
import io.vavr.control.Option;
import java.awt.BasicStroke;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
@ -13,35 +18,30 @@ import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@RequiredArgsConstructor
@Slf4j
class Generator {
@NotNull
private final Maze maze;
@NonNull
private final Labyrinth labyrinth;
@NotNull
@NonNull
public ByteArrayOutputStream generate() {
final float pageWidth = this.maze.getWidth() * PDFRenderer.SCALE + 2 * PDFRenderer.MARGIN;
final float pageHeight = this.maze.getHeight() * PDFRenderer.SCALE + 2 * PDFRenderer.MARGIN;
final float pageWidth = this.labyrinth.getWidth() * PDFRenderer.SCALE + 2 * PDFRenderer.MARGIN;
final float pageHeight = this.labyrinth.getHeight() * PDFRenderer.SCALE + 2 * PDFRenderer.MARGIN;
final PDDocument pdDocument = new PDDocument();
final PDDocumentInformation info = new PDDocumentInformation();
info.setTitle("Maze %sx%s, ID %s (%s)".formatted(this.maze.getWidth(), this.maze.getHeight(), this.maze.getRandomSeed(), this.maze.getAlgorithm()));
info.setTitle("Labyrinth %sx%s, ID %s".formatted(this.labyrinth.getWidth(), this.labyrinth.getHeight(), this.labyrinth.getRandomSeed()));
pdDocument.setDocumentInformation(info);
final PDPage puzzlePage = new PDPage(new PDRectangle(pageWidth, pageHeight));
final PDPage solutionPage = new PDPage(new PDRectangle(pageWidth, pageHeight));
pdDocument.addPage(puzzlePage);
pdDocument.addPage(solutionPage);
try (final PDPageContentStream puzzlePageContentStream = new PDPageContentStream(pdDocument, puzzlePage);
final PDPageContentStream solutionPageContentStream = new PDPageContentStream(pdDocument, solutionPage)) {
final PDPageContentStream solutionPageContentStream = new PDPageContentStream(pdDocument, solutionPage)) {
setUpPageContentStream(puzzlePageContentStream);
setUpPageContentStream(solutionPageContentStream);
this.drawHorizontalLines(puzzlePageContentStream, solutionPageContentStream);
@ -60,7 +60,7 @@ class Generator {
return output;
}
private void setUpPageContentStream(@NotNull final PDPageContentStream pageContentStream) throws IOException {
private void setUpPageContentStream(@NonNull final PDPageContentStream pageContentStream) throws IOException {
pageContentStream.setLineCapStyle(BasicStroke.CAP_ROUND);
pageContentStream.setLineJoinStyle(BasicStroke.JOIN_ROUND);
pageContentStream.setLineWidth(1.0f);
@ -68,15 +68,15 @@ class Generator {
pageContentStream.setNonStrokingColor(Color.BLACK);
}
private void drawHorizontalLines(@NotNull final PDPageContentStream... contentStreams) throws IOException {
private void drawHorizontalLines(@NonNull final PDPageContentStream... contentStreams) throws IOException {
// PDF has the origin in the lower left corner. We want it in the upper left corner, hence some magic is required.
Coordinate coordinate = new Coordinate(0f, 0f);
// Draw the TOP borders of all tiles.
for (int y = 0; y < this.maze.getHeight(); y++) {
for (int y = 0; y < this.labyrinth.getHeight(); y++) {
boolean isPainting = false;
coordinate = coordinate.withY(y);
for (int x = 0; x < this.maze.getWidth(); x++) {
final Tile currentTile = this.maze.getTileAt(x, y).get();
for (int x = 0; x < this.labyrinth.getWidth(); x++) {
final Tile currentTile = this.labyrinth.getTileAt(x, y).get();
coordinate = coordinate.withX(x);
if (currentTile.hasWallAt(Direction.TOP)) {
if (!isPainting) {
@ -96,7 +96,7 @@ class Generator {
}
}
if (isPainting) {
coordinate = coordinate.withX(this.maze.getWidth());
coordinate = coordinate.withX(this.labyrinth.getWidth());
for (final PDPageContentStream contentStream : contentStreams) {
contentStream.lineTo(coordinate.getX(), coordinate.getY());
contentStream.stroke();
@ -105,10 +105,10 @@ class Generator {
}
// Draw the BOTTOM border of the last row of tiles.
boolean isPainting = false;
int y = this.maze.getHeight();
coordinate = coordinate.withY(this.maze.getHeight());
for (int x = 0; x < this.maze.getWidth(); x++) {
final Tile currentTile = this.maze.getTileAt(x, y - 1).get();
int y = this.labyrinth.getHeight();
coordinate = coordinate.withY(this.labyrinth.getHeight());
for (int x = 0; x < this.labyrinth.getWidth(); x++) {
final Tile currentTile = this.labyrinth.getTileAt(x, y - 1).get();
coordinate = coordinate.withX(x);
if (currentTile.hasWallAt(Direction.BOTTOM)) {
if (!isPainting) {
@ -128,7 +128,7 @@ class Generator {
}
}
if (isPainting) {
coordinate = coordinate.withX(this.maze.getWidth());
coordinate = coordinate.withX(this.labyrinth.getWidth());
for (final PDPageContentStream contentStream : contentStreams) {
contentStream.lineTo(coordinate.getX(), coordinate.getY());
contentStream.stroke();
@ -136,15 +136,15 @@ class Generator {
}
}
private void drawVerticalLines(@NotNull final PDPageContentStream... contentStreams) throws IOException {
private void drawVerticalLines(@NonNull final PDPageContentStream... contentStreams) throws IOException {
// PDF has the origin in the lower left corner. We want it in the upper left corner, hence some magic is required.
Coordinate coordinate = new Coordinate(0f, 0f);
// Draw the LEFT borders of all tiles.
for (int x = 0; x < this.maze.getWidth(); x++) {
for (int x = 0; x < this.labyrinth.getWidth(); x++) {
boolean isPainting = false;
coordinate = coordinate.withX(x);
for (int y = 0; y < this.maze.getHeight(); y++) {
final Tile currentTile = this.maze.getTileAt(x, y).get();
for (int y = 0; y < this.labyrinth.getHeight(); y++) {
final Tile currentTile = this.labyrinth.getTileAt(x, y).get();
coordinate = coordinate.withY(y);
if (currentTile.hasWallAt(Direction.LEFT)) {
if (!isPainting) {
@ -164,7 +164,7 @@ class Generator {
}
}
if (isPainting) {
coordinate = coordinate.withY(this.maze.getHeight());
coordinate = coordinate.withY(this.labyrinth.getHeight());
for (final PDPageContentStream contentStream : contentStreams) {
contentStream.lineTo(coordinate.getX(), coordinate.getY());
contentStream.stroke();
@ -173,10 +173,10 @@ class Generator {
}
// Draw the RIGHT border of the last column of tiles.
boolean isPainting = false;
int x = this.maze.getWidth();
coordinate = coordinate.withX(this.maze.getWidth());
for (int y = 0; y < this.maze.getHeight(); y++) {
final Tile currentTile = this.maze.getTileAt(x - 1, y).get();
int x = this.labyrinth.getWidth();
coordinate = coordinate.withX(this.labyrinth.getWidth());
for (int y = 0; y < this.labyrinth.getHeight(); y++) {
final Tile currentTile = this.labyrinth.getTileAt(x - 1, y).get();
coordinate = coordinate.withY(y);
if (currentTile.hasWallAt(Direction.RIGHT)) {
if (!isPainting) {
@ -196,7 +196,7 @@ class Generator {
}
}
if (isPainting) {
coordinate = coordinate.withY(this.maze.getHeight());
coordinate = coordinate.withY(this.labyrinth.getHeight());
for (final PDPageContentStream contentStream : contentStreams) {
contentStream.lineTo(coordinate.getX(), coordinate.getY());
contentStream.stroke();
@ -204,36 +204,36 @@ class Generator {
}
}
private void drawSolution(@NotNull final PDPageContentStream pageContentStream) throws IOException {
private void drawSolution(@NonNull final PDPageContentStream pageContentStream) throws IOException {
// Draw the solution in red
pageContentStream.setStrokingColor(Color.RED);
// PDF has the origin in the lower left corner. We want it in the upper left corner, hence some magic is required.
final Position end = this.maze.getEnd();
Position currentPosition = this.maze.getStart();
final Position end = this.labyrinth.getEnd();
Position currentPosition = this.labyrinth.getStart();
Position previousPosition = null;
SolutionCoordinate coordinate = new SolutionCoordinate(currentPosition.x(), currentPosition.y());
SolutionCoordinate coordinate = new SolutionCoordinate(currentPosition.getX(), currentPosition.getY());
pageContentStream.moveTo(coordinate.getX(), coordinate.getY());
do {
Position newCurrent = this.findNextSolutionPosition(previousPosition, currentPosition);
previousPosition = currentPosition;
currentPosition = newCurrent;
coordinate = new SolutionCoordinate(currentPosition.x(), currentPosition.y());
coordinate = new SolutionCoordinate(currentPosition.getX(), currentPosition.getY());
pageContentStream.lineTo(coordinate.getX(), coordinate.getY());
} while (!currentPosition.equals(end));
pageContentStream.stroke();
}
@NotNull
private Position findNextSolutionPosition(@Nullable final Position previousPosition, @NotNull final Position currentPosition) {
final Tile currentTile = this.maze.getTileAt(currentPosition).get();
@NonNull
private Position findNextSolutionPosition(@Nullable final Position previousPosition, @NonNull final Position currentPosition) {
final Tile currentTile = this.labyrinth.getTileAt(currentPosition).get();
for (final Direction direction : Direction.values()) {
if (!currentTile.hasWallAt(direction)) {
final Position position = currentPosition.move(direction);
final Option<Tile> tileAtPosition = this.maze.getTileAt(position);
final Option<Tile> tileAtPosition = this.labyrinth.getTileAt(position);
if (position.equals(previousPosition)) {
continue;
}
if (tileAtPosition.exists(Tile::isSolution)) {
if (tileAtPosition.map(Tile::isSolution).getOrElse(false)) {
return position;
}
}
@ -265,7 +265,7 @@ class Generator {
}
private float calcY(final int y) {
return (Generator.this.maze.getHeight() - y) * PDFRenderer.SCALE + PDFRenderer.MARGIN;
return (Generator.this.labyrinth.getHeight() - y) * PDFRenderer.SCALE + PDFRenderer.MARGIN;
}
}
@ -285,7 +285,7 @@ class Generator {
}
private float calcY(final int y) {
return (Generator.this.maze.getHeight() - y) * PDFRenderer.SCALE - PDFRenderer.SCALE / 2 + PDFRenderer.MARGIN;
return (Generator.this.labyrinth.getHeight() - y) * PDFRenderer.SCALE - PDFRenderer.SCALE / 2 + PDFRenderer.MARGIN;
}
}
}

View file

@ -1,10 +1,9 @@
package ch.fritteli.maze.generator.renderer.pdf;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.renderer.Renderer;
import org.jetbrains.annotations.NotNull;
package ch.fritteli.labyrinth.generator.renderer.pdf;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.renderer.Renderer;
import java.io.ByteArrayOutputStream;
import lombok.NonNull;
public class PDFRenderer implements Renderer<ByteArrayOutputStream> {
static final float MARGIN = 10;
@ -13,15 +12,15 @@ public class PDFRenderer implements Renderer<ByteArrayOutputStream> {
private PDFRenderer() {
}
@NotNull
@NonNull
public static PDFRenderer newInstance() {
return new PDFRenderer();
}
@NotNull
@NonNull
@Override
public ByteArrayOutputStream render(@NotNull final Maze maze) {
final Generator generator = new Generator(maze);
public ByteArrayOutputStream render(@NonNull final Labyrinth labyrinth) {
final Generator generator = new Generator(labyrinth);
return generator.generate();
}
}

View file

@ -1,36 +1,35 @@
package ch.fritteli.maze.generator.renderer.pdffile;
package ch.fritteli.labyrinth.generator.renderer.pdffile;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.renderer.Renderer;
import ch.fritteli.maze.generator.renderer.pdf.PDFRenderer;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.renderer.Renderer;
import ch.fritteli.labyrinth.generator.renderer.pdf.PDFRenderer;
import io.vavr.control.Option;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.NoSuchElementException;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PDFFileRenderer implements Renderer<Path> {
@NotNull
@NonNull
private static final PDFRenderer PDF_RENDERER = PDFRenderer.newInstance();
@NotNull
@NonNull
private Option<Path> targetFile;
private PDFFileRenderer() {
this.targetFile = Try
.of(() -> Files.createTempFile("maze_", ".pdf"))
.of(() -> Files.createTempFile("labyrinth_", ".pdf"))
.onFailure(ex -> log.error("Unable to set default target file.", ex))
.toOption();
}
@NotNull
@NonNull
public static PDFFileRenderer newInstance() {
return new PDFFileRenderer();
}
@ -41,15 +40,15 @@ public class PDFFileRenderer implements Renderer<Path> {
.exists(File::canWrite);
}
@NotNull
public PDFFileRenderer setTargetFile(@NotNull final Path targetFile) {
@NonNull
public PDFFileRenderer setTargetFile(@NonNull final Path targetFile) {
this.targetFile = Option.of(targetFile);
return this;
}
@NotNull
@NonNull
@Override
public Path render(@NotNull final Maze maze) {
public Path render(@NonNull final Labyrinth labyrinth) {
if (!this.isTargetFileDefinedAndWritable()) {
try {
Files.createFile(this.targetFile.get());
@ -57,7 +56,7 @@ public class PDFFileRenderer implements Renderer<Path> {
throw new IllegalArgumentException("Cannot write to target file.", e);
}
}
final ByteArrayOutputStream bytes = PDF_RENDERER.render(maze);
final ByteArrayOutputStream bytes = PDF_RENDERER.render(labyrinth);
final Path outputFile = this.targetFile.get();
try {
bytes.writeTo(Files.newOutputStream(outputFile));

View file

@ -1,4 +1,4 @@
package ch.fritteli.maze.generator.renderer.text;
package ch.fritteli.labyrinth.generator.renderer.text;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;

View file

@ -1,17 +1,17 @@
package ch.fritteli.maze.generator.renderer.text;
package ch.fritteli.labyrinth.generator.renderer.text;
import ch.fritteli.maze.generator.model.Direction;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Tile;
import ch.fritteli.labyrinth.generator.model.Direction;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.model.Tile;
import io.vavr.control.Option;
import lombok.AccessLevel;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
class Generator {
@NotNull
private final Maze maze;
@NonNull
private final Labyrinth labyrinth;
private final boolean renderSolution;
private int x = 0;
private int y = 0;
@ -25,21 +25,30 @@ class Generator {
private int line = 0;
boolean hasNext() {
return this.y < this.maze.getHeight();
return this.y < this.labyrinth.getHeight();
}
String next() {
final Tile currentTile = this.maze.getTileAt(this.x, this.y).get();
final Option<Tile> topTile = this.maze.getTileAt(this.x, this.y - 1);
final Option<Tile> rightTile = this.maze.getTileAt(this.x + 1, this.y);
final Option<Tile> bottomTile = this.maze.getTileAt(this.x, this.y + 1);
final Option<Tile> leftTile = this.maze.getTileAt(this.x - 1, this.y);
final String s = switch (this.line) {
case 0 -> this.renderTopLine(currentTile, leftTile, topTile);
case 1 -> this.renderCenterLine(currentTile, topTile, rightTile, bottomTile, leftTile);
case 2 -> this.renderBottomLine(currentTile, leftTile);
default -> "";
};
final Tile currentTile = this.labyrinth.getTileAt(this.x, this.y).get();
final Option<Tile> topTile = this.labyrinth.getTileAt(this.x, this.y - 1);
final Option<Tile> rightTile = this.labyrinth.getTileAt(this.x + 1, this.y);
final Option<Tile> bottomTile = this.labyrinth.getTileAt(this.x, this.y + 1);
final Option<Tile> leftTile = this.labyrinth.getTileAt(this.x - 1, this.y);
final String s;
switch (this.line) {
case 0:
s = this.renderTopLine(currentTile, leftTile, topTile);
break;
case 1:
s = this.renderCenterLine(currentTile, topTile, rightTile, bottomTile, leftTile);
break;
case 2:
s = this.renderBottomLine(currentTile, leftTile);
break;
default:
s = "";
break;
}
this.prepareNextStep();
return s;
}
@ -47,13 +56,13 @@ class Generator {
private void prepareNextStep() {
// do some magic ...
this.x++;
if (this.x == this.maze.getWidth()) {
if (this.x == this.labyrinth.getWidth()) {
// Reached the end of the row?
// On to the next line then!
this.x = 0;
this.line++;
}
if (this.line == 2 && this.y < this.maze.getHeight() - 1) {
if (this.line == 2 && this.y < this.labyrinth.getHeight() - 1) {
// Finished rendering the center line, and more rows available?
// On to the next row then!
this.line = 0;
@ -67,7 +76,7 @@ class Generator {
}
}
private String renderTopLine(@NotNull final Tile currentTile, @NotNull final Option<Tile> leftTile, @NotNull final Option<Tile> topTile) {
private String renderTopLine(@NonNull final Tile currentTile, @NonNull final Option<Tile> leftTile, @NonNull final Option<Tile> topTile) {
final CharDefinition charDef1 = new CharDefinition();
final CharDefinition charDef2 = new CharDefinition();
final CharDefinition charDef3 = new CharDefinition();
@ -97,17 +106,17 @@ class Generator {
charDef3.up();
}
result = charDef1.toString() + charDef2;
if (this.x == this.maze.getWidth() - 1) {
if (this.x == this.labyrinth.getWidth() - 1) {
result += charDef3 + "\n";
}
return result;
}
private String renderCenterLine(@NotNull final Tile currentTile,
@NotNull final Option<Tile> topTile,
@NotNull final Option<Tile> rightTile,
@NotNull final Option<Tile> bottomTile,
@NotNull final Option<Tile> leftTile) {
private String renderCenterLine(@NonNull final Tile currentTile,
@NonNull final Option<Tile> topTile,
@NonNull final Option<Tile> rightTile,
@NonNull final Option<Tile> bottomTile,
@NonNull final Option<Tile> leftTile) {
final CharDefinition charDef1 = new CharDefinition();
final CharDefinition charDef2 = new CharDefinition();
final CharDefinition charDef3 = new CharDefinition();
@ -144,14 +153,14 @@ class Generator {
result = charDef1.toString() + charDef2;
if (this.x == this.maze.getWidth() - 1) {
if (this.x == this.labyrinth.getWidth() - 1) {
result += charDef3 + "\n";
}
return result;
}
private String renderBottomLine(@NotNull final Tile currentTile, @NotNull final Option<Tile> leftTile) {
private String renderBottomLine(@NonNull final Tile currentTile, @NonNull final Option<Tile> leftTile) {
String result;
final CharDefinition charDef1 = new CharDefinition();
final CharDefinition charDef2 = new CharDefinition();
@ -178,21 +187,21 @@ class Generator {
result = charDef1.toString() + charDef2;
if (this.x == this.maze.getWidth() - 1) {
if (this.x == this.labyrinth.getWidth() - 1) {
result += charDef3;
}
return result;
}
private boolean hasWallAt(@NotNull final Option<Tile> tile, @NotNull final Direction direction) {
private boolean hasWallAt(@NonNull final Option<Tile> tile, @NonNull final Direction direction) {
return tile.map(t -> t.hasWallAt(direction)).getOrElse(false);
}
private boolean isSolution(@NotNull final Tile tile) {
return this.renderSolution && tile.isSolution();
private boolean isSolution(@NonNull final Tile tile) {
return this.renderSolution && tile != null && tile.isSolution();
}
private boolean isSolution(@NotNull final Option<Tile> tile) {
private boolean isSolution(@NonNull final Option<Tile> tile) {
return this.renderSolution && tile.map(Tile::isSolution).getOrElse(false);
}
}

View file

@ -1,8 +1,8 @@
package ch.fritteli.maze.generator.renderer.text;
package ch.fritteli.labyrinth.generator.renderer.text;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.renderer.Renderer;
import org.jetbrains.annotations.NotNull;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.renderer.Renderer;
import lombok.NonNull;
public class TextRenderer implements Renderer<String> {
private boolean renderSolution;
@ -11,24 +11,24 @@ public class TextRenderer implements Renderer<String> {
this.renderSolution = false;
}
@NotNull
@NonNull
public static TextRenderer newInstance() {
return new TextRenderer();
}
@NotNull
@NonNull
public TextRenderer setRenderSolution(final boolean renderSolution) {
this.renderSolution = renderSolution;
return this;
}
@NotNull
@NonNull
@Override
public String render(@NotNull final Maze maze) {
if (maze.getWidth() == 0 || maze.getHeight() == 0) {
public String render(@NonNull final Labyrinth labyrinth) {
if (labyrinth.getWidth() == 0 || labyrinth.getHeight() == 0) {
return "";
}
final Generator generator = new Generator(maze, this.renderSolution);
final Generator generator = new Generator(labyrinth, this.renderSolution);
final StringBuilder sb = new StringBuilder();
while (generator.hasNext()) {
sb.append(generator.next());

View file

@ -1,38 +1,39 @@
package ch.fritteli.maze.generator.renderer.textfile;
package ch.fritteli.labyrinth.generator.renderer.textfile;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.renderer.Renderer;
import ch.fritteli.maze.generator.renderer.text.TextRenderer;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.renderer.Renderer;
import ch.fritteli.labyrinth.generator.renderer.text.TextRenderer;
import io.vavr.collection.List;
import io.vavr.control.Option;
import io.vavr.control.Try;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.NoSuchElementException;
@Slf4j
public class TextFileRenderer implements Renderer<List<Path>> {
@NotNull
@NonNull
private static final TextRenderer TEXT_RENDERER = TextRenderer.newInstance();
@NotNull
private Option<Path> targetMazeFile;
@NotNull
@NonNull
private Option<Path> targetLabyrinthFile;
@NonNull
private Option<Path> targetSolutionFile;
private TextFileRenderer() {
this.targetMazeFile = Try
.of(() -> Files.createTempFile("maze_", ".txt"))
this.targetLabyrinthFile = Try
.of(() -> Files.createTempFile("labyrinth_", ".txt"))
.onFailure(ex -> log.error("Unable to set default target file", ex))
.toOption();
this.targetSolutionFile = this.targetMazeFile.toTry()
this.targetSolutionFile = this.targetLabyrinthFile.toTry()
.map(Path::getParent)
.flatMap(parent -> this.targetMazeFile.toTry()
.flatMap(parent -> this.targetLabyrinthFile.toTry()
.map(Path::getFileName)
.map(Path::toString)
.map(a -> a.replace(".txt", "-solution.txt"))
@ -41,13 +42,13 @@ public class TextFileRenderer implements Renderer<List<Path>> {
.toOption();
}
@NotNull
@NonNull
public static TextFileRenderer newInstance() {
return new TextFileRenderer();
}
public boolean isTargetMazeFileDefinedAndWritable() {
return this.targetMazeFile
public boolean isTargetLabyrinthFileDefinedAndWritable() {
return this.targetLabyrinthFile
.map(Path::toFile)
.exists(File::canWrite);
}
@ -58,27 +59,27 @@ public class TextFileRenderer implements Renderer<List<Path>> {
.exists(File::canWrite);
}
@NotNull
public TextFileRenderer setTargetMazeFile(@NotNull final Path targetMazeFile) {
this.targetMazeFile = Option.of(targetMazeFile);
@NonNull
public TextFileRenderer setTargetLabyrinthFile(@NonNull final Path targetLabyrinthFile) {
this.targetLabyrinthFile = Option.of(targetLabyrinthFile);
return this;
}
@NotNull
public TextFileRenderer setTargetSolutionFile(@NotNull final Path targetSolutionFile) {
@NonNull
public TextFileRenderer setTargetSolutionFile(@NonNull final Path targetSolutionFile) {
this.targetSolutionFile = Option.of(targetSolutionFile);
return this;
}
@NotNull
@NonNull
@Override
public List<Path> render(@NotNull final Maze maze) {
if (!this.isTargetMazeFileDefinedAndWritable()) {
public List<Path> render(@NonNull final Labyrinth labyrinth) {
if (!this.isTargetLabyrinthFileDefinedAndWritable()) {
try {
Files.createFile(this.targetMazeFile.get());
Files.createFile(this.targetLabyrinthFile.get());
} catch (IOException | NoSuchElementException e) {
log.error("Cannot write to target maze file.", e);
throw new IllegalArgumentException("Cannot write to target maze file.", e);
log.error("Cannot write to target labyrinth file.", e);
throw new IllegalArgumentException("Cannot write to target labyrinth file.", e);
}
}
if (!this.isTargetSolutionFileDefinedAndWritable()) {
@ -91,21 +92,21 @@ public class TextFileRenderer implements Renderer<List<Path>> {
final String text;
final String solution;
synchronized (TEXT_RENDERER) {
text = TEXT_RENDERER.setRenderSolution(false).render(maze).strip();
solution = TEXT_RENDERER.setRenderSolution(true).render(maze).strip();
text = TEXT_RENDERER.setRenderSolution(false).render(labyrinth).strip();
solution = TEXT_RENDERER.setRenderSolution(true).render(labyrinth).strip();
}
final Path targetMazeFile = this.targetMazeFile.get();
final Path targetLabyrinthFile = this.targetLabyrinthFile.get();
final Path targetSolutionFile = this.targetSolutionFile.get();
try {
Files.writeString(targetMazeFile, text);
Files.write(targetLabyrinthFile, text.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
log.error("Failed writing to file " + targetMazeFile.normalize(), e);
log.error("Failed writing to file " + targetLabyrinthFile.normalize(), e);
}
try {
Files.writeString(targetSolutionFile, solution);
Files.write(targetSolutionFile, solution.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
log.error("Failed writing to file " + targetSolutionFile.normalize());
}
return List.of(targetMazeFile, targetSolutionFile);
return List.of(targetLabyrinthFile, targetSolutionFile);
}
}

View file

@ -0,0 +1,74 @@
package ch.fritteli.labyrinth.generator.serialization;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.model.Tile;
import lombok.NonNull;
import java.io.ByteArrayInputStream;
public class LabyrinthInputStream extends ByteArrayInputStream {
public LabyrinthInputStream(@NonNull final byte[] buf) {
super(buf);
}
public long readLong() {
long result = 0;
result |= ((long) this.readInt()) << 32;
result |= 0xffffffffL & this.readInt();
return result;
}
public int readInt() {
int result = 0;
result |= (0xff & this.readByte()) << 24;
result |= (0xff & this.readByte()) << 16;
result |= (0xff & this.readByte()) << 8;
result |= 0xff & this.readByte();
return result;
}
public void checkHeader() {
final byte magic1 = this.readByte();
if (magic1 != SerializerDeserializer.MAGIC_BYTE_1) {
throw new IllegalArgumentException("Invalid labyrinth data.");
}
final byte magic2 = this.readByte();
if (magic2 != SerializerDeserializer.MAGIC_BYTE_2) {
throw new IllegalArgumentException("Invalid labyrinth data.");
}
final int version = this.readByte();
if (version != SerializerDeserializer.VERSION_BYTE) {
throw new IllegalArgumentException("Unknown Labyrinth data version: " + version);
}
}
public byte readByte() {
final int read = this.read();
if (read == -1) {
// end of stream reached
throw new ArrayIndexOutOfBoundsException("End of stream reached. Cannot read more bytes.");
}
return (byte) read;
}
@NonNull
public Labyrinth readLabyrinthData() {
final long randomSeed = this.readLong();
final int width = this.readInt();
final int height = this.readInt();
final Tile[][] tiles = new Tile[width][height];
for (int x = 0; x < width; x++) {
tiles[x] = new Tile[height];
}
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final byte bitmask = this.readByte();
tiles[x][y] = SerializerDeserializer.getTileForBitmask(bitmask);
}
}
return SerializerDeserializer.createLabyrinth(tiles, width, height, randomSeed);
}
}

View file

@ -0,0 +1,50 @@
package ch.fritteli.labyrinth.generator.serialization;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.model.Tile;
import lombok.NonNull;
import java.io.ByteArrayOutputStream;
public class LabyrinthOutputStream extends ByteArrayOutputStream {
public void writeHeader() {
this.writeByte(SerializerDeserializer.MAGIC_BYTE_1);
this.writeByte(SerializerDeserializer.MAGIC_BYTE_2);
this.writeByte(SerializerDeserializer.VERSION_BYTE);
}
public void writeByte(final byte value) {
this.write(value);
}
public void writeLabyrinthData(@NonNull final Labyrinth labyrinth) {
final long randomSeed = labyrinth.getRandomSeed();
final int width = labyrinth.getWidth();
final int height = labyrinth.getHeight();
this.writeLong(randomSeed);
this.writeInt(width);
this.writeInt(height);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// We .get() it, because we want to crash hard if it is not available.
final Tile tile = labyrinth.getTileAt(x, y).get();
final byte bitmask = SerializerDeserializer.getBitmaskForTile(tile);
this.writeByte(bitmask);
}
}
}
public void writeLong(final long value) {
this.writeInt((int) (value >> 32));
this.writeInt((int) value);
}
public void writeInt(final int value) {
this.write(value >> 24);
this.write(value >> 16);
this.write(value >> 8);
this.write(value);
}
}

View file

@ -0,0 +1,146 @@
package ch.fritteli.labyrinth.generator.serialization;
import ch.fritteli.labyrinth.generator.model.Direction;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import ch.fritteli.labyrinth.generator.model.Tile;
import lombok.NonNull;
import lombok.experimental.UtilityClass;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.EnumSet;
/**
* <pre>
* decimal hex bin border
* 0 0 0000 no border
* 1 1 0001 top
* 2 2 0010 right
* 3 3 0011 top+right
* 4 4 0100 bottom
* 5 5 0101 top+bottom
* 6 6 0110 right+bottom
* 7 7 0111 top+right+bottom
* 8 8 1000 left
* 9 9 1001 top+left
* 10 a 1010 right+left
* 11 b 1011 top+right+left
* 12 c 1100 bottom+left
* 13 d 1101 top+bottom+left
* 14 e 1110 right+bottom+left
* 15 f 1111 top+right+bottom+left
* </pre>
* ==&gt; bits 0..2: always 0; bit 3: 1=solution, 0=not solution; bits 4..7: encode walls
* ==&gt; first bytes are:
* <pre>
* byte hex meaning
* 00 0x1a magic
* 01 0xb1 magic
* 02 0x01 version (0x00 -> dev, 0x01 -> stable)
* 03..06 width (int)
* 07..10 height (int)
* 11..18 random seed number (long)
* 19.. tiles
* </pre>
* Extraneous space (poss. last nibble) is ignored.
*/
@UtilityClass
public class SerializerDeserializer {
final byte MAGIC_BYTE_1 = 0x1a;
final byte MAGIC_BYTE_2 = (byte) 0xb1;
final byte VERSION_BYTE = 0x01;
private final byte TOP_BIT = 0b0000_0001;
private final byte RIGHT_BIT = 0b0000_0010;
private final byte BOTTOM_BIT = 0b0000_0100;
private final byte LEFT_BIT = 0b0000_1000;
private final byte SOLUTION_BIT = 0b0001_0000;
/**
* Serializes the {@code labyrinth} into a byte array.
*
* @param labyrinth The labyrinth to be serialized.
* @return The resulting byte array.
*/
@NonNull
public byte[] serialize(@NonNull final Labyrinth labyrinth) {
final LabyrinthOutputStream stream = new LabyrinthOutputStream();
stream.writeHeader();
stream.writeLabyrinthData(labyrinth);
return stream.toByteArray();
}
/**
* Deserializes the byte array into an instance of {@link Labyrinth}.
*
* @param bytes The byte array to be deserialized.
* @return An instance of {@link Labyrinth}.
*/
@NonNull
public Labyrinth deserialize(@NonNull final byte[] bytes) {
final LabyrinthInputStream stream = new LabyrinthInputStream(bytes);
stream.checkHeader();
return stream.readLabyrinthData();
}
@NonNull
Labyrinth createLabyrinth(@NonNull final Tile[][] field, final int width, final int height, final long randomSeed) {
try {
final Constructor<Labyrinth> constructor = Labyrinth.class.getDeclaredConstructor(Tile[][].class, Integer.TYPE, Integer.TYPE, Long.TYPE);
constructor.setAccessible(true);
return constructor.newInstance(field, width, height, randomSeed);
} catch (@NonNull final NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
throw new RuntimeException("Can not deserialize Labyrinth from labyrinth data.", e);
}
}
@NonNull
private Tile createTile(@NonNull final EnumSet<Direction> walls, boolean solution) {
try {
final Constructor<Tile> constructor = Tile.class.getDeclaredConstructor(EnumSet.class, Boolean.TYPE);
constructor.setAccessible(true);
return constructor.newInstance(walls, solution);
} catch (@NonNull final NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Can not deserialize Tile from labyrinth data.", e);
}
}
byte getBitmaskForTile(@NonNull final Tile tile) {
byte bitmask = 0;
if (tile.hasWallAt(Direction.TOP)) {
bitmask |= TOP_BIT;
}
if (tile.hasWallAt(Direction.RIGHT)) {
bitmask |= RIGHT_BIT;
}
if (tile.hasWallAt(Direction.BOTTOM)) {
bitmask |= BOTTOM_BIT;
}
if (tile.hasWallAt((Direction.LEFT))) {
bitmask |= LEFT_BIT;
}
if (tile.isSolution()) {
bitmask |= SOLUTION_BIT;
}
return bitmask;
}
@NonNull
Tile getTileForBitmask(final byte bitmask) {
final EnumSet<Direction> walls = EnumSet.noneOf(Direction.class);
if ((bitmask & TOP_BIT) == TOP_BIT) {
walls.add(Direction.TOP);
}
if ((bitmask & RIGHT_BIT) == RIGHT_BIT) {
walls.add(Direction.RIGHT);
}
if ((bitmask & BOTTOM_BIT) == BOTTOM_BIT) {
walls.add(Direction.BOTTOM);
}
if ((bitmask & LEFT_BIT) == LEFT_BIT) {
walls.add(Direction.LEFT);
}
final boolean solution = (bitmask & SOLUTION_BIT) == SOLUTION_BIT;
return createTile(walls, solution);
}
}

View file

@ -1,65 +0,0 @@
package ch.fritteli.maze.generator;
import ch.fritteli.maze.generator.algorithm.RandomDepthFirst;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.renderer.html.HTMLRenderer;
import ch.fritteli.maze.generator.renderer.htmlfile.HTMLFileRenderer;
import ch.fritteli.maze.generator.renderer.json.JsonRenderer;
import ch.fritteli.maze.generator.renderer.jsonfile.JsonFileRenderer;
import ch.fritteli.maze.generator.renderer.pdffile.PDFFileRenderer;
import ch.fritteli.maze.generator.renderer.text.TextRenderer;
import ch.fritteli.maze.generator.renderer.textfile.TextFileRenderer;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import java.nio.file.Path;
import java.nio.file.Paths;
@Slf4j
@UtilityClass
public class Main {
public static void main(@NotNull final String[] args) {
final int width = 20;
final int height = 30;
final Maze maze = new Maze(width, height/*, 0*/);
new RandomDepthFirst(maze).run();
final TextRenderer textRenderer = TextRenderer.newInstance();
final HTMLRenderer htmlRenderer = HTMLRenderer.newInstance();
final JsonRenderer jsonRenderer = JsonRenderer.newInstance();
final Path userHome = Paths.get(System.getProperty("user.home"));
final String baseFilename = getBaseFilename(maze);
final TextFileRenderer textFileRenderer = TextFileRenderer.newInstance()
.setTargetMazeFile(userHome.resolve(baseFilename + ".txt"))
.setTargetSolutionFile(userHome.resolve(baseFilename + "-solution.txt"));
final HTMLFileRenderer htmlFileRenderer = HTMLFileRenderer.newInstance()
.setTargetFile(userHome.resolve(baseFilename + ".html"));
final JsonFileRenderer jsonFileRenderer = JsonFileRenderer.newInstance()
.setTargetFile(userHome.resolve(baseFilename + ".json"));
final PDFFileRenderer pdfFileRenderer = PDFFileRenderer.newInstance()
.setTargetFile(userHome.resolve(baseFilename + ".pdf"));
log.info("Maze-ID: {}", maze.getRandomSeed());
// Render Maze to stdout
log.info("Text rendering:\n{}", textRenderer.render(maze));
// Render Maze solution to stdout
log.info("Text rendering with solution:\n{}", textRenderer.setRenderSolution(true).render(maze));
// Render HTML to stdout
log.info("HTML rendering:\n{}", htmlRenderer.render(maze));
// Render JSON to stdout
log.info("JSON rendering:\n{}", jsonRenderer.render(maze));
// Render Maze and solution to (separate) files
log.info("Text rendering to file:\n{}", textFileRenderer.render(maze));
// Render HTML to file
log.info("HTML rendering to file:\n{}", htmlFileRenderer.render(maze));
// Render JSON to file
log.info("JSON rendering to file:\n{}", jsonFileRenderer.render(maze));
// Render PDF to file
log.info("PDF rendering to file:\n{}", pdfFileRenderer.render(maze));
}
private static String getBaseFilename(@NotNull final Maze maze) {
return "maze-" + maze.getWidth() + "x" + maze.getHeight() + "-" + maze.getRandomSeed();
}
}

View file

@ -1,20 +0,0 @@
package ch.fritteli.maze.generator.algorithm;
import ch.fritteli.maze.generator.model.Maze;
import org.jetbrains.annotations.NotNull;
import java.util.Random;
public abstract class AbstractMazeGeneratorAlgorithm implements MazeGeneratorAlgorithm {
@NotNull
protected final Maze maze;
@NotNull
protected final Random random;
protected AbstractMazeGeneratorAlgorithm(@NotNull final Maze maze, @NotNull final String algorithmName) {
this.maze = maze;
this.random = new Random(maze.getRandomSeed());
this.maze.setAlgorithm(algorithmName);
}
}

View file

@ -1,5 +0,0 @@
package ch.fritteli.maze.generator.algorithm;
public interface MazeGeneratorAlgorithm {
void run();
}

View file

@ -1,107 +0,0 @@
package ch.fritteli.maze.generator.algorithm;
import ch.fritteli.maze.generator.model.Direction;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import ch.fritteli.maze.generator.model.Tile;
import io.vavr.control.Option;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Deque;
import java.util.LinkedList;
public class RandomDepthFirst extends AbstractMazeGeneratorAlgorithm {
@NotNull
private final Deque<Position> positions = new LinkedList<>();
public RandomDepthFirst(@NotNull final Maze maze) {
super(maze, "Random Depth First");
}
public void run() {
this.preDig();
this.dig();
this.postDig();
}
private void preDig() {
final Position end = this.maze.getEnd();
final Direction direction = this.determineDirectionForDigging(end);
if (direction != null) {
final Tile endTile = this.maze.getEndTile();
this.digFrom(endTile, direction);
}
this.positions.push(end);
}
private void dig() {
while (!this.positions.isEmpty()) {
final Position currentPosition = this.positions.peek();
final Tile currentTile = this.maze.getTileAt(currentPosition).get();
final Option<Direction> directionToDigTo = currentTile.getRandomAvailableDirection(this.random);
if (directionToDigTo.isDefined()) {
final Direction digTo = directionToDigTo.get();
final Direction digFrom = digTo.invert();
final Position neighborPosition = currentPosition.move(digTo);
final Tile neighborTile = this.maze.getTileAt(neighborPosition).get();
if (currentTile.digTo(digTo) && neighborTile.digFrom(digFrom)) {
// all ok!
this.positions.push(neighborPosition);
if (neighborPosition.equals(this.maze.getStart())) {
this.markSolution();
}
} else {
// Hm, didn't work.
currentTile.undigTo(digTo);
currentTile.preventDiggingToOrFrom(digTo);
}
} else {
this.positions.pop();
}
}
}
private void markSolution() {
this.positions.forEach(position -> this.maze.getTileAt(position).get().setSolution());
}
private void postDig() {
final Position start = this.maze.getStart();
final Direction direction = this.determineDirectionForDigging(start);
if (direction != null) {
final Tile startTile = this.maze.getStartTile();
this.digTo(startTile, direction);
}
}
@Nullable
private Direction determineDirectionForDigging(@NotNull final Position position) {
if (position.y() == 0) {
return Direction.TOP;
}
if (position.x() == 0) {
return Direction.LEFT;
}
if (position.y() == this.maze.getHeight() - 1) {
return Direction.BOTTOM;
}
if (position.x() == this.maze.getWidth() - 1) {
return Direction.RIGHT;
}
return null;
}
private void digFrom(@NotNull final Tile tile, @NotNull final Direction direction) {
tile.enableDiggingToOrFrom(direction);
tile.digFrom(direction);
}
private void digTo(@NotNull final Tile tile, @NotNull final Direction direction) {
tile.enableDiggingToOrFrom(direction);
tile.digTo(direction);
}
}

View file

@ -1,62 +0,0 @@
package ch.fritteli.maze.generator.algorithm.wilson;
import ch.fritteli.maze.generator.model.Direction;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import org.jetbrains.annotations.NotNull;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;
public class MazeSolver {
@NotNull
private final Maze maze;
MazeSolver(@NotNull final Maze maze) {
this.maze = maze;
}
void solve() {
final Direction directionToOuterWall = Wilson.getDirectionToOuterWall(
this.maze.getStart(),
this.maze.getWidth(),
this.maze.getHeight()
);
final List<Position> solution = this.getSolution(this.maze.getStart(), directionToOuterWall);
for (Position position : solution) {
this.maze.getTileAt(position).get().setSolution();
}
}
private List<Position> getSolution(@NotNull Position position,
@NotNull Direction forbidden) {
record PathElement(@NotNull Position position,
@NotNull EnumSet<Direction> possibleDirections) {
}
final Stack<PathElement> solution = new Stack<>();
final EnumSet<Direction> directions = this.maze.getTileAt(position).get().getOpenDirections();
directions.remove(forbidden);
PathElement head = new PathElement(position, directions);
solution.push(head);
while (!head.position.equals(this.maze.getEnd())) {
if (head.possibleDirections.isEmpty()) {
solution.pop();
head = solution.peek();
} else {
final Iterator<Direction> iterator = head.possibleDirections.iterator();
final Direction direction = iterator.next();
iterator.remove();
final Position next = head.position.move(direction);
final EnumSet<Direction> openDirections = this.maze.getTileAt(next).get().getOpenDirections();
openDirections.remove(direction.invert());
head = new PathElement(next, openDirections);
solution.push(head);
}
}
return solution.stream().map(PathElement::position).collect(Collectors.toList());
}
}

View file

@ -1,91 +0,0 @@
package ch.fritteli.maze.generator.algorithm.wilson;
import ch.fritteli.maze.generator.model.Direction;
import ch.fritteli.maze.generator.model.Position;
import io.vavr.collection.List;
import io.vavr.collection.Stream;
import io.vavr.collection.Traversable;
import io.vavr.control.Option;
import org.jetbrains.annotations.NotNull;
import java.util.Random;
class Path {
private final int width;
private final int height;
@NotNull
private List<Position> positions;
Path(@NotNull final Position start, int width, int height) {
this.positions = List.of(start);
this.width = width;
this.height = height;
}
@NotNull
Position growRandom(@NotNull final Random random) {
final Position position = this.nextRandomPosition(random);
if (this.contains(position)) {
this.removeLoopUpTo(position);
return this.growRandom(random);
}
this.positions = this.positions.prepend(position);
return position;
}
@NotNull
List<Position> getPositions() {
return this.positions;
}
@NotNull
Position getStart() {
return this.positions.last();
}
@NotNull
Traversable<Direction> getMovesFromStart() {
return this.positions.reverse().sliding(2)
.flatMap(positions1 -> Option.when(
positions1.size() == 2,
// DEV-NOTE: .get() is safe here, because in the context of a path, there MUST be a direction
// from one position to the next.
() -> positions1.head().getDirectionTo(positions1.last()).get()
));
}
@NotNull
private Position nextRandomPosition(@NotNull final Random random) {
final Direction randomDirection = this.getRandomDirection(random);
final Position nextPosition = this.positions.head().move(randomDirection);
if (this.isWithinBounds(nextPosition) && !nextPosition.equals(this.positions.head())) {
return nextPosition;
}
return this.nextRandomPosition(random);
}
private boolean isWithinBounds(@NotNull final Position position) {
return position.x() >= 0 && position.x() < this.width && position.y() >= 0 && position.y() < this.height;
}
private boolean contains(@NotNull final Position position) {
return this.positions.contains(position);
}
private void removeLoopUpTo(@NotNull final Position position) {
this.positions = this.positions.dropUntil(position::equals);
}
@NotNull
private Direction getRandomDirection(@NotNull final Random random) {
final Direction[] array = Direction.values();
return array[random.nextInt(array.length)];
}
@Override
public String toString() {
return Stream.ofAll(this.positions)
.map(position -> "(%s,%s)".formatted(position.x(), position.y()))
.mkString("Path[", "->", "]");
}
}

View file

@ -1,131 +0,0 @@
package ch.fritteli.maze.generator.algorithm.wilson;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import io.vavr.Tuple;
import io.vavr.collection.Stream;
import io.vavr.collection.Traversable;
import io.vavr.control.Option;
import org.jetbrains.annotations.NotNull;
import java.util.Random;
/**
* This class will build paths such that in the end all fields of the maze are covered by exactly one path.
*/
class PathsBuilder {
private final int width;
private final int height;
@NotNull
private final Random random;
@NotNull
private final Multimap<Integer, Integer> availablePositions;
PathsBuilder(@NotNull final Maze maze,
@NotNull final Random random) {
this.width = maze.getWidth();
this.height = maze.getHeight();
this.random = random;
this.availablePositions = HashMultimap.create(this.width, this.height);
// Initialize the available positions.
for (int x = 0; x < this.width; x++) {
for (int y = 0; y < this.height; y++) {
this.availablePositions.put(x, y);
}
}
}
/**
* Create all the paths such that the maze will be completely filled and every field of it will be covered by
* exactly one path.
*
* @return A {@link Traversable} of generated {@link Path Paths}.
*/
@NotNull
Traversable<Path> buildPaths() {
this.initializeWithRandomStartingPosition();
return Stream.unfoldLeft(
this,
builder -> builder.buildPath()
.map(path -> {
builder.setPartOfMaze(path);
return Tuple.of(builder, path);
})
);
}
private void initializeWithRandomStartingPosition() {
this.popRandomPosition();
}
/**
* Creates one new path, if possible. If the maze is already filled, {@link io.vavr.control.Option.None} is
* returned.
*
* @return An {@link Option} of a new {@link Path} instance.
*/
@NotNull
private Option<Path> buildPath() {
return this.initializeNewPath()
.map(this::growPath);
}
@NotNull
private Option<Path> initializeNewPath() {
return this.popRandomPosition()
.map(position -> new Path(position, this.width, this.height));
}
/**
* Randomly grow the {@code path} until it reaches a field that is part of the maze and return it. The resulting
* path will contain no loops.
*
* @param path The {@link Path} to grow.
* @return The final {@link Path} that reaches the maze.
*/
@NotNull
private Path growPath(@NotNull final Path path) {
Position lastPosition;
do {
lastPosition = path.growRandom(this.random);
} while (this.isNotPartOfMaze(lastPosition));
return path;
}
private boolean isNotPartOfMaze(@NotNull final Position position) {
return this.availablePositions.containsEntry(position.x(), position.y());
}
private void setPartOfMaze(@NotNull final Position position) {
this.availablePositions.remove(position.x(), position.y());
}
private void setPartOfMaze(@NotNull final Path path) {
path.getPositions().forEach(this::setPartOfMaze);
}
/**
* Finds a random {@link Position}, that is not yet part of the maze, marks it as being part of the maze and returns
* it. If no position is available, {@link io.vavr.control.Option.None} is returned.
*
* @return An available position or {@link io.vavr.control.Option.None}.
*/
@NotNull
private Option<Position> popRandomPosition() {
if (this.availablePositions.isEmpty()) {
return Option.none();
}
final Integer[] keys = this.availablePositions.keySet().toArray(Integer[]::new);
final int key = keys[this.random.nextInt(keys.length)];
final Integer[] values = this.availablePositions.get(key).toArray(Integer[]::new);
final int value = values[this.random.nextInt(values.length)];
this.availablePositions.remove(key, value);
return Option.some(new Position(key, value));
}
}

View file

@ -1,96 +0,0 @@
package ch.fritteli.maze.generator.algorithm.wilson;
import ch.fritteli.maze.generator.algorithm.AbstractMazeGeneratorAlgorithm;
import ch.fritteli.maze.generator.model.Direction;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import ch.fritteli.maze.generator.model.Tile;
import io.vavr.collection.Traversable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* An implementation of <a href="https://en.wikipedia.org/wiki/Maze_generation_algorithm#Wilson's_algorithm">Wilson's Algorithm</a>.
* In short:
* <ol>
* <li>Pick random location, add to maze</li>
* <li>While locations that are not part of the maze exist, loop:
* <ol>
* <li>Pick random location that's not part of the maze</li>
* <li>Randomly walk from this location, until ...
* <ul>
* <li>... either you hit the current path, forming a loop. Then remove the entire loop and continue
* walking.</li>
* <li>... or you hit a position that is part of the maze. Then add the path to the maze and start the next
* walk.</li>
* </ul></li>
* </ol></li>
* </ol>
*/
public class Wilson extends AbstractMazeGeneratorAlgorithm {
public Wilson(@NotNull final Maze maze) {
super(maze, "Wilson");
}
@Nullable
static Direction getDirectionToOuterWall(@NotNull final Position position,
final int width,
final int height) {
if (position.y() == 0) {
return Direction.TOP;
}
if (position.y() == height - 1) {
return Direction.BOTTOM;
}
if (position.x() == 0) {
return Direction.LEFT;
}
if (position.x() == width - 1) {
return Direction.RIGHT;
}
return null;
}
@Override
public void run() {
final Traversable<Path> paths = new PathsBuilder(this.maze, this.random)
.buildPaths();
this.applyPathsToMaze(paths);
}
private void applyPathsToMaze(@NotNull final Traversable<Path> paths) {
this.openStartAndEndWalls();
paths.forEach(path -> path.getMovesFromStart()
.foldLeft(
path.getStart(),
(position, direction) -> {
this.maze.getTileAt(position).get()
.digTo(direction);
final Position next = position.move(direction);
this.maze.getTileAt(next).get()
.digTo(direction.invert());
return next;
}));
final MazeSolver solver = new MazeSolver(this.maze);
solver.solve();
}
private void openStartAndEndWalls() {
this.openWall(this.maze.getStart(), this.maze.getStartTile());
this.openWall(this.maze.getEnd(), this.maze.getEndTile());
}
private void openWall(@NotNull final Position position, @NotNull final Tile tile) {
final Direction direction = this.getDirectionToOuterWall(position);
tile.enableDiggingToOrFrom(direction);
tile.digTo(direction);
}
@Nullable
private Direction getDirectionToOuterWall(@NotNull final Position position) {
return getDirectionToOuterWall(position, this.maze.getWidth(), this.maze.getHeight());
}
}

View file

@ -1,20 +0,0 @@
package ch.fritteli.maze.generator.model;
import org.jetbrains.annotations.NotNull;
public enum Direction {
TOP,
RIGHT,
BOTTOM,
LEFT;
@NotNull
public Direction invert() {
return switch (this) {
case TOP -> BOTTOM;
case RIGHT -> LEFT;
case BOTTOM -> TOP;
case LEFT -> RIGHT;
};
}
}

View file

@ -1,163 +0,0 @@
package ch.fritteli.maze.generator.model;
import io.vavr.control.Option;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.jetbrains.annotations.NotNull;
@EqualsAndHashCode
@ToString
public class Maze {
private final Tile[][] field;
@Getter
private final int width;
@Getter
private final int height;
@Getter
private final long randomSeed;
@Getter
private final Position start;
@Getter
private final Position end;
@Getter
@Setter
private String algorithm;
public Maze(final int width, final int height) {
this(width, height, System.nanoTime());
}
public Maze(final int width, final int height, @NotNull final Position start, @NotNull final Position end) {
this(width, height, System.nanoTime(), start, end);
}
public Maze(final int width, final int height, final long randomSeed) {
this(width, height, randomSeed, new Position(0, 0), new Position(width - 1, height - 1));
}
public Maze(final int width,
final int height,
final long randomSeed,
@NotNull final Position start,
@NotNull final Position end) {
if (width <= 1 || height <= 1) {
throw new IllegalArgumentException("width and height must be >1");
}
if (start.equals(end)) {
throw new IllegalArgumentException("'start' must not be equal to 'end'");
}
if (start.x() != 0 && start.x() != width - 1 && start.y() != 0 && start.y() != height - 1) {
throw new IllegalArgumentException("'start' must be at the edge of the maze");
}
if (end.x() != 0 && end.x() != width - 1 && end.y() != 0 && end.y() != height - 1) {
throw new IllegalArgumentException("'end' must be at the edge of the maze");
}
this.width = width;
this.height = height;
this.randomSeed = randomSeed;
this.field = new Tile[width][height];
this.start = start;
this.end = end;
this.initField();
}
/**
* INTERNAL API. Exists only for deserialization. Not to be called from user code.
*/
private Maze(@NotNull final Tile[][] field, final int width, final int height, final long randomSeed) {
this.field = field;
this.width = width;
this.height = height;
this.randomSeed = randomSeed;
this.start = new Position(0, 0);
this.end = new Position(this.width - 1, this.height - 1);
}
/**
* INTERNAL API. Exists only for deserialization. Not to be called from user code.
*/
private Maze(@NotNull final Tile[][] field,
final int width,
final int height,
@NotNull final Position start,
@NotNull final Position end,
final long randomSeed) {
this.field = field;
this.width = width;
this.height = height;
this.randomSeed = randomSeed;
this.start = start;
this.end = end;
}
/**
* INTERNAL API. Exists only for deserialization. Not to be called from user code.
*/
private Maze(@NotNull final Tile[][] field,
final int width,
final int height,
@NotNull final Position start,
@NotNull final Position end,
final long randomSeed,
@NotNull final String algorithm) {
this.field = field;
this.width = width;
this.height = height;
this.randomSeed = randomSeed;
this.algorithm = algorithm;
this.start = start;
this.end = end;
}
@NotNull
public Option<Tile> getTileAt(@NotNull final Position position) {
return this.getTileAt(position.x(), position.y());
}
@NotNull
public Option<Tile> getTileAt(final int x, final int y) {
if (x < 0 || y < 0 || x >= this.width || y >= this.height) {
return Option.none();
}
return Option.of(this.field[x][y]);
}
@NotNull
public Tile getStartTile() {
return this.getTileAt(this.start).get();
}
@NotNull
public Tile getEndTile() {
return this.getTileAt(this.end).get();
}
private void initField() {
for (int x = 0; x < this.width; x++) {
this.field[x] = new Tile[this.height];
for (int y = 0; y < this.height; y++) {
final Tile tile = new Tile();
this.hardenWalls(tile, x, y);
this.field[x][y] = tile;
}
}
}
private void hardenWalls(@NotNull final Tile tile, final int x, final int y) {
if (x == 0) {
tile.preventDiggingToOrFrom(Direction.LEFT);
}
if (x == this.width - 1) {
tile.preventDiggingToOrFrom(Direction.RIGHT);
}
if (y == 0) {
tile.preventDiggingToOrFrom(Direction.TOP);
}
if (y == this.height - 1) {
tile.preventDiggingToOrFrom(Direction.BOTTOM);
}
}
}

View file

@ -1,34 +0,0 @@
package ch.fritteli.maze.generator.model;
import io.vavr.control.Option;
import lombok.With;
import org.jetbrains.annotations.NotNull;
@With
public record Position(int x, int y) {
@NotNull
public Position move(@NotNull final Direction direction) {
return switch (direction) {
case BOTTOM -> this.withY(this.y + 1);
case LEFT -> this.withX(this.x - 1);
case RIGHT -> this.withX(this.x + 1);
case TOP -> this.withY(this.y - 1);
};
}
@NotNull
public Option<Direction> getDirectionTo(@NotNull final Position position) {
final int xDiff = position.x - this.x;
final int yDiff = position.y - this.y;
return switch (xDiff) {
case -1 -> Option.when(yDiff == 0, Direction.LEFT);
case 0 -> switch (yDiff) {
case -1 -> Option.some(Direction.TOP);
case 1 -> Option.some(Direction.BOTTOM);
default -> Option.none();
};
case 1 -> Option.when(yDiff == 0, Direction.RIGHT);
default -> Option.none();
};
}
}

View file

@ -1,57 +0,0 @@
package ch.fritteli.maze.generator.model;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.jetbrains.annotations.NotNull;
import java.util.EnumSet;
@EqualsAndHashCode
@ToString
public class Walls {
private final EnumSet<Direction> directions = EnumSet.noneOf(Direction.class);
@EqualsAndHashCode.Exclude
private final EnumSet<Direction> sealed = EnumSet.noneOf(Direction.class);
public void set(@NotNull final Direction direction) {
this.directions.add(direction);
}
public void setAll() {
this.directions.addAll(EnumSet.allOf(Direction.class));
}
public boolean clear(@NotNull final Direction direction) {
if (this.sealed.contains(direction)) {
return false;
}
return this.directions.remove(direction);
}
public boolean isSet(@NotNull final Direction direction) {
return this.directions.contains(direction);
}
@NotNull
public EnumSet<Direction> getUnsealedSet() {
final EnumSet<Direction> result = EnumSet.copyOf(this.directions);
result.removeAll(this.sealed);
return result;
}
public void seal(@NotNull final Direction direction) {
if (!this.directions.contains(direction)) {
throw new IllegalStateException("Trying to seal cleared Direction: " + direction);
}
this.sealed.add(direction);
}
public void unseal(@NotNull final Direction direction) {
this.sealed.remove(direction);
}
@NotNull
public EnumSet<Direction> getOpen() {
return EnumSet.complementOf(this.directions);
}
}

View file

@ -1,9 +0,0 @@
package ch.fritteli.maze.generator.renderer;
import ch.fritteli.maze.generator.model.Maze;
import org.jetbrains.annotations.NotNull;
public interface Renderer<T> {
@NotNull
T render(@NotNull final Maze maze);
}

View file

@ -1,177 +0,0 @@
package ch.fritteli.maze.generator.renderer.html;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.renderer.Renderer;
import org.jetbrains.annotations.NotNull;
public class HTMLRenderer implements Renderer<String> {
private static final String POSTAMBLE = """
<script>
let userPath = [];
const DIR_UNDEF = -1;
const DIR_SAME = 0;
const DIR_UP = 1;
const DIR_RIGHT = 2;
const DIR_DOWN = 3;
const DIR_LEFT = 4;
function getCoords(cell) {
return {
x: cell.cellIndex,
y: cell.parentElement.rowIndex
};
}
function distance(prev, next) {
return Math.abs(prev.x - next.x) + Math.abs(prev.y - next.y);
}
function direction(prev, next) {
const dist = distance(prev, next);
if (dist === 0) {
return DIR_SAME;
}
if (dist !== 1) {
return DIR_UNDEF;
}
if (next.x === prev.x) {
if (next.y === prev.y + 1) {
return DIR_DOWN;
}
return DIR_UP;
}
if (next.x === prev.x + 1) {
return DIR_RIGHT;
}
return DIR_LEFT;
}
(function () {
const labyrinthTable = document.getElementById("labyrinth");
const labyrinthCells = labyrinthTable.getElementsByTagName("td");
const start = {x: 0, y: 0};
const end = {
x: labyrinthTable.getElementsByTagName("tr")[0].getElementsByTagName("td").length - 1,
y: labyrinthTable.getElementsByTagName("tr").length - 1
};
for (let i = 0; i < labyrinthCells.length; i++) {
let cell = labyrinthCells.item(i);
cell.onclick = (event) => {
let target = event.target;
const coords = getCoords(target);
if (coords.x === end.x && coords.y === end.y) {
alert("HOORAY! You did it! Congratulations!")
}
if (userPath.length === 0) {
if (coords.x === start.x && coords.y === start.y) {
userPath.push(coords);
target.classList.toggle("user");
}
} else {
const dir = direction(userPath[userPath.length - 1], coords);
switch (dir) {
case DIR_UNDEF:
return;
case DIR_SAME:
userPath.pop();
target.classList.toggle("user");
return;
default:
if (userPath.find(value => value.x === coords.x && value.y === coords.y)) {
return;
} else {
switch (dir) {
case DIR_UP:
if (target.classList.contains("bottom")) {
return;
}
break;
case DIR_RIGHT:
if (target.classList.contains("left")) {
return;
}
break;
case DIR_DOWN:
if (target.classList.contains("top")) {
return;
}
break;
case DIR_LEFT:
if (target.classList.contains("right")) {
return;
}
break;
}
userPath.push(coords);
target.classList.toggle("user");
return;
}
}
}
};
}
})();
</script></body></html>""";
private HTMLRenderer() {
}
@NotNull
public static HTMLRenderer newInstance() {
return new HTMLRenderer();
}
@NotNull
@Override
public String render(@NotNull final Maze maze) {
if (maze.getWidth() == 0 || maze.getHeight() == 0) {
return this.getPreamble(maze) + POSTAMBLE;
}
final Generator generator = new Generator(maze);
final StringBuilder sb = new StringBuilder(this.getPreamble(maze));
sb.append("<table id=\"labyrinth\">");
while (generator.hasNext()) {
sb.append(generator.next());
}
sb.append("</table>");
sb.append(POSTAMBLE);
return sb.toString();
}
private String getPreamble(@NotNull final Maze maze) {
return """
<!DOCTYPE html>
<html lang="en">
<head>
<title>Maze %dx%d, ID %d, Algorithm %s</title>
<meta charset="utf-8">
<style>
table{border-collapse:collapse;}
td{border:0 solid black;height:1em;width:1em;cursor:pointer;}
td.top{border-top-width:1px;}
td.right{border-right-width:1px;}
td.bottom{border-bottom-width:1px;}
td.left{border-left-width:1px;}
td.user{background:hotpink;}
</style>
<script>
let solution = false;
function toggleSolution() {
let stylesheet = document.styleSheets[0];
if (solution) {
stylesheet.deleteRule(0);
} else {
stylesheet.insertRule("td.solution{background-color:lightgray;}", 0);
}
solution = !solution;
}
</script>
</head>
<body>
<input id="solutionbox" type="checkbox" onclick="toggleSolution()"/>
<label for="solutionbox">show solution</label>"""
.formatted(
maze.getWidth(),
maze.getHeight(),
maze.getRandomSeed(),
maze.getAlgorithm()
);
}
}

View file

@ -1,59 +0,0 @@
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.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
class Generator {
@NotNull
private final Maze maze;
@NotNull
JsonMaze generate() {
final JsonMaze result = new JsonMaze();
result.setId(String.valueOf(this.maze.getRandomSeed()));
result.setAlgorithm(this.maze.getAlgorithm());
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 dimensions %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().x());
start.setY(this.maze.getStart().y());
result.setStart(start);
final JsonCoordinates end = new JsonCoordinates();
end.setX(this.maze.getEnd().x());
end.setY(this.maze.getEnd().y());
result.setEnd(end);
return result;
}
}

View file

@ -1,69 +0,0 @@
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<String> {
@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<List<JsonCell>> 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);
}
}

View file

@ -1,69 +0,0 @@
package ch.fritteli.maze.generator.renderer.jsonfile;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.renderer.Renderer;
import ch.fritteli.maze.generator.renderer.json.JsonRenderer;
import io.vavr.control.Option;
import io.vavr.control.Try;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.NoSuchElementException;
@Slf4j
public class JsonFileRenderer implements Renderer<Path> {
@NotNull
private static final JsonRenderer JSON_RENDERER = JsonRenderer.newInstance();
@NotNull
private Option<Path> targetFile;
private JsonFileRenderer() {
this.targetFile = Try
.of(() -> Files.createTempFile("maze_", ".json"))
.onFailure(ex -> log.error("Unable to set default target file.", ex))
.toOption();
}
@NotNull
public static JsonFileRenderer newInstance() {
return new JsonFileRenderer();
}
public boolean isTargetFileDefinedAndWritable() {
return this.targetFile
.map(Path::toFile)
.exists(File::canWrite);
}
@NotNull
public JsonFileRenderer setTargetFile(@NotNull final Path targetFile) {
this.targetFile = Option.of(targetFile);
return this;
}
@NotNull
@Override
public Path render(@NotNull final Maze maze) {
if (!this.isTargetFileDefinedAndWritable()) {
try {
Files.createFile(this.targetFile.get());
} catch (final IOException | NoSuchElementException e) {
throw new IllegalArgumentException("Cannot write to target file.", e);
}
}
final String json = JSON_RENDERER.render(maze);
final Path outputFile = this.targetFile.get();
try {
Files.writeString(outputFile, json, StandardCharsets.UTF_8);
} catch (final IOException e) {
log.error("Failed writing to file %s".formatted(outputFile.normalize()), e);
}
return outputFile;
}
}

View file

@ -1,48 +0,0 @@
package ch.fritteli.maze.generator.serialization;
import ch.fritteli.maze.generator.model.Maze;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public abstract class AbstractMazeInputStream extends ByteArrayInputStream {
public AbstractMazeInputStream(@NotNull final byte[] buf) {
super(buf);
}
public abstract void checkHeader();
@NotNull
public abstract Maze readMazeData() throws IOException;
public byte readByte() {
final int read = this.read();
if (read == -1) {
// end of stream reached
throw new ArrayIndexOutOfBoundsException("End of stream reached. Cannot read more bytes.");
}
return (byte) read;
}
public int readByteAsInt() {
return 0xff & this.readByte();
}
public int readInt() {
int result = 0;
result |= (0xff & this.readByte()) << 24;
result |= (0xff & this.readByte()) << 16;
result |= (0xff & this.readByte()) << 8;
result |= 0xff & this.readByte();
return result;
}
public long readLong() {
long result = 0;
result |= ((long) this.readInt()) << 32;
result |= 0xffffffffL & this.readInt();
return result;
}
}

View file

@ -1,29 +0,0 @@
package ch.fritteli.maze.generator.serialization;
import ch.fritteli.maze.generator.model.Maze;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayOutputStream;
public abstract class AbstractMazeOutputStream extends ByteArrayOutputStream {
public abstract void writeHeader();
public abstract void writeMazeData(@NotNull final Maze maze);
public void writeByte(final byte value) {
this.write(value);
}
public void writeInt(final int value) {
this.write(value >> 24);
this.write(value >> 16);
this.write(value >> 8);
this.write(value);
}
public void writeLong(final long value) {
this.writeInt((int) (value >> 32));
this.writeInt((int) value);
}
}

View file

@ -1,100 +0,0 @@
package ch.fritteli.maze.generator.serialization;
import ch.fritteli.maze.generator.model.Direction;
import ch.fritteli.maze.generator.model.Tile;
import lombok.experimental.UtilityClass;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.EnumSet;
/**
* Binary format description of a {@link Tile}.<br>
* A tile is stored in one byte:
* <ul>
* <li>bits 0..2: always 0</li>
* <li>bit 3: 1=solution, 0=not solution</li>
* <li>bits 4..7: encode walls</li>
* </ul>
* The values for bits 4..7 are as follows:
* <pre>
* decimal hex bin border
* 0 0 0000 no border
* 1 1 0001 top
* 2 2 0010 right
* 3 3 0011 top+right
* 4 4 0100 bottom
* 5 5 0101 top+bottom
* 6 6 0110 right+bottom
* 7 7 0111 top+right+bottom
* 8 8 1000 left
* 9 9 1001 top+left
* 10 a 1010 right+left
* 11 b 1011 top+right+left
* 12 c 1100 bottom+left
* 13 d 1101 top+bottom+left
* 14 e 1110 right+bottom+left
* 15 f 1111 top+right+bottom+left
* </pre>
*/
@UtilityClass
public class CommonTileHandler {
private final byte TOP_BIT = 0b0000_0001;
private final byte RIGHT_BIT = 0b0000_0010;
private final byte BOTTOM_BIT = 0b0000_0100;
private final byte LEFT_BIT = 0b0000_1000;
private final byte SOLUTION_BIT = 0b0001_0000;
public byte getBitmaskForTile(@NotNull final Tile tile) {
byte bitmask = 0;
if (tile.hasWallAt(Direction.TOP)) {
bitmask |= TOP_BIT;
}
if (tile.hasWallAt(Direction.RIGHT)) {
bitmask |= RIGHT_BIT;
}
if (tile.hasWallAt(Direction.BOTTOM)) {
bitmask |= BOTTOM_BIT;
}
if (tile.hasWallAt((Direction.LEFT))) {
bitmask |= LEFT_BIT;
}
if (tile.isSolution()) {
bitmask |= SOLUTION_BIT;
}
return bitmask;
}
@NotNull
public Tile getTileForBitmask(final byte bitmask) {
final EnumSet<Direction> walls = EnumSet.noneOf(Direction.class);
if ((bitmask & TOP_BIT) == TOP_BIT) {
walls.add(Direction.TOP);
}
if ((bitmask & RIGHT_BIT) == RIGHT_BIT) {
walls.add(Direction.RIGHT);
}
if ((bitmask & BOTTOM_BIT) == BOTTOM_BIT) {
walls.add(Direction.BOTTOM);
}
if ((bitmask & LEFT_BIT) == LEFT_BIT) {
walls.add(Direction.LEFT);
}
final boolean solution = (bitmask & SOLUTION_BIT) == SOLUTION_BIT;
return createTile(walls, solution);
}
@NotNull
private Tile createTile(@NotNull final EnumSet<Direction> walls, boolean solution) {
try {
final Constructor<Tile> constructor = Tile.class.getDeclaredConstructor(EnumSet.class, Boolean.TYPE);
constructor.setAccessible(true);
return constructor.newInstance(walls, solution);
} catch (@NotNull final NoSuchMethodException | InstantiationException | IllegalAccessException |
InvocationTargetException e) {
throw new RuntimeException("Can not deserialize Tile from maze data.", e);
}
}
}

View file

@ -1,9 +0,0 @@
package ch.fritteli.maze.generator.serialization;
import lombok.experimental.UtilityClass;
@UtilityClass
public class MazeConstants {
public final byte MAGIC_BYTE_1 = 0x1a;
public final byte MAGIC_BYTE_2 = (byte) 0xb1;
}

View file

@ -1,60 +0,0 @@
package ch.fritteli.maze.generator.serialization.v1;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Tile;
import ch.fritteli.maze.generator.serialization.AbstractMazeInputStream;
import ch.fritteli.maze.generator.serialization.CommonTileHandler;
import ch.fritteli.maze.generator.serialization.MazeConstants;
import org.jetbrains.annotations.NotNull;
public class MazeInputStreamV1 extends AbstractMazeInputStream {
public MazeInputStreamV1(@NotNull final byte[] buf) {
super(buf);
}
@Override
public void checkHeader() {
// 00 0x1a magic
// 01 0xb1 magic
// 02 0x01 version
final byte magic1 = this.readByte();
if (magic1 != MazeConstants.MAGIC_BYTE_1) {
throw new IllegalArgumentException("Invalid maze data.");
}
final byte magic2 = this.readByte();
if (magic2 != MazeConstants.MAGIC_BYTE_2) {
throw new IllegalArgumentException("Invalid maze data.");
}
final int version = this.readByte();
if (version != SerializerDeserializerV1.VERSION_BYTE) {
throw new IllegalArgumentException("Unknown maze data version: " + version);
}
}
@NotNull
@Override
public Maze readMazeData() {
// 03..10 random seed number (long)
// 11..14 width (int)
// 15..18 height (int)
// 19.. tiles
final long randomSeed = this.readLong();
final int width = this.readInt();
final int height = this.readInt();
final Tile[][] tiles = new Tile[width][height];
for (int x = 0; x < width; x++) {
tiles[x] = new Tile[height];
}
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final byte bitmask = this.readByte();
tiles[x][y] = CommonTileHandler.getTileForBitmask(bitmask);
}
}
return SerializerDeserializerV1.createMaze(tiles, width, height, randomSeed);
}
}

View file

@ -1,44 +0,0 @@
package ch.fritteli.maze.generator.serialization.v1;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Tile;
import ch.fritteli.maze.generator.serialization.AbstractMazeOutputStream;
import ch.fritteli.maze.generator.serialization.CommonTileHandler;
import ch.fritteli.maze.generator.serialization.MazeConstants;
import org.jetbrains.annotations.NotNull;
public class MazeOutputStreamV1 extends AbstractMazeOutputStream {
@Override
public void writeHeader() {
// 00 0x1a magic
// 01 0xb1 magic
// 02 0x02 version
this.writeByte(MazeConstants.MAGIC_BYTE_1);
this.writeByte(MazeConstants.MAGIC_BYTE_2);
this.writeByte(SerializerDeserializerV1.VERSION_BYTE);
}
@Override
public void writeMazeData(@NotNull final Maze maze) {
// 03..10 random seed number (long)
// 11..14 width (int)
// 15..18 height (int)
// 19.. tiles
final long randomSeed = maze.getRandomSeed();
final int width = maze.getWidth();
final int height = maze.getHeight();
this.writeLong(randomSeed);
this.writeInt(width);
this.writeInt(height);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// We .get() it, because we want to crash hard if it is not available.
final Tile tile = maze.getTileAt(x, y).get();
final byte bitmask = CommonTileHandler.getBitmaskForTile(tile);
this.writeByte(bitmask);
}
}
}
}

View file

@ -1,67 +0,0 @@
package ch.fritteli.maze.generator.serialization.v1;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Tile;
import lombok.experimental.UtilityClass;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Header bytes are:
* <pre>
* byte hex meaning
* 00 0x1a magic
* 01 0xb1 magic
* 02 0x01 version (0x00 -> dev, 0x01 -> stable)
* 03..10 random seed number (long)
* 11..14 width (int)
* 15..18 height (int)
* 19.. tiles
* </pre>
* Extraneous space (poss. last nibble) is ignored.
*/
@UtilityClass
public class SerializerDeserializerV1 {
public final byte VERSION_BYTE = 0x01;
/**
* Serializes the {@code maze} into a byte array.
*
* @param maze The {@link Maze} to be serialized.
* @return The resulting byte array.
*/
@NotNull
public byte[] serialize(@NotNull final Maze maze) {
final MazeOutputStreamV1 stream = new MazeOutputStreamV1();
stream.writeHeader();
stream.writeMazeData(maze);
return stream.toByteArray();
}
/**
* Deserializes the byte array into an instance of {@link Maze}.
*
* @param bytes The byte array to be deserialized.
* @return An instance of {@link Maze}.
*/
@NotNull
public Maze deserialize(@NotNull final byte[] bytes) {
final MazeInputStreamV1 stream = new MazeInputStreamV1(bytes);
stream.checkHeader();
return stream.readMazeData();
}
@NotNull
Maze createMaze(@NotNull final Tile[][] field, final int width, final int height, final long randomSeed) {
try {
final Constructor<Maze> constructor = Maze.class.getDeclaredConstructor(Tile[][].class, Integer.TYPE, Integer.TYPE, Long.TYPE);
constructor.setAccessible(true);
return constructor.newInstance(field, width, height, randomSeed);
} catch (@NotNull final NoSuchMethodException | IllegalAccessException | InstantiationException |
InvocationTargetException e) {
throw new RuntimeException("Can not deserialize Maze from maze data.", e);
}
}
}

View file

@ -1,71 +0,0 @@
package ch.fritteli.maze.generator.serialization.v2;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import ch.fritteli.maze.generator.model.Tile;
import ch.fritteli.maze.generator.serialization.AbstractMazeInputStream;
import ch.fritteli.maze.generator.serialization.CommonTileHandler;
import ch.fritteli.maze.generator.serialization.MazeConstants;
import org.jetbrains.annotations.NotNull;
public class MazeInputStreamV2 extends AbstractMazeInputStream {
public MazeInputStreamV2(@NotNull final byte[] buf) {
super(buf);
}
@Override
public void checkHeader() {
// 00 0x1a magic
// 01 0xb1 magic
// 02 0x02 version
final byte magic1 = this.readByte();
if (magic1 != MazeConstants.MAGIC_BYTE_1) {
throw new IllegalArgumentException("Invalid maze data.");
}
final byte magic2 = this.readByte();
if (magic2 != MazeConstants.MAGIC_BYTE_2) {
throw new IllegalArgumentException("Invalid maze data.");
}
final int version = this.readByte();
if (version != SerializerDeserializerV2.VERSION_BYTE) {
throw new IllegalArgumentException("Unknown maze data version: " + version);
}
}
@NotNull
@Override
public Maze readMazeData() {
// 03..06 width (int)
// 07..10 height (int)
// 11..14 start-x (int)
// 15..18 start-y (int)
// 19..22 end-x (int)
// 23..26 end-y (int)
// 27..34 random seed number (long)
// 35.. tiles
final int width = this.readInt();
final int height = this.readInt();
final int startX = this.readInt();
final int startY = this.readInt();
final int endX = this.readInt();
final int endY = this.readInt();
final long randomSeed = this.readLong();
final Tile[][] tiles = new Tile[width][height];
for (int x = 0; x < width; x++) {
tiles[x] = new Tile[height];
}
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final byte bitmask = this.readByte();
tiles[x][y] = CommonTileHandler.getTileForBitmask(bitmask);
}
}
final Position start = new Position(startX, startY);
final Position end = new Position(endX, endY);
return SerializerDeserializerV2.createMaze(tiles, width, height, start, end, randomSeed);
}
}

View file

@ -1,55 +0,0 @@
package ch.fritteli.maze.generator.serialization.v2;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import ch.fritteli.maze.generator.model.Tile;
import ch.fritteli.maze.generator.serialization.AbstractMazeOutputStream;
import ch.fritteli.maze.generator.serialization.CommonTileHandler;
import ch.fritteli.maze.generator.serialization.MazeConstants;
import org.jetbrains.annotations.NotNull;
public class MazeOutputStreamV2 extends AbstractMazeOutputStream {
@Override
public void writeHeader() {
// 00 0x1a magic
// 01 0xb1 magic
// 02 0x02 version
this.writeByte(MazeConstants.MAGIC_BYTE_1);
this.writeByte(MazeConstants.MAGIC_BYTE_2);
this.writeByte(SerializerDeserializerV2.VERSION_BYTE);
}
@Override
public void writeMazeData(@NotNull final Maze maze) {
// 03..06 width (int)
// 07..10 height (int)
// 11..14 start-x (int)
// 15..18 start-y (int)
// 19..22 end-x (int)
// 23..26 end-y (int)
// 27..34 random seed number (long)
// 35.. tiles
final long randomSeed = maze.getRandomSeed();
final int width = maze.getWidth();
final int height = maze.getHeight();
final Position start = maze.getStart();
final Position end = maze.getEnd();
this.writeInt(width);
this.writeInt(height);
this.writeInt(start.x());
this.writeInt(start.y());
this.writeInt(end.x());
this.writeInt(end.y());
this.writeLong(randomSeed);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// We .get() it, because we want to crash hard if it is not available.
final Tile tile = maze.getTileAt(x, y).get();
final byte bitmask = CommonTileHandler.getBitmaskForTile(tile);
this.writeByte(bitmask);
}
}
}
}

View file

@ -1,72 +0,0 @@
package ch.fritteli.maze.generator.serialization.v2;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import ch.fritteli.maze.generator.model.Tile;
import lombok.experimental.UtilityClass;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Header bytes are:
* <pre>
* byte hex meaning
* 00 0x1a magic
* 01 0xb1 magic
* 02 0x02 version (0x00 -> dev, 0x01 -> deprecated, 0x02 -> stable)
* 03..06 width (int)
* 07..10 height (int)
* 11..14 start-x (int)
* 15..18 start-y (int)
* 19..22 end-x (int)
* 23..26 end-y (int)
* 27..34 random seed number (long)
* 35.. tiles
* </pre>
* Extraneous space (poss. last nibble) is ignored.
*/
@UtilityClass
public class SerializerDeserializerV2 {
public final byte VERSION_BYTE = 0x02;
/**
* Serializes the {@code maze} into a byte array.
*
* @param maze The {@link Maze} to be serialized.
* @return The resulting byte array.
*/
@NotNull
public byte[] serialize(@NotNull final Maze maze) {
final MazeOutputStreamV2 stream = new MazeOutputStreamV2();
stream.writeHeader();
stream.writeMazeData(maze);
return stream.toByteArray();
}
/**
* Deserializes the byte array into an instance of {@link Maze}.
*
* @param bytes The byte array to be deserialized.
* @return An instance of {@link Maze}.
*/
@NotNull
public Maze deserialize(@NotNull final byte[] bytes) {
final MazeInputStreamV2 stream = new MazeInputStreamV2(bytes);
stream.checkHeader();
return stream.readMazeData();
}
@NotNull
Maze createMaze(@NotNull final Tile[][] field, final int width, final int height, @NotNull final Position start, @NotNull final Position end, final long randomSeed) {
try {
final Constructor<Maze> constructor = Maze.class.getDeclaredConstructor(Tile[][].class, Integer.TYPE, Integer.TYPE, Position.class, Position.class, Long.TYPE);
constructor.setAccessible(true);
return constructor.newInstance(field, width, height, start, end, randomSeed);
} catch (@NotNull final NoSuchMethodException | IllegalAccessException | InstantiationException |
InvocationTargetException e) {
throw new RuntimeException("Can not deserialize Maze from maze data.", e);
}
}
}

View file

@ -1,79 +0,0 @@
package ch.fritteli.maze.generator.serialization.v3;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import ch.fritteli.maze.generator.model.Tile;
import ch.fritteli.maze.generator.serialization.AbstractMazeInputStream;
import ch.fritteli.maze.generator.serialization.CommonTileHandler;
import ch.fritteli.maze.generator.serialization.MazeConstants;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class MazeInputStreamV3 extends AbstractMazeInputStream {
public MazeInputStreamV3(@NotNull final byte[] buf) {
super(buf);
}
@Override
public void checkHeader() {
// 00 0x1a magic
// 01 0xb1 magic
// 02 0x03 version
final byte magic1 = this.readByte();
if (magic1 != MazeConstants.MAGIC_BYTE_1) {
throw new IllegalArgumentException("Invalid maze data.");
}
final byte magic2 = this.readByte();
if (magic2 != MazeConstants.MAGIC_BYTE_2) {
throw new IllegalArgumentException("Invalid maze data.");
}
final int version = this.readByte();
if (version != SerializerDeserializerV3.VERSION_BYTE) {
throw new IllegalArgumentException("Unknown maze data version: " + version);
}
}
@NotNull
@Override
public Maze readMazeData() throws IOException {
// 03..06 width (int)
// 07..10 height (int)
// 11..14 start-x (int)
// 15..18 start-y (int)
// 19..22 end-x (int)
// 23..26 end-y (int)
// 27..34 random seed number (long)
// 35 length of the algorithm's name (unsigned byte)
// 36..+len name (bytes of String)
// +len+1.. tiles
final int width = this.readInt();
final int height = this.readInt();
final int startX = this.readInt();
final int startY = this.readInt();
final int endX = this.readInt();
final int endY = this.readInt();
final long randomSeed = this.readLong();
final int algorithmLength = this.readByteAsInt();
final String algorithm = new String(this.readNBytes(algorithmLength), StandardCharsets.UTF_8);
final Tile[][] tiles = new Tile[width][height];
for (int x = 0; x < width; x++) {
tiles[x] = new Tile[height];
}
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final byte bitmask = this.readByte();
tiles[x][y] = CommonTileHandler.getTileForBitmask(bitmask);
}
}
final Position start = new Position(startX, startY);
final Position end = new Position(endX, endY);
return SerializerDeserializerV3.createMaze(tiles, width, height, start, end, randomSeed, algorithm);
}
}

View file

@ -1,86 +0,0 @@
package ch.fritteli.maze.generator.serialization.v3;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import ch.fritteli.maze.generator.model.Tile;
import ch.fritteli.maze.generator.serialization.AbstractMazeOutputStream;
import ch.fritteli.maze.generator.serialization.CommonTileHandler;
import ch.fritteli.maze.generator.serialization.MazeConstants;
import org.jetbrains.annotations.NotNull;
import java.nio.charset.StandardCharsets;
public class MazeOutputStreamV3 extends AbstractMazeOutputStream {
@Override
public void writeHeader() {
// 00 0x1a magic
// 01 0xb1 magic
// 02 0x03 version
this.writeByte(MazeConstants.MAGIC_BYTE_1);
this.writeByte(MazeConstants.MAGIC_BYTE_2);
this.writeByte(SerializerDeserializerV3.VERSION_BYTE);
}
@Override
public void writeMazeData(@NotNull final Maze maze) {
// 03..06 width (int)
// 07..10 height (int)
// 11..14 start-x (int)
// 15..18 start-y (int)
// 19..22 end-x (int)
// 23..26 end-y (int)
// 27..34 random seed number (long)
// 35 length of the algorithm's name (unsigned byte)
// 36..+len name (bytes of String)
// +len+1.. tiles
final long randomSeed = maze.getRandomSeed();
final AlgorithmWrapper algorithm = this.getAlgorithmWrapper(maze.getAlgorithm());
final int width = maze.getWidth();
final int height = maze.getHeight();
final Position start = maze.getStart();
final Position end = maze.getEnd();
this.writeInt(width);
this.writeInt(height);
this.writeInt(start.x());
this.writeInt(start.y());
this.writeInt(end.x());
this.writeInt(end.y());
this.writeLong(randomSeed);
this.writeByte(algorithm.length());
this.writeBytes(algorithm.name());
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// We .get() it, because we want to crash hard if it is not available.
final Tile tile = maze.getTileAt(x, y).get();
final byte bitmask = CommonTileHandler.getBitmaskForTile(tile);
this.writeByte(bitmask);
}
}
}
@NotNull
private AlgorithmWrapper getAlgorithmWrapper(@NotNull final String algorithm) {
final byte[] bytes = algorithm.getBytes(StandardCharsets.UTF_8);
if (bytes.length < 256) {
// Phew, that's the easy case!
return new AlgorithmWrapper(bytes, (byte) bytes.length);
}
// Let's use a very primitive, brute-force approach
int strLen = Math.min(255, algorithm.length());
int len;
byte[] name;
do {
name = algorithm.substring(0, strLen).getBytes(StandardCharsets.UTF_8);
len = name.length;
strLen--;
} while (len > 255);
return new AlgorithmWrapper(name, (byte) len);
}
private record AlgorithmWrapper(@NotNull byte[] name, byte length) {
}
}

View file

@ -1,89 +0,0 @@
package ch.fritteli.maze.generator.serialization.v3;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import ch.fritteli.maze.generator.model.Tile;
import lombok.experimental.UtilityClass;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Header bytes are:
* <pre>
* byte hex meaning
* 00 0x1a magic
* 01 0xb1 magic
* 02 0x03 version (0x00 -> dev, 0x01, 0x02 -> deprecated, 0x03 -> stable)
* 03..06 width (int)
* 07..10 height (int)
* 11..14 start-x (int)
* 15..18 start-y (int)
* 19..22 end-x (int)
* 23..26 end-y (int)
* 27..34 random seed number (long)
* 35 length of the algorithm's name (number of bytes of the Java String) (unsigned byte)
* 36..(36+len) algorithm's name (bytes of the Java String) (byte...)
* 36+len+1.. tiles
* </pre>
* Extraneous space (poss. last nibble) is ignored.
*/
@UtilityClass
public class SerializerDeserializerV3 {
public final byte VERSION_BYTE = 0x03;
/**
* Serializes the {@code maze} into a byte array.
*
* @param maze The {@link Maze} to be serialized.
* @return The resulting byte array.
*/
@NotNull
public byte[] serialize(@NotNull final Maze maze) {
final MazeOutputStreamV3 stream = new MazeOutputStreamV3();
stream.writeHeader();
stream.writeMazeData(maze);
return stream.toByteArray();
}
/**
* Deserializes the byte array into an instance of {@link Maze}.
*
* @param bytes The byte array to be deserialized.
* @return An instance of {@link Maze}.
*/
@NotNull
public Maze deserialize(@NotNull final byte[] bytes) throws IOException {
final MazeInputStreamV3 stream = new MazeInputStreamV3(bytes);
stream.checkHeader();
return stream.readMazeData();
}
@NotNull
Maze createMaze(@NotNull final Tile[][] field,
final int width,
final int height,
@NotNull final Position start,
@NotNull final Position end,
final long randomSeed,
@NotNull final String algorithm) {
try {
final Constructor<Maze> constructor = Maze.class.getDeclaredConstructor(
Tile[][].class,
Integer.TYPE,
Integer.TYPE,
Position.class,
Position.class,
Long.TYPE,
String.class
);
constructor.setAccessible(true);
return constructor.newInstance(field, width, height, start, end, randomSeed, algorithm);
} catch (@NotNull final NoSuchMethodException | IllegalAccessException | InstantiationException |
InvocationTargetException e) {
throw new RuntimeException("Can not deserialize Maze from maze data.", e);
}
}
}

View file

@ -1,101 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://manuel.friedli.info/maze/maze.schema.json",
"javaType": "ch.fritteli.maze.generator.json.JsonMaze",
"type": "object",
"additionalProperties": false,
"required": [
"id",
"algorithm",
"width",
"height",
"start",
"end",
"grid"
],
"properties": {
"id": {
"type": "string",
"description": "64 bit precision signed integer value. Transmitted as string, because ECMAScript (browsers) don't normally handle 64 bit integers well, as the ECMAScript 'number' type is a 64 bit signed double value, leaving only 53 bits for the integer part, thus losing precision."
},
"algorithm": {
"type": "string",
"description": "The name of the algorithm used to generate the maze."
},
"width": {
"type": "integer",
"minimum": 1
},
"height": {
"type": "integer",
"minimum": 1
},
"start": {
"$ref": "#/$defs/coordinates"
},
"end": {
"$ref": "#/$defs/coordinates"
},
"grid": {
"$ref": "#/$defs/grid"
}
},
"$defs": {
"grid": {
"type": "array",
"items": {
"$ref": "#/$defs/row"
},
"minItems": 1
},
"row": {
"type": "array",
"items": {
"$ref": "#/$defs/cell"
},
"minItems": 1
},
"cell": {
"type": "object",
"javaType": "ch.fritteli.maze.generator.json.JsonCell",
"additionalProperties": false,
"required": [],
"properties": {
"top": {
"type": "boolean"
},
"right": {
"type": "boolean"
},
"bottom": {
"type": "boolean"
},
"left": {
"type": "boolean"
},
"solution": {
"type": "boolean"
}
}
},
"coordinates": {
"type": "object",
"javaType": "ch.fritteli.maze.generator.json.JsonCoordinates",
"additionalProperties": false,
"required": [
"x",
"y"
],
"properties": {
"x": {
"type": "integer",
"minimum": 0
},
"y": {
"type": "integer",
"minimum": 0
}
}
}
}
}

View file

@ -1,4 +1,4 @@
package ch.fritteli.maze.generator.model;
package ch.fritteli.labyrinth.generator.model;
import org.junit.jupiter.api.Test;
@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.assertThat;
class DirectionTest {
@Test
void shouldInvertTheDirection() {
void invert() {
assertThat(Direction.TOP.invert()).isEqualTo(Direction.BOTTOM);
assertThat(Direction.RIGHT.invert()).isEqualTo(Direction.LEFT);
assertThat(Direction.BOTTOM.invert()).isEqualTo(Direction.TOP);

View file

@ -0,0 +1,29 @@
package ch.fritteli.labyrinth.generator.model;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
class LabyrinthTest {
@Test
void testConstruct() {
// act / assert on simple cases
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new Labyrinth(0, 0))
.withMessage("width and height must be >1");
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new Labyrinth(0, 0, 0))
.withMessage("width and height must be >1");
// now for the real work:
// arrange
final Labyrinth sut = new Labyrinth(2, 3, 5);
// assert
assertThat(sut)
.returns(2, Labyrinth::getWidth)
.returns(3, Labyrinth::getHeight)
.returns(5L, Labyrinth::getRandomSeed)
.returns(new Position(0, 0), Labyrinth::getStart)
.returns(new Position(1, 2), Labyrinth::getEnd);
}
}

View file

@ -1,4 +1,4 @@
package ch.fritteli.maze.generator.model;
package ch.fritteli.labyrinth.generator.model;
import org.junit.jupiter.api.Test;
@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.assertThat;
class PositionTest {
@Test
void shouldMoveToCorrectNeighborPosition() {
void move() {
// arrange
final Position sut = new Position(0, 0);

View file

@ -1,4 +1,4 @@
package ch.fritteli.maze.generator.model;
package ch.fritteli.labyrinth.generator.model;
import io.vavr.control.Option;
import org.junit.jupiter.api.Test;
@ -9,20 +9,21 @@ import static org.assertj.core.api.Assertions.assertThat;
class TileTest {
@Test
void shouldConstructATileWithDefaultValues() {
void testConstruct() {
// arrange / act
final Tile sut = new Tile();
//assert
assertThat(sut.hasWallAt(Direction.TOP)).isTrue();
assertThat(sut.hasWallAt(Direction.RIGHT)).isTrue();
assertThat(sut.hasWallAt(Direction.BOTTOM)).isTrue();
assertThat(sut.hasWallAt(Direction.LEFT)).isTrue();
assertThat(sut.isSolution()).isFalse();
assertThat(sut)
.returns(true, v -> v.hasWallAt(Direction.TOP))
.returns(true, v -> v.hasWallAt(Direction.RIGHT))
.returns(true, v -> v.hasWallAt(Direction.BOTTOM))
.returns(true, v -> v.hasWallAt(Direction.LEFT))
.returns(false, Tile::isSolution);
}
@Test
void tileCanBeDugIntoOnlyOnce() {
void testDigFrom() {
// arrange
final Tile sut = new Tile();
@ -42,27 +43,29 @@ class TileTest {
}
@Test
void canDigToDirectionOnlyOnce() {
void testDigTo() {
// arrange
final Tile sut = new Tile();
// act / assert
assertThat(sut.digTo(Direction.TOP)).isTrue();
assertThat(sut.digTo(Direction.RIGHT)).isTrue();
assertThat(sut.digTo(Direction.BOTTOM)).isTrue();
assertThat(sut.digTo(Direction.LEFT)).isTrue();
// digging a second time does not succeed
assertThat(sut.digTo(Direction.LEFT)).isFalse();
assertThat(sut)
.returns(true, v -> v.digTo(Direction.TOP))
.returns(true, v -> v.digTo(Direction.RIGHT))
.returns(true, v -> v.digTo(Direction.BOTTOM))
.returns(true, v -> v.digTo(Direction.LEFT))
// digging a second time does not succeed
.returns(false, v -> v.digTo(Direction.LEFT));
// assert
assertThat(sut.hasWallAt(Direction.TOP)).isFalse();
assertThat(sut.hasWallAt(Direction.RIGHT)).isFalse();
assertThat(sut.hasWallAt(Direction.BOTTOM)).isFalse();
assertThat(sut.hasWallAt(Direction.LEFT)).isFalse();
assertThat(sut)
.returns(false, v -> v.hasWallAt(Direction.TOP))
.returns(false, v -> v.hasWallAt(Direction.RIGHT))
.returns(false, v -> v.hasWallAt(Direction.BOTTOM))
.returns(false, v -> v.hasWallAt(Direction.LEFT));
}
@Test
void canNotDigToOrFromDirectionWhenPrevented() {
void testPreventDiggingToOrFrom() {
// arrange
final Tile sut = new Tile();
@ -70,11 +73,10 @@ class TileTest {
sut.preventDiggingToOrFrom(Direction.LEFT);
// assert
assertThat(sut.digTo(Direction.LEFT)).isFalse();
assertThat(sut.digFrom(Direction.LEFT)).isFalse();
assertThat(sut.hasWallAt(Direction.LEFT)).isTrue();
// Digging in another direction is still permitted
assertThat(sut.digTo(Direction.RIGHT)).isTrue();
assertThat(sut)
.returns(false, v -> v.digTo(Direction.LEFT))
.returns(false, v -> v.digFrom(Direction.LEFT))
.returns(true, v -> v.hasWallAt(Direction.LEFT));
}
@Test

View file

@ -1,10 +1,8 @@
package ch.fritteli.maze.generator.model;
package ch.fritteli.labyrinth.generator.model;
import io.vavr.collection.Stream;
import org.junit.jupiter.api.Test;
import java.util.EnumSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@ -65,14 +63,14 @@ class WallsTest {
}
@Test
void testSeal() {
void testHarden() {
// arrange
final Walls sut = new Walls();
sut.set(Direction.TOP);
sut.set(Direction.RIGHT);
// act
sut.seal(Direction.TOP);
sut.harden(Direction.TOP);
// assert
assertThat(sut)
@ -88,34 +86,34 @@ class WallsTest {
assertThat(result).isFalse();
assertThat(sut.isSet(Direction.TOP)).isTrue();
// act / assert: try to seal un-set wall
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> sut.seal(Direction.LEFT));
// act / assert: try to harden un-set wall
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> sut.harden(Direction.LEFT));
}
@Test
void testUnseal() {
void testUnharden() {
// arrange
final Walls sut = new Walls();
sut.setAll();
sut.seal(Direction.TOP);
sut.harden(Direction.TOP);
// pre-assert: TOP can't be cleared while hardened
assertThat(sut.clear(Direction.TOP)).isFalse();
// act
sut.unseal(Direction.TOP);
sut.unharden(Direction.TOP);
// assert: TOP can be cleared
assertThat(sut.clear(Direction.TOP)).isTrue();
}
@Test
void testGetUnsealedSet() {
void testGetUnhardenedSet() {
// arrange
final Walls sut = new Walls();
// act
EnumSet<Direction> result = sut.getUnsealedSet();
Stream<Direction> result = sut.getUnhardenedSet();
// assert
assertThat(result).isEmpty();
@ -125,16 +123,16 @@ class WallsTest {
sut.set(Direction.LEFT);
// act
result = sut.getUnsealedSet();
result = sut.getUnhardenedSet();
// assert
assertThat(result).containsExactly(Direction.TOP, Direction.LEFT);
// arrange: seal a direction
sut.seal(Direction.TOP);
// arrange: harden a direction
sut.harden(Direction.TOP);
// act
result = sut.getUnsealedSet();
result = sut.getUnhardenedSet();
// assert
assertThat(result).containsExactly(Direction.LEFT);

View file

@ -1,6 +1,5 @@
package ch.fritteli.maze.generator.renderer.text;
package ch.fritteli.labyrinth.generator.renderer.text;
import ch.fritteli.maze.generator.renderer.text.CharDefinition;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;

View file

@ -0,0 +1,32 @@
package ch.fritteli.labyrinth.generator.serialization;
import ch.fritteli.labyrinth.generator.model.Labyrinth;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class SerializerDeserializerTest {
@Test
void testSerializeDeserializeTiny() {
final Labyrinth expected = new Labyrinth(2, 2, 255);
final byte[] bytes = SerializerDeserializer.serialize(expected);
final Labyrinth result = SerializerDeserializer.deserialize(bytes);
assertThat(result).isEqualTo(expected);
}
@Test
void testSerializeDeserializeMedium() {
final Labyrinth expected = new Labyrinth(20, 20, -271828182846L);
final byte[] bytes = SerializerDeserializer.serialize(expected);
final Labyrinth result = SerializerDeserializer.deserialize(bytes);
assertThat(result).isEqualTo(expected);
}
@Test
void testSerializeDeserializeLarge() {
final Labyrinth expected = new Labyrinth(200, 320, 3141592653589793238L);
final byte[] bytes = SerializerDeserializer.serialize(expected);
final Labyrinth result = SerializerDeserializer.deserialize(bytes);
assertThat(result).isEqualTo(expected);
}
}

View file

@ -1,100 +0,0 @@
package ch.fritteli.maze.generator.algorithm.wilson;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.renderer.text.TextRenderer;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class WilsonTest {
@Test
void testTinyGeneration() {
// arrange
final Maze maze = new Maze(3, 3, 0);
final Wilson wilson = new Wilson(maze);
// act
wilson.run();
// assert
final String textRepresentation = TextRenderer.newInstance().render(maze);
assertThat(textRepresentation).isEqualTo("""
""");
}
@Test
void testSimpleGeneration() {
// arrange
final Maze maze = new Maze(10, 10, 0);
final Wilson wilson = new Wilson(maze);
// act
wilson.run();
// assert
final String textRepresentation = TextRenderer.newInstance().render(maze);
assertThat(textRepresentation).isEqualTo("""
""");
}
@Test
void testSimpleGenerationWithSolution() {
// arrange
final Maze maze = new Maze(10, 10, 0);
final Wilson wilson = new Wilson(maze);
// act
wilson.run();
// assert
final String textRepresentation = TextRenderer.newInstance().setRenderSolution(true).render(maze);
assertThat(textRepresentation).isEqualTo("""
""");
}
}

View file

@ -1,41 +0,0 @@
package ch.fritteli.maze.generator.model;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
class MazeTest {
@Test
void shouldNotAccept0AsWidthOrHeight() {
// act / assert
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new Maze(0, 0))
.withMessage("width and height must be >1");
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new Maze(0, 0, 0))
.withMessage("width and height must be >1");
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new Maze(0, 5))
.withMessage("width and height must be >1");
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new Maze(0, 5, 0))
.withMessage("width and height must be >1");
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new Maze(5, 0))
.withMessage("width and height must be >1");
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new Maze(5, 0, 0))
.withMessage("width and height must be >1");
}
@Test
void testConstruct() {
// arrange
final Maze sut = new Maze(2, 3, 5);
// assert
assertThat(sut)
.returns(2, Maze::getWidth)
.returns(3, Maze::getHeight)
.returns(5L, Maze::getRandomSeed)
.satisfies(
maze -> assertThat(maze.getStart()).isEqualTo(new Position(0, 0)),
maze -> assertThat(maze.getEnd()).isEqualTo(new Position(1, 2))
);
}
}

View file

@ -1,42 +0,0 @@
package ch.fritteli.maze.generator.serialization.v1;
import ch.fritteli.maze.generator.algorithm.RandomDepthFirst;
import ch.fritteli.maze.generator.model.Maze;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class SerializerDeserializerV1Test {
@Test
void testSerializeDeserializeTiny() {
final Maze expected = new Maze(2, 2, 255);
new RandomDepthFirst(expected).run();
final byte[] bytes = SerializerDeserializerV1.serialize(expected);
final Maze result = SerializerDeserializerV1.deserialize(bytes);
assertThat(result.getAlgorithm()).isNull();
expected.setAlgorithm(null);
assertThat(result).isEqualTo(expected);
}
@Test
void testSerializeDeserializeMedium() {
final Maze expected = new Maze(20, 20, -271828182846L);
new RandomDepthFirst(expected).run();
final byte[] bytes = SerializerDeserializerV1.serialize(expected);
final Maze result = SerializerDeserializerV1.deserialize(bytes);
assertThat(result.getAlgorithm()).isNull();
expected.setAlgorithm(null);
assertThat(result).isEqualTo(expected);
}
@Test
void testSerializeDeserializeLarge() {
final Maze expected = new Maze(200, 320, 3141592653589793238L);
new RandomDepthFirst(expected).run();
final byte[] bytes = SerializerDeserializerV1.serialize(expected);
final Maze result = SerializerDeserializerV1.deserialize(bytes);
assertThat(result.getAlgorithm()).isNull();
expected.setAlgorithm(null);
assertThat(result).isEqualTo(expected);
}
}

View file

@ -1,46 +0,0 @@
package ch.fritteli.maze.generator.serialization.v2;
import ch.fritteli.maze.generator.algorithm.RandomDepthFirst;
import ch.fritteli.maze.generator.algorithm.wilson.Wilson;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
class SerializerDeserializerV2Test {
@Test
void testSerializeDeserializeTiny() throws IOException {
final Maze expected = new Maze(2, 2, 255, new Position(0, 0), new Position(1, 1));
new RandomDepthFirst(expected).run();
final byte[] bytes = SerializerDeserializerV2.serialize(expected);
final Maze result = SerializerDeserializerV2.deserialize(bytes);
assertThat(result.getAlgorithm()).isNull();
expected.setAlgorithm(null);
assertThat(result).isEqualTo(expected);
}
@Test
void testSerializeDeserializeMedium() throws IOException {
final Maze expected = new Maze(20, 20, -271828182846L);
new Wilson(expected).run();
final byte[] bytes = SerializerDeserializerV2.serialize(expected);
final Maze result = SerializerDeserializerV2.deserialize(bytes);
assertThat(result.getAlgorithm()).isNull();
expected.setAlgorithm(null);
assertThat(result).isEqualTo(expected);
}
@Test
void testSerializeDeserializeLarge() throws IOException {
final Maze expected = new Maze(200, 320, 3141592653589793238L);
new Wilson(expected).run();
final byte[] bytes = SerializerDeserializerV2.serialize(expected);
final Maze result = SerializerDeserializerV2.deserialize(bytes);
assertThat(result.getAlgorithm()).isNull();
expected.setAlgorithm(null);
assertThat(result).isEqualTo(expected);
}
}

View file

@ -1,49 +0,0 @@
package ch.fritteli.maze.generator.serialization.v3;
import ch.fritteli.maze.generator.algorithm.RandomDepthFirst;
import ch.fritteli.maze.generator.algorithm.wilson.Wilson;
import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
class SerializerDeserializerV3Test {
@Test
void testSerializeDeserializeTiny() throws IOException {
final Maze expected = new Maze(2, 2, 255, new Position(0, 0), new Position(1, 1));
new RandomDepthFirst(expected).run();
final byte[] bytes = SerializerDeserializerV3.serialize(expected);
final Maze result = SerializerDeserializerV3.deserialize(bytes);
assertThat(result).isEqualTo(expected);
}
@Test
void testSerializeDeserializeMedium() throws IOException {
final Maze expected = new Maze(20, 20, -271828182846L);
new Wilson(expected).run();
final byte[] bytes = SerializerDeserializerV3.serialize(expected);
final Maze result = SerializerDeserializerV3.deserialize(bytes);
assertThat(result).isEqualTo(expected);
}
@Test
void testSerializeDeserializeLarge() throws IOException {
final Maze expected = new Maze(200, 320, 3141592653589793238L);
new Wilson(expected).run();
final byte[] bytes = SerializerDeserializerV3.serialize(expected);
final Maze result = SerializerDeserializerV3.deserialize(bytes);
assertThat(result).isEqualTo(expected);
}
@Test
void testSerializeDeserializeLargeRandom() throws IOException {
final Maze expected = new Maze(200, 320, 3141592653589793238L);
new RandomDepthFirst(expected).run();
final byte[] bytes = SerializerDeserializerV3.serialize(expected);
final Maze result = SerializerDeserializerV3.deserialize(bytes);
assertThat(result).isEqualTo(expected);
}
}