Compare commits
No commits in common. "master" and "v0.0.4" have entirely different histories.
52 changed files with 902 additions and 1718 deletions
|
@ -3,7 +3,7 @@ type: docker
|
||||||
name: default
|
name: default
|
||||||
steps:
|
steps:
|
||||||
- name: build
|
- name: build
|
||||||
image: maven:3.9-eclipse-temurin-21
|
image: maven:3.8-openjdk-18-slim
|
||||||
commands:
|
commands:
|
||||||
- mvn clean install -DskipTests=true -Dmaven.javadoc.skip=true -B -V
|
- mvn clean install -DskipTests=true -Dmaven.javadoc.skip=true -B -V
|
||||||
when:
|
when:
|
||||||
|
@ -13,7 +13,7 @@ steps:
|
||||||
- refs/head/feature/**
|
- refs/head/feature/**
|
||||||
- refs/tags/**
|
- refs/tags/**
|
||||||
- name: test
|
- name: test
|
||||||
image: maven:3.9-eclipse-temurin-21
|
image: maven:3.8-openjdk-18-slim
|
||||||
commands:
|
commands:
|
||||||
- mvn test -B
|
- mvn test -B
|
||||||
when:
|
when:
|
||||||
|
@ -22,12 +22,10 @@ steps:
|
||||||
- master
|
- master
|
||||||
- feature/*
|
- feature/*
|
||||||
- name: deploy
|
- name: deploy
|
||||||
image: maven:3.9-eclipse-temurin-21
|
image: maven:3.8-openjdk-18-slim
|
||||||
environment:
|
environment:
|
||||||
REPO_TOKEN:
|
REPO_TOKEN:
|
||||||
from_secret: repo-token
|
from_secret: repo-token
|
||||||
REPO_TOKEN_OSSRH:
|
|
||||||
from_secret: repo-token-ossrh
|
|
||||||
commands:
|
commands:
|
||||||
- mvn -s maven-settings.xml deploy -DskipTests=true
|
- mvn -s maven-settings.xml deploy -DskipTests=true
|
||||||
when:
|
when:
|
||||||
|
|
|
@ -1 +1,2 @@
|
||||||
# maze-generator
|
# labyrinth-generator
|
||||||
|
|
||||||
|
|
|
@ -8,10 +8,5 @@
|
||||||
<username>ci</username>
|
<username>ci</username>
|
||||||
<password>${env.REPO_TOKEN}</password>
|
<password>${env.REPO_TOKEN}</password>
|
||||||
</server>
|
</server>
|
||||||
<server>
|
|
||||||
<id>ossrh</id>
|
|
||||||
<username>4etdRvZF</username>
|
|
||||||
<password>${env.REPO_TOKEN_OSSRH}</password>
|
|
||||||
</server>
|
|
||||||
</servers>
|
</servers>
|
||||||
</settings>
|
</settings>
|
||||||
|
|
|
@ -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>
|
|
185
pom.xml
185
pom.xml
|
@ -5,24 +5,26 @@
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>ch.fritteli</groupId>
|
<groupId>ch.fritteli</groupId>
|
||||||
<artifactId>fritteli-build-parent</artifactId>
|
<artifactId>fritteli-build-parent</artifactId>
|
||||||
<version>5.1.0</version>
|
<version>2.0.4</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<groupId>ch.fritteli.a-maze-r</groupId>
|
<groupId>ch.fritteli.labyrinth</groupId>
|
||||||
<artifactId>maze-generator</artifactId>
|
<artifactId>labyrinth-generator</artifactId>
|
||||||
<version>0.2.2-SNAPSHOT</version>
|
<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.
|
<properties>
|
||||||
</description>
|
<java.source.version>17</java.source.version>
|
||||||
<url>https://manuel.friedli.info/maze.html</url>
|
<java.target.version>17</java.target.version>
|
||||||
<inceptionYear>2022</inceptionYear>
|
<jetbrains-annotations.version>24.0.1</jetbrains-annotations.version>
|
||||||
|
<junit-jupiter.version>5.9.2</junit-jupiter.version>
|
||||||
<licenses>
|
<logback.version>1.4.6</logback.version>
|
||||||
<license>
|
<lombok.version>1.18.26</lombok.version>
|
||||||
<name>GNU Affero General Public License</name>
|
<pdfbox.version>2.0.27</pdfbox.version>
|
||||||
<url>https://www.gnu.org/licenses/agpl-3.0.html</url>
|
<slf4j.version>2.0.7</slf4j.version>
|
||||||
</license>
|
<vavr.version>0.10.4</vavr.version>
|
||||||
</licenses>
|
</properties>
|
||||||
|
|
||||||
<developers>
|
<developers>
|
||||||
<developer>
|
<developer>
|
||||||
|
@ -39,28 +41,6 @@
|
||||||
</developer>
|
</developer>
|
||||||
</developers>
|
</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>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
|
@ -79,23 +59,15 @@
|
||||||
<artifactId>pdfbox</artifactId>
|
<artifactId>pdfbox</artifactId>
|
||||||
<version>${pdfbox.version}</version>
|
<version>${pdfbox.version}</version>
|
||||||
</dependency>
|
</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>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
|
<version>${slf4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>ch.qos.logback</groupId>
|
<groupId>ch.qos.logback</groupId>
|
||||||
<artifactId>logback-classic</artifactId>
|
<artifactId>logback-classic</artifactId>
|
||||||
|
<version>${logback.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.jupiter</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
@ -104,27 +76,31 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
<artifactId>assertj-core</artifactId>
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>3.24.2</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.jsonschema2pojo</groupId>
|
<artifactId>maven-assembly-plugin</artifactId>
|
||||||
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
|
<configuration>
|
||||||
<version>${jsonschema2pojo-maven-plugin.version}</version>
|
<archive>
|
||||||
|
<manifest>
|
||||||
|
<mainClass>ch.fritteli.labyrinth.generator.Main</mainClass>
|
||||||
|
</manifest>
|
||||||
|
</archive>
|
||||||
|
<descriptorRefs>
|
||||||
|
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||||
|
</descriptorRefs>
|
||||||
|
</configuration>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<phase>generate-sources</phase>
|
<id>make-assembly</id>
|
||||||
|
<phase>package</phase>
|
||||||
<goals>
|
<goals>
|
||||||
<goal>generate</goal>
|
<goal>single</goal>
|
||||||
</goals>
|
</goals>
|
||||||
<configuration>
|
|
||||||
<sourcePaths>
|
|
||||||
<sourcePath>src/main/resources/maze.schema.json</sourcePath>
|
|
||||||
</sourcePaths>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
@ -144,55 +120,52 @@
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-site-plugin</artifactId>
|
<artifactId>maven-site-plugin</artifactId>
|
||||||
<version>${maven-site-plugin.version}</version>
|
<version>4.0.0-M6</version>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
<scm>
|
||||||
<profiles>
|
<connection>scm:git:https://gittr.ch/java/labyrinth-generator.git</connection>
|
||||||
<profile>
|
<developerConnection>scm:git:ssh://git@gittr.ch/java/labyrinth-generator.git</developerConnection>
|
||||||
<id>release</id>
|
<url>https://gittr.ch/java/labyrinth-generator</url>
|
||||||
<build>
|
<tag>v0.0.4</tag>
|
||||||
<plugins>
|
</scm>
|
||||||
<plugin>
|
<distributionManagement>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<repository>
|
||||||
<artifactId>maven-source-plugin</artifactId>
|
<id>repo.gittr.ch</id>
|
||||||
<executions>
|
<name>gittr.ch</name>
|
||||||
<execution>
|
<url>https://repo.gittr.ch/releases/</url>
|
||||||
<id>attach-sources</id>
|
</repository>
|
||||||
<goals>
|
<snapshotRepository>
|
||||||
<goal>jar-no-fork</goal>
|
<id>repo.gittr.ch</id>
|
||||||
</goals>
|
<name>gittr.ch</name>
|
||||||
</execution>
|
<url>https://repo.gittr.ch/snapshots/</url>
|
||||||
</executions>
|
</snapshotRepository>
|
||||||
</plugin>
|
</distributionManagement>
|
||||||
<plugin>
|
<repositories>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<repository>
|
||||||
<artifactId>maven-javadoc-plugin</artifactId>
|
<id>repo.gittr.ch.releases</id>
|
||||||
<executions>
|
<url>https://repo.gittr.ch/releases/</url>
|
||||||
<execution>
|
<releases>
|
||||||
<id>attach-javadocs</id>
|
<enabled>true</enabled>
|
||||||
<goals>
|
<updatePolicy>never</updatePolicy>
|
||||||
<goal>jar</goal>
|
</releases>
|
||||||
</goals>
|
<snapshots>
|
||||||
</execution>
|
<enabled>false</enabled>
|
||||||
</executions>
|
<updatePolicy>never</updatePolicy>
|
||||||
</plugin>
|
</snapshots>
|
||||||
<plugin>
|
</repository>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<repository>
|
||||||
<artifactId>maven-gpg-plugin</artifactId>
|
<id>repo.gittr.ch.snapshots</id>
|
||||||
<executions>
|
<url>https://repo.gittr.ch/snapshots/</url>
|
||||||
<execution>
|
<releases>
|
||||||
<id>sign-artifacts</id>
|
<enabled>false</enabled>
|
||||||
<phase>verify</phase>
|
<updatePolicy>never</updatePolicy>
|
||||||
<goals>
|
</releases>
|
||||||
<goal>sign</goal>
|
<snapshots>
|
||||||
</goals>
|
<enabled>true</enabled>
|
||||||
</execution>
|
<updatePolicy>always</updatePolicy>
|
||||||
</executions>
|
</snapshots>
|
||||||
</plugin>
|
</repository>
|
||||||
</plugins>
|
</repositories>
|
||||||
</build>
|
|
||||||
</profile>
|
|
||||||
</profiles>
|
|
||||||
</project>
|
</project>
|
||||||
|
|
51
src/main/java/ch/fritteli/labyrinth/generator/Main.java
Normal file
51
src/main/java/ch/fritteli/labyrinth/generator/Main.java
Normal 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();
|
||||||
|
}
|
||||||
|
}
|
|
@ -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()!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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)!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,13 +1,13 @@
|
||||||
package ch.fritteli.maze.generator.model;
|
package ch.fritteli.labyrinth.generator.model;
|
||||||
|
|
||||||
import io.vavr.collection.Stream;
|
import io.vavr.collection.Stream;
|
||||||
import io.vavr.control.Option;
|
import io.vavr.control.Option;
|
||||||
import lombok.AccessLevel;
|
import lombok.AccessLevel;
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import lombok.NonNull;
|
||||||
import lombok.ToString;
|
import lombok.ToString;
|
||||||
import lombok.experimental.FieldDefaults;
|
import lombok.experimental.FieldDefaults;
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
import java.util.EnumSet;
|
import java.util.EnumSet;
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
|
@ -32,24 +32,24 @@ public class Tile {
|
||||||
* @param walls
|
* @param walls
|
||||||
* @param solution
|
* @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) {
|
for (final Direction direction : walls) {
|
||||||
this.walls.set(direction);
|
this.walls.set(direction);
|
||||||
this.walls.seal(direction);
|
this.walls.harden(direction);
|
||||||
}
|
}
|
||||||
this.visited = true;
|
this.visited = true;
|
||||||
this.solution = solution;
|
this.solution = solution;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void preventDiggingToOrFrom(@NotNull final Direction direction) {
|
public void preventDiggingToOrFrom(@NonNull final Direction direction) {
|
||||||
this.walls.seal(direction);
|
this.walls.harden(direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void enableDiggingToOrFrom(@NotNull final Direction direction) {
|
public void enableDiggingToOrFrom(@NonNull final Direction direction) {
|
||||||
this.walls.unseal(direction);
|
this.walls.unharden(direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean digFrom(@NotNull final Direction direction) {
|
public boolean digFrom(@NonNull final Direction direction) {
|
||||||
if (this.visited) {
|
if (this.visited) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
@ -57,16 +57,16 @@ public class Tile {
|
||||||
return this.walls.clear(direction);
|
return this.walls.clear(direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean digTo(@NotNull final Direction direction) {
|
public boolean digTo(@NonNull final Direction direction) {
|
||||||
return this.walls.clear(direction);
|
return this.walls.clear(direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void undigTo(@NotNull final Direction direction) {
|
public void undigTo(@NonNull final Direction direction) {
|
||||||
this.walls.set(direction);
|
this.walls.set(direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Option<Direction> getRandomAvailableDirection(@NotNull final Random random) {
|
public Option<Direction> getRandomAvailableDirection(@NonNull final Random random) {
|
||||||
final Stream<Direction> availableDirections = this.walls.getUnsealedSet();
|
final Stream<Direction> availableDirections = this.walls.getUnhardenedSet();
|
||||||
if (availableDirections.isEmpty()) {
|
if (availableDirections.isEmpty()) {
|
||||||
return Option.none();
|
return Option.none();
|
||||||
}
|
}
|
||||||
|
@ -74,7 +74,7 @@ public class Tile {
|
||||||
return Option.of(availableDirections.get(index));
|
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);
|
return this.walls.isSet(direction);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
package ch.fritteli.maze.generator.model;
|
package ch.fritteli.labyrinth.generator.model;
|
||||||
|
|
||||||
import io.vavr.collection.Stream;
|
import io.vavr.collection.Stream;
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
|
import lombok.NonNull;
|
||||||
import lombok.ToString;
|
import lombok.ToString;
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
import java.util.EnumSet;
|
import java.util.EnumSet;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
@ -15,9 +15,9 @@ import java.util.TreeSet;
|
||||||
@ToString
|
@ToString
|
||||||
public class Walls {
|
public class Walls {
|
||||||
private final SortedSet<Direction> directions = new TreeSet<>();
|
private final SortedSet<Direction> directions = new TreeSet<>();
|
||||||
private final Set<Direction> sealed = new HashSet<>();
|
private final Set<Direction> hardened = new HashSet<>();
|
||||||
|
|
||||||
public void set(@NotNull final Direction direction) {
|
public void set(@NonNull final Direction direction) {
|
||||||
this.directions.add(direction);
|
this.directions.add(direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -25,30 +25,30 @@ public class Walls {
|
||||||
this.directions.addAll(EnumSet.allOf(Direction.class));
|
this.directions.addAll(EnumSet.allOf(Direction.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean clear(@NotNull final Direction direction) {
|
public boolean clear(@NonNull final Direction direction) {
|
||||||
if (this.sealed.contains(direction)) {
|
if (this.hardened.contains(direction)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return this.directions.remove(direction);
|
return this.directions.remove(direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isSet(@NotNull final Direction direction) {
|
public boolean isSet(@NonNull final Direction direction) {
|
||||||
return this.directions.contains(direction);
|
return this.directions.contains(direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Stream<Direction> getUnsealedSet() {
|
public Stream<Direction> getUnhardenedSet() {
|
||||||
return Stream.ofAll(this.directions)
|
return Stream.ofAll(this.directions)
|
||||||
.removeAll(this.sealed);
|
.removeAll(this.hardened);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void seal(@NotNull final Direction direction) {
|
public void harden(@NonNull final Direction direction) {
|
||||||
if (!this.directions.contains(direction)) {
|
if (!this.directions.contains(direction)) {
|
||||||
throw new IllegalStateException("Trying to seal cleared Direction: " + direction);
|
throw new IllegalStateException("Trying to harden cleared Direction: " + direction);
|
||||||
}
|
}
|
||||||
this.sealed.add(direction);
|
this.hardened.add(direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void unseal(@NotNull final Direction direction) {
|
public void unharden(@NonNull final Direction direction) {
|
||||||
this.sealed.remove(direction);
|
this.hardened.remove(direction);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -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);
|
||||||
|
}
|
|
@ -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.labyrinth.generator.model.Direction;
|
||||||
import ch.fritteli.maze.generator.model.Maze;
|
import ch.fritteli.labyrinth.generator.model.Labyrinth;
|
||||||
import ch.fritteli.maze.generator.model.Tile;
|
import ch.fritteli.labyrinth.generator.model.Tile;
|
||||||
import io.vavr.collection.HashSet;
|
import io.vavr.collection.HashSet;
|
||||||
import io.vavr.collection.Set;
|
import io.vavr.collection.Set;
|
||||||
import lombok.AccessLevel;
|
import lombok.AccessLevel;
|
||||||
|
import lombok.NonNull;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
|
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
|
||||||
class Generator {
|
class Generator {
|
||||||
private final Maze maze;
|
private final Labyrinth labyrinth;
|
||||||
private int y = 0;
|
private int y = 0;
|
||||||
|
|
||||||
boolean hasNext() {
|
boolean hasNext() {
|
||||||
return this.y < this.maze.getHeight();
|
return this.y < this.labyrinth.getHeight();
|
||||||
}
|
}
|
||||||
|
|
||||||
String next() {
|
String next() {
|
||||||
StringBuilder sb = new StringBuilder("<tr>");
|
StringBuilder sb = new StringBuilder("<tr>");
|
||||||
for (int x = 0; x < this.maze.getWidth(); x++) {
|
for (int x = 0; x < this.labyrinth.getWidth(); x++) {
|
||||||
final Tile currentTile = this.maze.getTileAt(x, this.y).get();
|
final Tile currentTile = this.labyrinth.getTileAt(x, this.y).get();
|
||||||
sb.append("<td class=\"");
|
sb.append("<td class=\"");
|
||||||
sb.append(this.getClasses(currentTile).mkString(" "));
|
sb.append(this.getClasses(currentTile).mkString(" "));
|
||||||
sb.append("\"> </td>");
|
sb.append("\"> </td>");
|
||||||
|
@ -31,7 +31,7 @@ class Generator {
|
||||||
return sb.toString();
|
return sb.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
private Set<String> getClasses(@NotNull final Tile tile) {
|
private Set<String> getClasses(@NonNull final Tile tile) {
|
||||||
Set<String> result = HashSet.empty();
|
Set<String> result = HashSet.empty();
|
||||||
if (tile.hasWallAt(Direction.TOP)) {
|
if (tile.hasWallAt(Direction.TOP)) {
|
||||||
result = result.add("top");
|
result = result.add("top");
|
|
@ -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>";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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.labyrinth.generator.model.Labyrinth;
|
||||||
import ch.fritteli.maze.generator.renderer.Renderer;
|
import ch.fritteli.labyrinth.generator.renderer.Renderer;
|
||||||
import ch.fritteli.maze.generator.renderer.html.HTMLRenderer;
|
import ch.fritteli.labyrinth.generator.renderer.html.HTMLRenderer;
|
||||||
import io.vavr.control.Option;
|
import io.vavr.control.Option;
|
||||||
import io.vavr.control.Try;
|
import io.vavr.control.Try;
|
||||||
|
import lombok.NonNull;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
@ -17,19 +17,19 @@ import java.util.NoSuchElementException;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class HTMLFileRenderer implements Renderer<Path> {
|
public class HTMLFileRenderer implements Renderer<Path> {
|
||||||
@NotNull
|
@NonNull
|
||||||
private static final HTMLRenderer HTML_RENDERER = HTMLRenderer.newInstance();
|
private static final HTMLRenderer HTML_RENDERER = HTMLRenderer.newInstance();
|
||||||
@NotNull
|
@NonNull
|
||||||
private Option<Path> targetFile;
|
private Option<Path> targetFile;
|
||||||
|
|
||||||
private HTMLFileRenderer() {
|
private HTMLFileRenderer() {
|
||||||
this.targetFile = Try
|
this.targetFile = Try
|
||||||
.of(() -> Files.createTempFile("maze_", ".html"))
|
.of(() -> Files.createTempFile("labyrinth_", ".html"))
|
||||||
.onFailure(ex -> log.error("Unable to set default target file.", ex))
|
.onFailure(ex -> log.error("Unable to set default target file.", ex))
|
||||||
.toOption();
|
.toOption();
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
public static HTMLFileRenderer newInstance() {
|
public static HTMLFileRenderer newInstance() {
|
||||||
return new HTMLFileRenderer();
|
return new HTMLFileRenderer();
|
||||||
}
|
}
|
||||||
|
@ -40,15 +40,15 @@ public class HTMLFileRenderer implements Renderer<Path> {
|
||||||
.exists(File::canWrite);
|
.exists(File::canWrite);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
public HTMLFileRenderer setTargetFile(@NotNull final Path targetFile) {
|
public HTMLFileRenderer setTargetFile(@NonNull final Path targetFile) {
|
||||||
this.targetFile = Option.of(targetFile);
|
this.targetFile = Option.of(targetFile);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
@Override
|
@Override
|
||||||
public Path render(@NotNull final Maze maze) {
|
public Path render(@NonNull final Labyrinth labyrinth) {
|
||||||
if (!this.isTargetFileDefinedAndWritable()) {
|
if (!this.isTargetFileDefinedAndWritable()) {
|
||||||
try {
|
try {
|
||||||
Files.createFile(this.targetFile.get());
|
Files.createFile(this.targetFile.get());
|
||||||
|
@ -56,7 +56,7 @@ public class HTMLFileRenderer implements Renderer<Path> {
|
||||||
throw new IllegalArgumentException("Cannot write to target file.", e);
|
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();
|
final Path targetFile = this.targetFile.get();
|
||||||
try {
|
try {
|
||||||
Files.writeString(targetFile, html, StandardCharsets.UTF_8);
|
Files.writeString(targetFile, html, StandardCharsets.UTF_8);
|
|
@ -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.labyrinth.generator.model.Direction;
|
||||||
import ch.fritteli.maze.generator.model.Maze;
|
import ch.fritteli.labyrinth.generator.model.Labyrinth;
|
||||||
import ch.fritteli.maze.generator.model.Position;
|
import ch.fritteli.labyrinth.generator.model.Position;
|
||||||
import ch.fritteli.maze.generator.model.Tile;
|
import ch.fritteli.labyrinth.generator.model.Tile;
|
||||||
import io.vavr.control.Option;
|
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.RequiredArgsConstructor;
|
||||||
import lombok.Value;
|
import lombok.Value;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
@ -13,28 +18,23 @@ import org.apache.pdfbox.pdmodel.PDDocumentInformation;
|
||||||
import org.apache.pdfbox.pdmodel.PDPage;
|
import org.apache.pdfbox.pdmodel.PDPage;
|
||||||
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
||||||
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
import java.awt.*;
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@Slf4j
|
@Slf4j
|
||||||
class Generator {
|
class Generator {
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
private final Maze maze;
|
private final Labyrinth labyrinth;
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
public ByteArrayOutputStream generate() {
|
public ByteArrayOutputStream generate() {
|
||||||
final float pageWidth = this.maze.getWidth() * PDFRenderer.SCALE + 2 * PDFRenderer.MARGIN;
|
final float pageWidth = this.labyrinth.getWidth() * PDFRenderer.SCALE + 2 * PDFRenderer.MARGIN;
|
||||||
final float pageHeight = this.maze.getHeight() * PDFRenderer.SCALE + 2 * PDFRenderer.MARGIN;
|
final float pageHeight = this.labyrinth.getHeight() * PDFRenderer.SCALE + 2 * PDFRenderer.MARGIN;
|
||||||
|
|
||||||
final PDDocument pdDocument = new PDDocument();
|
final PDDocument pdDocument = new PDDocument();
|
||||||
final PDDocumentInformation info = new PDDocumentInformation();
|
final PDDocumentInformation info = new PDDocumentInformation();
|
||||||
info.setTitle("Maze %sx%s, ID %s".formatted(this.maze.getWidth(), this.maze.getHeight(), this.maze.getRandomSeed()));
|
info.setTitle("Labyrinth %sx%s, ID %s".formatted(this.labyrinth.getWidth(), this.labyrinth.getHeight(), this.labyrinth.getRandomSeed()));
|
||||||
pdDocument.setDocumentInformation(info);
|
pdDocument.setDocumentInformation(info);
|
||||||
final PDPage puzzlePage = new PDPage(new PDRectangle(pageWidth, pageHeight));
|
final PDPage puzzlePage = new PDPage(new PDRectangle(pageWidth, pageHeight));
|
||||||
final PDPage solutionPage = new PDPage(new PDRectangle(pageWidth, pageHeight));
|
final PDPage solutionPage = new PDPage(new PDRectangle(pageWidth, pageHeight));
|
||||||
|
@ -60,7 +60,7 @@ class Generator {
|
||||||
return output;
|
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.setLineCapStyle(BasicStroke.CAP_ROUND);
|
||||||
pageContentStream.setLineJoinStyle(BasicStroke.JOIN_ROUND);
|
pageContentStream.setLineJoinStyle(BasicStroke.JOIN_ROUND);
|
||||||
pageContentStream.setLineWidth(1.0f);
|
pageContentStream.setLineWidth(1.0f);
|
||||||
|
@ -68,15 +68,15 @@ class Generator {
|
||||||
pageContentStream.setNonStrokingColor(Color.BLACK);
|
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.
|
// 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);
|
Coordinate coordinate = new Coordinate(0f, 0f);
|
||||||
// Draw the TOP borders of all tiles.
|
// 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;
|
boolean isPainting = false;
|
||||||
coordinate = coordinate.withY(y);
|
coordinate = coordinate.withY(y);
|
||||||
for (int x = 0; x < this.maze.getWidth(); x++) {
|
for (int x = 0; x < this.labyrinth.getWidth(); x++) {
|
||||||
final Tile currentTile = this.maze.getTileAt(x, y).get();
|
final Tile currentTile = this.labyrinth.getTileAt(x, y).get();
|
||||||
coordinate = coordinate.withX(x);
|
coordinate = coordinate.withX(x);
|
||||||
if (currentTile.hasWallAt(Direction.TOP)) {
|
if (currentTile.hasWallAt(Direction.TOP)) {
|
||||||
if (!isPainting) {
|
if (!isPainting) {
|
||||||
|
@ -96,7 +96,7 @@ class Generator {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isPainting) {
|
if (isPainting) {
|
||||||
coordinate = coordinate.withX(this.maze.getWidth());
|
coordinate = coordinate.withX(this.labyrinth.getWidth());
|
||||||
for (final PDPageContentStream contentStream : contentStreams) {
|
for (final PDPageContentStream contentStream : contentStreams) {
|
||||||
contentStream.lineTo(coordinate.getX(), coordinate.getY());
|
contentStream.lineTo(coordinate.getX(), coordinate.getY());
|
||||||
contentStream.stroke();
|
contentStream.stroke();
|
||||||
|
@ -105,10 +105,10 @@ class Generator {
|
||||||
}
|
}
|
||||||
// Draw the BOTTOM border of the last row of tiles.
|
// Draw the BOTTOM border of the last row of tiles.
|
||||||
boolean isPainting = false;
|
boolean isPainting = false;
|
||||||
int y = this.maze.getHeight();
|
int y = this.labyrinth.getHeight();
|
||||||
coordinate = coordinate.withY(this.maze.getHeight());
|
coordinate = coordinate.withY(this.labyrinth.getHeight());
|
||||||
for (int x = 0; x < this.maze.getWidth(); x++) {
|
for (int x = 0; x < this.labyrinth.getWidth(); x++) {
|
||||||
final Tile currentTile = this.maze.getTileAt(x, y - 1).get();
|
final Tile currentTile = this.labyrinth.getTileAt(x, y - 1).get();
|
||||||
coordinate = coordinate.withX(x);
|
coordinate = coordinate.withX(x);
|
||||||
if (currentTile.hasWallAt(Direction.BOTTOM)) {
|
if (currentTile.hasWallAt(Direction.BOTTOM)) {
|
||||||
if (!isPainting) {
|
if (!isPainting) {
|
||||||
|
@ -128,7 +128,7 @@ class Generator {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isPainting) {
|
if (isPainting) {
|
||||||
coordinate = coordinate.withX(this.maze.getWidth());
|
coordinate = coordinate.withX(this.labyrinth.getWidth());
|
||||||
for (final PDPageContentStream contentStream : contentStreams) {
|
for (final PDPageContentStream contentStream : contentStreams) {
|
||||||
contentStream.lineTo(coordinate.getX(), coordinate.getY());
|
contentStream.lineTo(coordinate.getX(), coordinate.getY());
|
||||||
contentStream.stroke();
|
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.
|
// 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);
|
Coordinate coordinate = new Coordinate(0f, 0f);
|
||||||
// Draw the LEFT borders of all tiles.
|
// 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;
|
boolean isPainting = false;
|
||||||
coordinate = coordinate.withX(x);
|
coordinate = coordinate.withX(x);
|
||||||
for (int y = 0; y < this.maze.getHeight(); y++) {
|
for (int y = 0; y < this.labyrinth.getHeight(); y++) {
|
||||||
final Tile currentTile = this.maze.getTileAt(x, y).get();
|
final Tile currentTile = this.labyrinth.getTileAt(x, y).get();
|
||||||
coordinate = coordinate.withY(y);
|
coordinate = coordinate.withY(y);
|
||||||
if (currentTile.hasWallAt(Direction.LEFT)) {
|
if (currentTile.hasWallAt(Direction.LEFT)) {
|
||||||
if (!isPainting) {
|
if (!isPainting) {
|
||||||
|
@ -164,7 +164,7 @@ class Generator {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isPainting) {
|
if (isPainting) {
|
||||||
coordinate = coordinate.withY(this.maze.getHeight());
|
coordinate = coordinate.withY(this.labyrinth.getHeight());
|
||||||
for (final PDPageContentStream contentStream : contentStreams) {
|
for (final PDPageContentStream contentStream : contentStreams) {
|
||||||
contentStream.lineTo(coordinate.getX(), coordinate.getY());
|
contentStream.lineTo(coordinate.getX(), coordinate.getY());
|
||||||
contentStream.stroke();
|
contentStream.stroke();
|
||||||
|
@ -173,10 +173,10 @@ class Generator {
|
||||||
}
|
}
|
||||||
// Draw the RIGHT border of the last column of tiles.
|
// Draw the RIGHT border of the last column of tiles.
|
||||||
boolean isPainting = false;
|
boolean isPainting = false;
|
||||||
int x = this.maze.getWidth();
|
int x = this.labyrinth.getWidth();
|
||||||
coordinate = coordinate.withX(this.maze.getWidth());
|
coordinate = coordinate.withX(this.labyrinth.getWidth());
|
||||||
for (int y = 0; y < this.maze.getHeight(); y++) {
|
for (int y = 0; y < this.labyrinth.getHeight(); y++) {
|
||||||
final Tile currentTile = this.maze.getTileAt(x - 1, y).get();
|
final Tile currentTile = this.labyrinth.getTileAt(x - 1, y).get();
|
||||||
coordinate = coordinate.withY(y);
|
coordinate = coordinate.withY(y);
|
||||||
if (currentTile.hasWallAt(Direction.RIGHT)) {
|
if (currentTile.hasWallAt(Direction.RIGHT)) {
|
||||||
if (!isPainting) {
|
if (!isPainting) {
|
||||||
|
@ -196,7 +196,7 @@ class Generator {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isPainting) {
|
if (isPainting) {
|
||||||
coordinate = coordinate.withY(this.maze.getHeight());
|
coordinate = coordinate.withY(this.labyrinth.getHeight());
|
||||||
for (final PDPageContentStream contentStream : contentStreams) {
|
for (final PDPageContentStream contentStream : contentStreams) {
|
||||||
contentStream.lineTo(coordinate.getX(), coordinate.getY());
|
contentStream.lineTo(coordinate.getX(), coordinate.getY());
|
||||||
contentStream.stroke();
|
contentStream.stroke();
|
||||||
|
@ -204,32 +204,32 @@ 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
|
// Draw the solution in red
|
||||||
pageContentStream.setStrokingColor(Color.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.
|
// 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();
|
final Position end = this.labyrinth.getEnd();
|
||||||
Position currentPosition = this.maze.getStart();
|
Position currentPosition = this.labyrinth.getStart();
|
||||||
Position previousPosition = null;
|
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());
|
pageContentStream.moveTo(coordinate.getX(), coordinate.getY());
|
||||||
do {
|
do {
|
||||||
Position newCurrent = this.findNextSolutionPosition(previousPosition, currentPosition);
|
Position newCurrent = this.findNextSolutionPosition(previousPosition, currentPosition);
|
||||||
previousPosition = currentPosition;
|
previousPosition = currentPosition;
|
||||||
currentPosition = newCurrent;
|
currentPosition = newCurrent;
|
||||||
coordinate = new SolutionCoordinate(currentPosition.x(), currentPosition.y());
|
coordinate = new SolutionCoordinate(currentPosition.getX(), currentPosition.getY());
|
||||||
pageContentStream.lineTo(coordinate.getX(), coordinate.getY());
|
pageContentStream.lineTo(coordinate.getX(), coordinate.getY());
|
||||||
} while (!currentPosition.equals(end));
|
} while (!currentPosition.equals(end));
|
||||||
pageContentStream.stroke();
|
pageContentStream.stroke();
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
private Position findNextSolutionPosition(@Nullable final Position previousPosition, @NotNull final Position currentPosition) {
|
private Position findNextSolutionPosition(@Nullable final Position previousPosition, @NonNull final Position currentPosition) {
|
||||||
final Tile currentTile = this.maze.getTileAt(currentPosition).get();
|
final Tile currentTile = this.labyrinth.getTileAt(currentPosition).get();
|
||||||
for (final Direction direction : Direction.values()) {
|
for (final Direction direction : Direction.values()) {
|
||||||
if (!currentTile.hasWallAt(direction)) {
|
if (!currentTile.hasWallAt(direction)) {
|
||||||
final Position position = currentPosition.move(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)) {
|
if (position.equals(previousPosition)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
@ -265,7 +265,7 @@ class Generator {
|
||||||
}
|
}
|
||||||
|
|
||||||
private float calcY(final int y) {
|
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) {
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,10 +1,9 @@
|
||||||
package ch.fritteli.maze.generator.renderer.pdf;
|
package ch.fritteli.labyrinth.generator.renderer.pdf;
|
||||||
|
|
||||||
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 java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import lombok.NonNull;
|
||||||
|
|
||||||
public class PDFRenderer implements Renderer<ByteArrayOutputStream> {
|
public class PDFRenderer implements Renderer<ByteArrayOutputStream> {
|
||||||
static final float MARGIN = 10;
|
static final float MARGIN = 10;
|
||||||
|
@ -13,15 +12,15 @@ public class PDFRenderer implements Renderer<ByteArrayOutputStream> {
|
||||||
private PDFRenderer() {
|
private PDFRenderer() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
public static PDFRenderer newInstance() {
|
public static PDFRenderer newInstance() {
|
||||||
return new PDFRenderer();
|
return new PDFRenderer();
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
@Override
|
@Override
|
||||||
public ByteArrayOutputStream render(@NotNull final Maze maze) {
|
public ByteArrayOutputStream render(@NonNull final Labyrinth labyrinth) {
|
||||||
final Generator generator = new Generator(maze);
|
final Generator generator = new Generator(labyrinth);
|
||||||
return generator.generate();
|
return generator.generate();
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -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.labyrinth.generator.model.Labyrinth;
|
||||||
import ch.fritteli.maze.generator.renderer.Renderer;
|
import ch.fritteli.labyrinth.generator.renderer.Renderer;
|
||||||
import ch.fritteli.maze.generator.renderer.pdf.PDFRenderer;
|
import ch.fritteli.labyrinth.generator.renderer.pdf.PDFRenderer;
|
||||||
import io.vavr.control.Option;
|
import io.vavr.control.Option;
|
||||||
import io.vavr.control.Try;
|
import io.vavr.control.Try;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
|
import lombok.NonNull;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class PDFFileRenderer implements Renderer<Path> {
|
public class PDFFileRenderer implements Renderer<Path> {
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
private static final PDFRenderer PDF_RENDERER = PDFRenderer.newInstance();
|
private static final PDFRenderer PDF_RENDERER = PDFRenderer.newInstance();
|
||||||
@NotNull
|
@NonNull
|
||||||
private Option<Path> targetFile;
|
private Option<Path> targetFile;
|
||||||
|
|
||||||
private PDFFileRenderer() {
|
private PDFFileRenderer() {
|
||||||
this.targetFile = Try
|
this.targetFile = Try
|
||||||
.of(() -> Files.createTempFile("maze_", ".pdf"))
|
.of(() -> Files.createTempFile("labyrinth_", ".pdf"))
|
||||||
.onFailure(ex -> log.error("Unable to set default target file.", ex))
|
.onFailure(ex -> log.error("Unable to set default target file.", ex))
|
||||||
.toOption();
|
.toOption();
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
public static PDFFileRenderer newInstance() {
|
public static PDFFileRenderer newInstance() {
|
||||||
return new PDFFileRenderer();
|
return new PDFFileRenderer();
|
||||||
}
|
}
|
||||||
|
@ -41,15 +40,15 @@ public class PDFFileRenderer implements Renderer<Path> {
|
||||||
.exists(File::canWrite);
|
.exists(File::canWrite);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
public PDFFileRenderer setTargetFile(@NotNull final Path targetFile) {
|
public PDFFileRenderer setTargetFile(@NonNull final Path targetFile) {
|
||||||
this.targetFile = Option.of(targetFile);
|
this.targetFile = Option.of(targetFile);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
@Override
|
@Override
|
||||||
public Path render(@NotNull final Maze maze) {
|
public Path render(@NonNull final Labyrinth labyrinth) {
|
||||||
if (!this.isTargetFileDefinedAndWritable()) {
|
if (!this.isTargetFileDefinedAndWritable()) {
|
||||||
try {
|
try {
|
||||||
Files.createFile(this.targetFile.get());
|
Files.createFile(this.targetFile.get());
|
||||||
|
@ -57,7 +56,7 @@ public class PDFFileRenderer implements Renderer<Path> {
|
||||||
throw new IllegalArgumentException("Cannot write to target file.", e);
|
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();
|
final Path outputFile = this.targetFile.get();
|
||||||
try {
|
try {
|
||||||
bytes.writeTo(Files.newOutputStream(outputFile));
|
bytes.writeTo(Files.newOutputStream(outputFile));
|
|
@ -1,4 +1,4 @@
|
||||||
package ch.fritteli.maze.generator.renderer.text;
|
package ch.fritteli.labyrinth.generator.renderer.text;
|
||||||
|
|
||||||
import lombok.AccessLevel;
|
import lombok.AccessLevel;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
|
@ -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.labyrinth.generator.model.Direction;
|
||||||
import ch.fritteli.maze.generator.model.Maze;
|
import ch.fritteli.labyrinth.generator.model.Labyrinth;
|
||||||
import ch.fritteli.maze.generator.model.Tile;
|
import ch.fritteli.labyrinth.generator.model.Tile;
|
||||||
import io.vavr.control.Option;
|
import io.vavr.control.Option;
|
||||||
import lombok.AccessLevel;
|
import lombok.AccessLevel;
|
||||||
|
import lombok.NonNull;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
|
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
|
||||||
class Generator {
|
class Generator {
|
||||||
@NotNull
|
@NonNull
|
||||||
private final Maze maze;
|
private final Labyrinth labyrinth;
|
||||||
private final boolean renderSolution;
|
private final boolean renderSolution;
|
||||||
private int x = 0;
|
private int x = 0;
|
||||||
private int y = 0;
|
private int y = 0;
|
||||||
|
@ -25,21 +25,30 @@ class Generator {
|
||||||
private int line = 0;
|
private int line = 0;
|
||||||
|
|
||||||
boolean hasNext() {
|
boolean hasNext() {
|
||||||
return this.y < this.maze.getHeight();
|
return this.y < this.labyrinth.getHeight();
|
||||||
}
|
}
|
||||||
|
|
||||||
String next() {
|
String next() {
|
||||||
final Tile currentTile = this.maze.getTileAt(this.x, this.y).get();
|
final Tile currentTile = this.labyrinth.getTileAt(this.x, this.y).get();
|
||||||
final Option<Tile> topTile = this.maze.getTileAt(this.x, this.y - 1);
|
final Option<Tile> topTile = this.labyrinth.getTileAt(this.x, this.y - 1);
|
||||||
final Option<Tile> rightTile = this.maze.getTileAt(this.x + 1, this.y);
|
final Option<Tile> rightTile = this.labyrinth.getTileAt(this.x + 1, this.y);
|
||||||
final Option<Tile> bottomTile = this.maze.getTileAt(this.x, this.y + 1);
|
final Option<Tile> bottomTile = this.labyrinth.getTileAt(this.x, this.y + 1);
|
||||||
final Option<Tile> leftTile = this.maze.getTileAt(this.x - 1, this.y);
|
final Option<Tile> leftTile = this.labyrinth.getTileAt(this.x - 1, this.y);
|
||||||
final String s = switch (this.line) {
|
final String s;
|
||||||
case 0 -> this.renderTopLine(currentTile, leftTile, topTile);
|
switch (this.line) {
|
||||||
case 1 -> this.renderCenterLine(currentTile, topTile, rightTile, bottomTile, leftTile);
|
case 0:
|
||||||
case 2 -> this.renderBottomLine(currentTile, leftTile);
|
s = this.renderTopLine(currentTile, leftTile, topTile);
|
||||||
default -> "";
|
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();
|
this.prepareNextStep();
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
@ -47,13 +56,13 @@ class Generator {
|
||||||
private void prepareNextStep() {
|
private void prepareNextStep() {
|
||||||
// do some magic ...
|
// do some magic ...
|
||||||
this.x++;
|
this.x++;
|
||||||
if (this.x == this.maze.getWidth()) {
|
if (this.x == this.labyrinth.getWidth()) {
|
||||||
// Reached the end of the row?
|
// Reached the end of the row?
|
||||||
// On to the next line then!
|
// On to the next line then!
|
||||||
this.x = 0;
|
this.x = 0;
|
||||||
this.line++;
|
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?
|
// Finished rendering the center line, and more rows available?
|
||||||
// On to the next row then!
|
// On to the next row then!
|
||||||
this.line = 0;
|
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 charDef1 = new CharDefinition();
|
||||||
final CharDefinition charDef2 = new CharDefinition();
|
final CharDefinition charDef2 = new CharDefinition();
|
||||||
final CharDefinition charDef3 = new CharDefinition();
|
final CharDefinition charDef3 = new CharDefinition();
|
||||||
|
@ -97,17 +106,17 @@ class Generator {
|
||||||
charDef3.up();
|
charDef3.up();
|
||||||
}
|
}
|
||||||
result = charDef1.toString() + charDef2;
|
result = charDef1.toString() + charDef2;
|
||||||
if (this.x == this.maze.getWidth() - 1) {
|
if (this.x == this.labyrinth.getWidth() - 1) {
|
||||||
result += charDef3 + "\n";
|
result += charDef3 + "\n";
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String renderCenterLine(@NotNull final Tile currentTile,
|
private String renderCenterLine(@NonNull final Tile currentTile,
|
||||||
@NotNull final Option<Tile> topTile,
|
@NonNull final Option<Tile> topTile,
|
||||||
@NotNull final Option<Tile> rightTile,
|
@NonNull final Option<Tile> rightTile,
|
||||||
@NotNull final Option<Tile> bottomTile,
|
@NonNull final Option<Tile> bottomTile,
|
||||||
@NotNull final Option<Tile> leftTile) {
|
@NonNull final Option<Tile> leftTile) {
|
||||||
final CharDefinition charDef1 = new CharDefinition();
|
final CharDefinition charDef1 = new CharDefinition();
|
||||||
final CharDefinition charDef2 = new CharDefinition();
|
final CharDefinition charDef2 = new CharDefinition();
|
||||||
final CharDefinition charDef3 = new CharDefinition();
|
final CharDefinition charDef3 = new CharDefinition();
|
||||||
|
@ -144,14 +153,14 @@ class Generator {
|
||||||
|
|
||||||
result = charDef1.toString() + charDef2;
|
result = charDef1.toString() + charDef2;
|
||||||
|
|
||||||
if (this.x == this.maze.getWidth() - 1) {
|
if (this.x == this.labyrinth.getWidth() - 1) {
|
||||||
result += charDef3 + "\n";
|
result += charDef3 + "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
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;
|
String result;
|
||||||
final CharDefinition charDef1 = new CharDefinition();
|
final CharDefinition charDef1 = new CharDefinition();
|
||||||
final CharDefinition charDef2 = new CharDefinition();
|
final CharDefinition charDef2 = new CharDefinition();
|
||||||
|
@ -178,21 +187,21 @@ class Generator {
|
||||||
|
|
||||||
result = charDef1.toString() + charDef2;
|
result = charDef1.toString() + charDef2;
|
||||||
|
|
||||||
if (this.x == this.maze.getWidth() - 1) {
|
if (this.x == this.labyrinth.getWidth() - 1) {
|
||||||
result += charDef3;
|
result += charDef3;
|
||||||
}
|
}
|
||||||
return result;
|
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);
|
return tile.map(t -> t.hasWallAt(direction)).getOrElse(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isSolution(@NotNull final Tile tile) {
|
private boolean isSolution(@NonNull final Tile tile) {
|
||||||
return this.renderSolution && tile.isSolution();
|
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);
|
return this.renderSolution && tile.map(Tile::isSolution).getOrElse(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -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.labyrinth.generator.model.Labyrinth;
|
||||||
import ch.fritteli.maze.generator.renderer.Renderer;
|
import ch.fritteli.labyrinth.generator.renderer.Renderer;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import lombok.NonNull;
|
||||||
|
|
||||||
public class TextRenderer implements Renderer<String> {
|
public class TextRenderer implements Renderer<String> {
|
||||||
private boolean renderSolution;
|
private boolean renderSolution;
|
||||||
|
@ -11,24 +11,24 @@ public class TextRenderer implements Renderer<String> {
|
||||||
this.renderSolution = false;
|
this.renderSolution = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
public static TextRenderer newInstance() {
|
public static TextRenderer newInstance() {
|
||||||
return new TextRenderer();
|
return new TextRenderer();
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
public TextRenderer setRenderSolution(final boolean renderSolution) {
|
public TextRenderer setRenderSolution(final boolean renderSolution) {
|
||||||
this.renderSolution = renderSolution;
|
this.renderSolution = renderSolution;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
@Override
|
@Override
|
||||||
public String render(@NotNull final Maze maze) {
|
public String render(@NonNull final Labyrinth labyrinth) {
|
||||||
if (maze.getWidth() == 0 || maze.getHeight() == 0) {
|
if (labyrinth.getWidth() == 0 || labyrinth.getHeight() == 0) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
final Generator generator = new Generator(maze, this.renderSolution);
|
final Generator generator = new Generator(labyrinth, this.renderSolution);
|
||||||
final StringBuilder sb = new StringBuilder();
|
final StringBuilder sb = new StringBuilder();
|
||||||
while (generator.hasNext()) {
|
while (generator.hasNext()) {
|
||||||
sb.append(generator.next());
|
sb.append(generator.next());
|
|
@ -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.labyrinth.generator.model.Labyrinth;
|
||||||
import ch.fritteli.maze.generator.renderer.Renderer;
|
import ch.fritteli.labyrinth.generator.renderer.Renderer;
|
||||||
import ch.fritteli.maze.generator.renderer.text.TextRenderer;
|
import ch.fritteli.labyrinth.generator.renderer.text.TextRenderer;
|
||||||
import io.vavr.collection.List;
|
import io.vavr.collection.List;
|
||||||
import io.vavr.control.Option;
|
import io.vavr.control.Option;
|
||||||
import io.vavr.control.Try;
|
import io.vavr.control.Try;
|
||||||
|
import lombok.NonNull;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
public class TextFileRenderer implements Renderer<List<Path>> {
|
public class TextFileRenderer implements Renderer<List<Path>> {
|
||||||
@NotNull
|
@NonNull
|
||||||
private static final TextRenderer TEXT_RENDERER = TextRenderer.newInstance();
|
private static final TextRenderer TEXT_RENDERER = TextRenderer.newInstance();
|
||||||
@NotNull
|
@NonNull
|
||||||
private Option<Path> targetMazeFile;
|
private Option<Path> targetLabyrinthFile;
|
||||||
@NotNull
|
@NonNull
|
||||||
private Option<Path> targetSolutionFile;
|
private Option<Path> targetSolutionFile;
|
||||||
|
|
||||||
private TextFileRenderer() {
|
private TextFileRenderer() {
|
||||||
this.targetMazeFile = Try
|
this.targetLabyrinthFile = Try
|
||||||
.of(() -> Files.createTempFile("maze_", ".txt"))
|
.of(() -> Files.createTempFile("labyrinth_", ".txt"))
|
||||||
.onFailure(ex -> log.error("Unable to set default target file", ex))
|
.onFailure(ex -> log.error("Unable to set default target file", ex))
|
||||||
.toOption();
|
.toOption();
|
||||||
|
|
||||||
this.targetSolutionFile = this.targetMazeFile.toTry()
|
this.targetSolutionFile = this.targetLabyrinthFile.toTry()
|
||||||
.map(Path::getParent)
|
.map(Path::getParent)
|
||||||
.flatMap(parent -> this.targetMazeFile.toTry()
|
.flatMap(parent -> this.targetLabyrinthFile.toTry()
|
||||||
.map(Path::getFileName)
|
.map(Path::getFileName)
|
||||||
.map(Path::toString)
|
.map(Path::toString)
|
||||||
.map(a -> a.replace(".txt", "-solution.txt"))
|
.map(a -> a.replace(".txt", "-solution.txt"))
|
||||||
|
@ -41,13 +42,13 @@ public class TextFileRenderer implements Renderer<List<Path>> {
|
||||||
.toOption();
|
.toOption();
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
public static TextFileRenderer newInstance() {
|
public static TextFileRenderer newInstance() {
|
||||||
return new TextFileRenderer();
|
return new TextFileRenderer();
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isTargetMazeFileDefinedAndWritable() {
|
public boolean isTargetLabyrinthFileDefinedAndWritable() {
|
||||||
return this.targetMazeFile
|
return this.targetLabyrinthFile
|
||||||
.map(Path::toFile)
|
.map(Path::toFile)
|
||||||
.exists(File::canWrite);
|
.exists(File::canWrite);
|
||||||
}
|
}
|
||||||
|
@ -58,27 +59,27 @@ public class TextFileRenderer implements Renderer<List<Path>> {
|
||||||
.exists(File::canWrite);
|
.exists(File::canWrite);
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
public TextFileRenderer setTargetMazeFile(@NotNull final Path targetMazeFile) {
|
public TextFileRenderer setTargetLabyrinthFile(@NonNull final Path targetLabyrinthFile) {
|
||||||
this.targetMazeFile = Option.of(targetMazeFile);
|
this.targetLabyrinthFile = Option.of(targetLabyrinthFile);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
public TextFileRenderer setTargetSolutionFile(@NotNull final Path targetSolutionFile) {
|
public TextFileRenderer setTargetSolutionFile(@NonNull final Path targetSolutionFile) {
|
||||||
this.targetSolutionFile = Option.of(targetSolutionFile);
|
this.targetSolutionFile = Option.of(targetSolutionFile);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
@Override
|
@Override
|
||||||
public List<Path> render(@NotNull final Maze maze) {
|
public List<Path> render(@NonNull final Labyrinth labyrinth) {
|
||||||
if (!this.isTargetMazeFileDefinedAndWritable()) {
|
if (!this.isTargetLabyrinthFileDefinedAndWritable()) {
|
||||||
try {
|
try {
|
||||||
Files.createFile(this.targetMazeFile.get());
|
Files.createFile(this.targetLabyrinthFile.get());
|
||||||
} catch (IOException | NoSuchElementException e) {
|
} catch (IOException | NoSuchElementException e) {
|
||||||
log.error("Cannot write to target maze file.", e);
|
log.error("Cannot write to target labyrinth file.", e);
|
||||||
throw new IllegalArgumentException("Cannot write to target maze file.", e);
|
throw new IllegalArgumentException("Cannot write to target labyrinth file.", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!this.isTargetSolutionFileDefinedAndWritable()) {
|
if (!this.isTargetSolutionFileDefinedAndWritable()) {
|
||||||
|
@ -91,21 +92,21 @@ public class TextFileRenderer implements Renderer<List<Path>> {
|
||||||
final String text;
|
final String text;
|
||||||
final String solution;
|
final String solution;
|
||||||
synchronized (TEXT_RENDERER) {
|
synchronized (TEXT_RENDERER) {
|
||||||
text = TEXT_RENDERER.setRenderSolution(false).render(maze).strip();
|
text = TEXT_RENDERER.setRenderSolution(false).render(labyrinth).strip();
|
||||||
solution = TEXT_RENDERER.setRenderSolution(true).render(maze).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();
|
final Path targetSolutionFile = this.targetSolutionFile.get();
|
||||||
try {
|
try {
|
||||||
Files.writeString(targetMazeFile, text);
|
Files.write(targetLabyrinthFile, text.getBytes(StandardCharsets.UTF_8));
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("Failed writing to file " + targetMazeFile.normalize(), e);
|
log.error("Failed writing to file " + targetLabyrinthFile.normalize(), e);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Files.writeString(targetSolutionFile, solution);
|
Files.write(targetSolutionFile, solution.getBytes(StandardCharsets.UTF_8));
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("Failed writing to file " + targetSolutionFile.normalize());
|
log.error("Failed writing to file " + targetSolutionFile.normalize());
|
||||||
}
|
}
|
||||||
return List.of(targetMazeFile, targetSolutionFile);
|
return List.of(targetLabyrinthFile, targetSolutionFile);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,10 +1,10 @@
|
||||||
package ch.fritteli.maze.generator.serialization.v1;
|
package ch.fritteli.labyrinth.generator.serialization;
|
||||||
|
|
||||||
import ch.fritteli.maze.generator.model.Direction;
|
import ch.fritteli.labyrinth.generator.model.Direction;
|
||||||
import ch.fritteli.maze.generator.model.Maze;
|
import ch.fritteli.labyrinth.generator.model.Labyrinth;
|
||||||
import ch.fritteli.maze.generator.model.Tile;
|
import ch.fritteli.labyrinth.generator.model.Tile;
|
||||||
|
import lombok.NonNull;
|
||||||
import lombok.experimental.UtilityClass;
|
import lombok.experimental.UtilityClass;
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
import java.lang.reflect.Constructor;
|
import java.lang.reflect.Constructor;
|
||||||
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
@ -45,7 +45,7 @@ import java.util.EnumSet;
|
||||||
* Extraneous space (poss. last nibble) is ignored.
|
* Extraneous space (poss. last nibble) is ignored.
|
||||||
*/
|
*/
|
||||||
@UtilityClass
|
@UtilityClass
|
||||||
public class SerializerDeserializerV1 {
|
public class SerializerDeserializer {
|
||||||
final byte MAGIC_BYTE_1 = 0x1a;
|
final byte MAGIC_BYTE_1 = 0x1a;
|
||||||
final byte MAGIC_BYTE_2 = (byte) 0xb1;
|
final byte MAGIC_BYTE_2 = (byte) 0xb1;
|
||||||
final byte VERSION_BYTE = 0x01;
|
final byte VERSION_BYTE = 0x01;
|
||||||
|
@ -57,57 +57,55 @@ public class SerializerDeserializerV1 {
|
||||||
private final byte SOLUTION_BIT = 0b0001_0000;
|
private final byte SOLUTION_BIT = 0b0001_0000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Serializes the {@code maze} into a byte array.
|
* Serializes the {@code labyrinth} into a byte array.
|
||||||
*
|
*
|
||||||
* @param maze The {@link Maze} to be serialized.
|
* @param labyrinth The labyrinth to be serialized.
|
||||||
* @return The resulting byte array.
|
* @return The resulting byte array.
|
||||||
*/
|
*/
|
||||||
@NotNull
|
@NonNull
|
||||||
public byte[] serialize(@NotNull final Maze maze) {
|
public byte[] serialize(@NonNull final Labyrinth labyrinth) {
|
||||||
final MazeOutputStreamV1 stream = new MazeOutputStreamV1();
|
final LabyrinthOutputStream stream = new LabyrinthOutputStream();
|
||||||
stream.writeHeader();
|
stream.writeHeader();
|
||||||
stream.writeMazeData(maze);
|
stream.writeLabyrinthData(labyrinth);
|
||||||
return stream.toByteArray();
|
return stream.toByteArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deserializes the byte array into an instance of {@link Maze}.
|
* Deserializes the byte array into an instance of {@link Labyrinth}.
|
||||||
*
|
*
|
||||||
* @param bytes The byte array to be deserialized.
|
* @param bytes The byte array to be deserialized.
|
||||||
* @return An instance of {@link Maze}.
|
* @return An instance of {@link Labyrinth}.
|
||||||
*/
|
*/
|
||||||
@NotNull
|
@NonNull
|
||||||
public Maze deserialize(@NotNull final byte[] bytes) {
|
public Labyrinth deserialize(@NonNull final byte[] bytes) {
|
||||||
final MazeInputStreamV1 stream = new MazeInputStreamV1(bytes);
|
final LabyrinthInputStream stream = new LabyrinthInputStream(bytes);
|
||||||
stream.checkHeader();
|
stream.checkHeader();
|
||||||
return stream.readMazeData();
|
return stream.readLabyrinthData();
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
Maze createMaze(@NotNull final Tile[][] field, final int width, final int height, final long randomSeed) {
|
Labyrinth createLabyrinth(@NonNull final Tile[][] field, final int width, final int height, final long randomSeed) {
|
||||||
try {
|
try {
|
||||||
final Constructor<Maze> constructor = Maze.class.getDeclaredConstructor(Tile[][].class, Integer.TYPE, Integer.TYPE, Long.TYPE);
|
final Constructor<Labyrinth> constructor = Labyrinth.class.getDeclaredConstructor(Tile[][].class, Integer.TYPE, Integer.TYPE, Long.TYPE);
|
||||||
constructor.setAccessible(true);
|
constructor.setAccessible(true);
|
||||||
return constructor.newInstance(field, width, height, randomSeed);
|
return constructor.newInstance(field, width, height, randomSeed);
|
||||||
} catch (@NotNull final NoSuchMethodException | IllegalAccessException | InstantiationException |
|
} catch (@NonNull final NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
|
||||||
InvocationTargetException e) {
|
throw new RuntimeException("Can not deserialize Labyrinth from labyrinth data.", e);
|
||||||
throw new RuntimeException("Can not deserialize Maze from maze data.", e);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
private Tile createTile(@NotNull final EnumSet<Direction> walls, boolean solution) {
|
private Tile createTile(@NonNull final EnumSet<Direction> walls, boolean solution) {
|
||||||
try {
|
try {
|
||||||
final Constructor<Tile> constructor = Tile.class.getDeclaredConstructor(EnumSet.class, Boolean.TYPE);
|
final Constructor<Tile> constructor = Tile.class.getDeclaredConstructor(EnumSet.class, Boolean.TYPE);
|
||||||
constructor.setAccessible(true);
|
constructor.setAccessible(true);
|
||||||
return constructor.newInstance(walls, solution);
|
return constructor.newInstance(walls, solution);
|
||||||
} catch (@NotNull final NoSuchMethodException | InstantiationException | IllegalAccessException |
|
} catch (@NonNull final NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
|
||||||
InvocationTargetException e) {
|
throw new RuntimeException("Can not deserialize Tile from labyrinth data.", e);
|
||||||
throw new RuntimeException("Can not deserialize Tile from maze data.", e);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
byte getBitmaskForTile(@NotNull final Tile tile) {
|
byte getBitmaskForTile(@NonNull final Tile tile) {
|
||||||
byte bitmask = 0;
|
byte bitmask = 0;
|
||||||
if (tile.hasWallAt(Direction.TOP)) {
|
if (tile.hasWallAt(Direction.TOP)) {
|
||||||
bitmask |= TOP_BIT;
|
bitmask |= TOP_BIT;
|
||||||
|
@ -127,7 +125,7 @@ public class SerializerDeserializerV1 {
|
||||||
return bitmask;
|
return bitmask;
|
||||||
}
|
}
|
||||||
|
|
||||||
@NotNull
|
@NonNull
|
||||||
Tile getTileForBitmask(final byte bitmask) {
|
Tile getTileForBitmask(final byte bitmask) {
|
||||||
final EnumSet<Direction> walls = EnumSet.noneOf(Direction.class);
|
final EnumSet<Direction> walls = EnumSet.noneOf(Direction.class);
|
||||||
if ((bitmask & TOP_BIT) == TOP_BIT) {
|
if ((bitmask & TOP_BIT) == TOP_BIT) {
|
|
@ -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();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,104 +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 java.util.Deque;
|
|
||||||
import java.util.LinkedList;
|
|
||||||
import java.util.Random;
|
|
||||||
|
|
||||||
public class RandomDepthFirst {
|
|
||||||
|
|
||||||
@NotNull
|
|
||||||
private final Maze maze;
|
|
||||||
@NotNull
|
|
||||||
private final Random random;
|
|
||||||
@NotNull
|
|
||||||
private final Deque<Position> positions = new LinkedList<>();
|
|
||||||
|
|
||||||
public RandomDepthFirst(@NotNull final Maze maze) {
|
|
||||||
this.maze = maze;
|
|
||||||
this.random = new Random(maze.getRandomSeed());
|
|
||||||
}
|
|
||||||
|
|
||||||
public void run() {
|
|
||||||
this.preDig();
|
|
||||||
this.dig();
|
|
||||||
this.postDig();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void preDig() {
|
|
||||||
final Position end = this.maze.getEnd();
|
|
||||||
final Tile endTile = this.maze.getEndTile();
|
|
||||||
|
|
||||||
if (end.y() == 0) {
|
|
||||||
endTile.enableDiggingToOrFrom(Direction.TOP);
|
|
||||||
endTile.digFrom(Direction.TOP);
|
|
||||||
} else if (end.x() == 0) {
|
|
||||||
endTile.enableDiggingToOrFrom(Direction.LEFT);
|
|
||||||
endTile.digFrom(Direction.LEFT);
|
|
||||||
} else if (end.y() == this.maze.getHeight() - 1) {
|
|
||||||
endTile.enableDiggingToOrFrom(Direction.BOTTOM);
|
|
||||||
endTile.digFrom(Direction.BOTTOM);
|
|
||||||
} else if (end.x() == this.maze.getWidth() - 1) {
|
|
||||||
endTile.enableDiggingToOrFrom(Direction.RIGHT);
|
|
||||||
endTile.digFrom(Direction.RIGHT);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 Tile startTile = this.maze.getStartTile();
|
|
||||||
|
|
||||||
if (start.y() == 0) {
|
|
||||||
startTile.enableDiggingToOrFrom(Direction.TOP);
|
|
||||||
startTile.digTo(Direction.TOP);
|
|
||||||
} else if (start.x() == 0) {
|
|
||||||
startTile.enableDiggingToOrFrom(Direction.LEFT);
|
|
||||||
startTile.digTo(Direction.LEFT);
|
|
||||||
} else if (start.y() == this.maze.getHeight() - 1) {
|
|
||||||
startTile.enableDiggingToOrFrom(Direction.BOTTOM);
|
|
||||||
startTile.digTo(Direction.BOTTOM);
|
|
||||||
} else if (start.x() == this.maze.getWidth() - 1) {
|
|
||||||
startTile.enableDiggingToOrFrom(Direction.RIGHT);
|
|
||||||
startTile.digTo(Direction.RIGHT);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,17 +0,0 @@
|
||||||
package ch.fritteli.maze.generator.model;
|
|
||||||
|
|
||||||
public enum Direction {
|
|
||||||
TOP,
|
|
||||||
RIGHT,
|
|
||||||
BOTTOM,
|
|
||||||
LEFT;
|
|
||||||
|
|
||||||
public Direction invert() {
|
|
||||||
return switch (this) {
|
|
||||||
case TOP -> BOTTOM;
|
|
||||||
case RIGHT -> LEFT;
|
|
||||||
case BOTTOM -> TOP;
|
|
||||||
case LEFT -> RIGHT;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,131 +0,0 @@
|
||||||
package ch.fritteli.maze.generator.model;
|
|
||||||
|
|
||||||
import io.vavr.control.Option;
|
|
||||||
import lombok.EqualsAndHashCode;
|
|
||||||
import lombok.Getter;
|
|
||||||
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;
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
@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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,16 +0,0 @@
|
||||||
package ch.fritteli.maze.generator.model;
|
|
||||||
|
|
||||||
import lombok.With;
|
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
@With
|
|
||||||
public record Position(int x, int y) {
|
|
||||||
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);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -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);
|
|
||||||
}
|
|
|
@ -1,167 +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 " + maze.getWidth() + "x" + maze.getHeight() + ", ID " + maze.getRandomSeed() + "</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>";
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,58 +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.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;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,43 +0,0 @@
|
||||||
package ch.fritteli.maze.generator.serialization;
|
|
||||||
|
|
||||||
import ch.fritteli.maze.generator.model.Maze;
|
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
import java.io.ByteArrayInputStream;
|
|
||||||
|
|
||||||
public abstract class AbstractMazeInputStream extends ByteArrayInputStream {
|
|
||||||
|
|
||||||
public AbstractMazeInputStream(@NotNull final byte[] buf) {
|
|
||||||
super(buf);
|
|
||||||
}
|
|
||||||
|
|
||||||
public abstract void checkHeader();
|
|
||||||
|
|
||||||
@NotNull
|
|
||||||
public abstract Maze readMazeData();
|
|
||||||
|
|
||||||
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 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;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,51 +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 org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
public class MazeInputStreamV1 extends AbstractMazeInputStream {
|
|
||||||
|
|
||||||
public MazeInputStreamV1(@NotNull final byte[] buf) {
|
|
||||||
super(buf);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void checkHeader() {
|
|
||||||
final byte magic1 = this.readByte();
|
|
||||||
if (magic1 != SerializerDeserializerV1.MAGIC_BYTE_1) {
|
|
||||||
throw new IllegalArgumentException("Invalid maze data.");
|
|
||||||
}
|
|
||||||
final byte magic2 = this.readByte();
|
|
||||||
if (magic2 != SerializerDeserializerV1.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() {
|
|
||||||
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] = SerializerDeserializerV1.getTileForBitmask(bitmask);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return SerializerDeserializerV1.createMaze(tiles, width, height, randomSeed);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,35 +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 org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
public class MazeOutputStreamV1 extends AbstractMazeOutputStream {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void writeHeader() {
|
|
||||||
this.writeByte(SerializerDeserializerV1.MAGIC_BYTE_1);
|
|
||||||
this.writeByte(SerializerDeserializerV1.MAGIC_BYTE_2);
|
|
||||||
this.writeByte(SerializerDeserializerV1.VERSION_BYTE);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void writeMazeData(@NotNull final Maze maze) {
|
|
||||||
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 = SerializerDeserializerV1.getBitmaskForTile(tile);
|
|
||||||
this.writeByte(bitmask);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,69 +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 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 != SerializerDeserializerV2.MAGIC_BYTE_1) {
|
|
||||||
throw new IllegalArgumentException("Invalid maze data.");
|
|
||||||
}
|
|
||||||
final byte magic2 = this.readByte();
|
|
||||||
if (magic2 != SerializerDeserializerV2.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] = SerializerDeserializerV2.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);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,53 +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 org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
public class MazeOutputStreamV2 extends AbstractMazeOutputStream {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void writeHeader() {
|
|
||||||
// 00 0x1a magic
|
|
||||||
// 01 0xb1 magic
|
|
||||||
// 02 0x02 version
|
|
||||||
this.writeByte(SerializerDeserializerV2.MAGIC_BYTE_1);
|
|
||||||
this.writeByte(SerializerDeserializerV2.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 = SerializerDeserializerV2.getBitmaskForTile(tile);
|
|
||||||
this.writeByte(bitmask);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,153 +0,0 @@
|
||||||
package ch.fritteli.maze.generator.serialization.v2;
|
|
||||||
|
|
||||||
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 lombok.experimental.UtilityClass;
|
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
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>
|
|
||||||
* ==> bits 0..2: always 0; bit 3: 1=solution, 0=not solution; bits 4..7: encode walls ==> first 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 {
|
|
||||||
|
|
||||||
final byte MAGIC_BYTE_1 = 0x1a;
|
|
||||||
final byte MAGIC_BYTE_2 = (byte) 0xb1;
|
|
||||||
final byte VERSION_BYTE = 0x02;
|
|
||||||
|
|
||||||
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 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,96 +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",
|
|
||||||
"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."
|
|
||||||
},
|
|
||||||
"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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,4 +1,4 @@
|
||||||
package ch.fritteli.maze.generator.model;
|
package ch.fritteli.labyrinth.generator.model;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
class DirectionTest {
|
class DirectionTest {
|
||||||
@Test
|
@Test
|
||||||
void shouldInvertTheDirection() {
|
void invert() {
|
||||||
assertThat(Direction.TOP.invert()).isEqualTo(Direction.BOTTOM);
|
assertThat(Direction.TOP.invert()).isEqualTo(Direction.BOTTOM);
|
||||||
assertThat(Direction.RIGHT.invert()).isEqualTo(Direction.LEFT);
|
assertThat(Direction.RIGHT.invert()).isEqualTo(Direction.LEFT);
|
||||||
assertThat(Direction.BOTTOM.invert()).isEqualTo(Direction.TOP);
|
assertThat(Direction.BOTTOM.invert()).isEqualTo(Direction.TOP);
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package ch.fritteli.maze.generator.model;
|
package ch.fritteli.labyrinth.generator.model;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
class PositionTest {
|
class PositionTest {
|
||||||
@Test
|
@Test
|
||||||
void shouldMoveToCorrectNeighborPosition() {
|
void move() {
|
||||||
// arrange
|
// arrange
|
||||||
final Position sut = new Position(0, 0);
|
final Position sut = new Position(0, 0);
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package ch.fritteli.maze.generator.model;
|
package ch.fritteli.labyrinth.generator.model;
|
||||||
|
|
||||||
import io.vavr.control.Option;
|
import io.vavr.control.Option;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
@ -9,20 +9,21 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
class TileTest {
|
class TileTest {
|
||||||
@Test
|
@Test
|
||||||
void shouldConstructATileWithDefaultValues() {
|
void testConstruct() {
|
||||||
// arrange / act
|
// arrange / act
|
||||||
final Tile sut = new Tile();
|
final Tile sut = new Tile();
|
||||||
|
|
||||||
//assert
|
//assert
|
||||||
assertThat(sut.hasWallAt(Direction.TOP)).isTrue();
|
assertThat(sut)
|
||||||
assertThat(sut.hasWallAt(Direction.RIGHT)).isTrue();
|
.returns(true, v -> v.hasWallAt(Direction.TOP))
|
||||||
assertThat(sut.hasWallAt(Direction.BOTTOM)).isTrue();
|
.returns(true, v -> v.hasWallAt(Direction.RIGHT))
|
||||||
assertThat(sut.hasWallAt(Direction.LEFT)).isTrue();
|
.returns(true, v -> v.hasWallAt(Direction.BOTTOM))
|
||||||
assertThat(sut.isSolution()).isFalse();
|
.returns(true, v -> v.hasWallAt(Direction.LEFT))
|
||||||
|
.returns(false, Tile::isSolution);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void tileCanBeDugIntoOnlyOnce() {
|
void testDigFrom() {
|
||||||
// arrange
|
// arrange
|
||||||
final Tile sut = new Tile();
|
final Tile sut = new Tile();
|
||||||
|
|
||||||
|
@ -42,27 +43,29 @@ class TileTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void canDigToDirectionOnlyOnce() {
|
void testDigTo() {
|
||||||
// arrange
|
// arrange
|
||||||
final Tile sut = new Tile();
|
final Tile sut = new Tile();
|
||||||
|
|
||||||
// act / assert
|
// act / assert
|
||||||
assertThat(sut.digTo(Direction.TOP)).isTrue();
|
assertThat(sut)
|
||||||
assertThat(sut.digTo(Direction.RIGHT)).isTrue();
|
.returns(true, v -> v.digTo(Direction.TOP))
|
||||||
assertThat(sut.digTo(Direction.BOTTOM)).isTrue();
|
.returns(true, v -> v.digTo(Direction.RIGHT))
|
||||||
assertThat(sut.digTo(Direction.LEFT)).isTrue();
|
.returns(true, v -> v.digTo(Direction.BOTTOM))
|
||||||
|
.returns(true, v -> v.digTo(Direction.LEFT))
|
||||||
// digging a second time does not succeed
|
// digging a second time does not succeed
|
||||||
assertThat(sut.digTo(Direction.LEFT)).isFalse();
|
.returns(false, v -> v.digTo(Direction.LEFT));
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(sut.hasWallAt(Direction.TOP)).isFalse();
|
assertThat(sut)
|
||||||
assertThat(sut.hasWallAt(Direction.RIGHT)).isFalse();
|
.returns(false, v -> v.hasWallAt(Direction.TOP))
|
||||||
assertThat(sut.hasWallAt(Direction.BOTTOM)).isFalse();
|
.returns(false, v -> v.hasWallAt(Direction.RIGHT))
|
||||||
assertThat(sut.hasWallAt(Direction.LEFT)).isFalse();
|
.returns(false, v -> v.hasWallAt(Direction.BOTTOM))
|
||||||
|
.returns(false, v -> v.hasWallAt(Direction.LEFT));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void canNotDigToOrFromDirectionWhenPrevented() {
|
void testPreventDiggingToOrFrom() {
|
||||||
// arrange
|
// arrange
|
||||||
final Tile sut = new Tile();
|
final Tile sut = new Tile();
|
||||||
|
|
||||||
|
@ -70,11 +73,10 @@ class TileTest {
|
||||||
sut.preventDiggingToOrFrom(Direction.LEFT);
|
sut.preventDiggingToOrFrom(Direction.LEFT);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(sut.digTo(Direction.LEFT)).isFalse();
|
assertThat(sut)
|
||||||
assertThat(sut.digFrom(Direction.LEFT)).isFalse();
|
.returns(false, v -> v.digTo(Direction.LEFT))
|
||||||
assertThat(sut.hasWallAt(Direction.LEFT)).isTrue();
|
.returns(false, v -> v.digFrom(Direction.LEFT))
|
||||||
// Digging in another direction is still permitted
|
.returns(true, v -> v.hasWallAt(Direction.LEFT));
|
||||||
assertThat(sut.digTo(Direction.RIGHT)).isTrue();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
|
@ -1,4 +1,4 @@
|
||||||
package ch.fritteli.maze.generator.model;
|
package ch.fritteli.labyrinth.generator.model;
|
||||||
|
|
||||||
import io.vavr.collection.Stream;
|
import io.vavr.collection.Stream;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
@ -63,14 +63,14 @@ class WallsTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testSeal() {
|
void testHarden() {
|
||||||
// arrange
|
// arrange
|
||||||
final Walls sut = new Walls();
|
final Walls sut = new Walls();
|
||||||
sut.set(Direction.TOP);
|
sut.set(Direction.TOP);
|
||||||
sut.set(Direction.RIGHT);
|
sut.set(Direction.RIGHT);
|
||||||
|
|
||||||
// act
|
// act
|
||||||
sut.seal(Direction.TOP);
|
sut.harden(Direction.TOP);
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(sut)
|
assertThat(sut)
|
||||||
|
@ -86,34 +86,34 @@ class WallsTest {
|
||||||
assertThat(result).isFalse();
|
assertThat(result).isFalse();
|
||||||
assertThat(sut.isSet(Direction.TOP)).isTrue();
|
assertThat(sut.isSet(Direction.TOP)).isTrue();
|
||||||
|
|
||||||
// act / assert: try to seal un-set wall
|
// act / assert: try to harden un-set wall
|
||||||
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> sut.seal(Direction.LEFT));
|
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> sut.harden(Direction.LEFT));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testUnseal() {
|
void testUnharden() {
|
||||||
// arrange
|
// arrange
|
||||||
final Walls sut = new Walls();
|
final Walls sut = new Walls();
|
||||||
sut.setAll();
|
sut.setAll();
|
||||||
sut.seal(Direction.TOP);
|
sut.harden(Direction.TOP);
|
||||||
|
|
||||||
// pre-assert: TOP can't be cleared while hardened
|
// pre-assert: TOP can't be cleared while hardened
|
||||||
assertThat(sut.clear(Direction.TOP)).isFalse();
|
assertThat(sut.clear(Direction.TOP)).isFalse();
|
||||||
|
|
||||||
// act
|
// act
|
||||||
sut.unseal(Direction.TOP);
|
sut.unharden(Direction.TOP);
|
||||||
|
|
||||||
// assert: TOP can be cleared
|
// assert: TOP can be cleared
|
||||||
assertThat(sut.clear(Direction.TOP)).isTrue();
|
assertThat(sut.clear(Direction.TOP)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetUnsealedSet() {
|
void testGetUnhardenedSet() {
|
||||||
// arrange
|
// arrange
|
||||||
final Walls sut = new Walls();
|
final Walls sut = new Walls();
|
||||||
|
|
||||||
// act
|
// act
|
||||||
Stream<Direction> result = sut.getUnsealedSet();
|
Stream<Direction> result = sut.getUnhardenedSet();
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(result).isEmpty();
|
assertThat(result).isEmpty();
|
||||||
|
@ -123,16 +123,16 @@ class WallsTest {
|
||||||
sut.set(Direction.LEFT);
|
sut.set(Direction.LEFT);
|
||||||
|
|
||||||
// act
|
// act
|
||||||
result = sut.getUnsealedSet();
|
result = sut.getUnhardenedSet();
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(result).containsExactly(Direction.TOP, Direction.LEFT);
|
assertThat(result).containsExactly(Direction.TOP, Direction.LEFT);
|
||||||
|
|
||||||
// arrange: seal a direction
|
// arrange: harden a direction
|
||||||
sut.seal(Direction.TOP);
|
sut.harden(Direction.TOP);
|
||||||
|
|
||||||
// act
|
// act
|
||||||
result = sut.getUnsealedSet();
|
result = sut.getUnhardenedSet();
|
||||||
|
|
||||||
// assert
|
// assert
|
||||||
assertThat(result).containsExactly(Direction.LEFT);
|
assertThat(result).containsExactly(Direction.LEFT);
|
|
@ -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 org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -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))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,36 +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).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).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).isEqualTo(expected);
|
|
||||||
}
|
|
||||||
}
|
|
Loading…
Reference in a new issue