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