Compare commits

...

34 commits

Author SHA1 Message Date
b18e7fba9e
Reword some stuff.
All checks were successful
continuous-integration/drone/push Build is passing
2024-05-18 02:18:06 +02:00
49725fe7df
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2024-05-18 01:24:06 +02:00
4db011fd92
[maven-release-plugin] prepare release v0.2.1
Some checks failed
continuous-integration/drone/push Build is failing
2024-05-18 01:24:03 +02:00
7eb8d09ae8
Update parent.
All checks were successful
continuous-integration/drone/push Build is passing
2024-05-18 01:21:22 +02:00
1e190150ef
Tokenized login. 2024-05-18 01:21:09 +02:00
724f0f1a53
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2024-05-18 00:38:03 +02:00
65084659c2
[maven-release-plugin] prepare release v0.2.0
Some checks failed
continuous-integration/drone/push Build is failing
2024-05-18 00:38:00 +02:00
79f5620aaa
[maven-release-plugin] rollback the release of v0.2.0
All checks were successful
continuous-integration/drone/push Build is passing
2024-05-18 00:36:13 +02:00
684ecdbe53
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2024-05-18 00:23:00 +02:00
2ab7f9dc5f
[maven-release-plugin] prepare release v0.2.0
Some checks failed
continuous-integration/drone/push Build is failing
2024-05-18 00:22:57 +02:00
e3bc8d8452 Merge pull request 'Chore: Java 21.' (#9) from feature/java21 into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #9
2024-05-18 00:20:54 +02:00
4dd91b0277
Chore: Java 21.
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2024-05-17 23:44:11 +02:00
aa27d5f138
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-16 02:36:43 +02:00
5fb88ff292
[maven-release-plugin] prepare release v0.1.0
Some checks failed
continuous-integration/drone/push Build is failing
2023-05-16 02:36:40 +02:00
ca67ca638b
Configure server credentials.
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2023-05-16 02:26:45 +02:00
fcb87e13a5
Rename all "labyrinth" to "maze" and configure the Sonatype maven repo. 2023-05-16 02:15:02 +02:00
cb1c016cc7 [maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-17 00:21:34 +02:00
db722741a2 [maven-release-plugin] prepare release v0.0.8
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-17 00:21:29 +02:00
2e07fa2981 Merge pull request 'feature/make-start-and-end-configurable' (#7) from feature/make-start-and-end-configurable into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: java/labyrinth-generator#7
2023-04-17 00:19:04 +02:00
31b7fd6b2a Fix wall detection/generation of start- and end-tiles.
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2023-04-17 00:17:19 +02:00
6302aaa5e8 Feat: Make start and end of a labyrinth configurable.
All checks were successful
continuous-integration/drone/push Build is passing
Also, small refactoring.
2023-04-16 23:38:01 +02:00
14e4e497ac [maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-16 00:36:43 +02:00
3222131a9c [maven-release-plugin] prepare release v0.0.7
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-16 00:36:37 +02:00
2362365708 Merge pull request 'JSON: Transmit the ID as a string. See commit for the reason.' (#6) from feature/id-as-string into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: java/labyrinth-generator#6
2023-04-16 00:34:26 +02:00
822a1b1528 JSON: Transmit the ID as a string. See commit for the reason.
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2023-04-16 00:27:00 +02:00
2dea68f386 [maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-14 01:31:40 +02:00
18a9543c43 [maven-release-plugin] prepare release v0.0.6
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-14 01:31:34 +02:00
f75e068c18 Merge pull request 'Implement a JSON and a JSON-file renderer.' (#5) from feature/json-renderer into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: java/labyrinth-generator#5
2023-04-14 01:24:27 +02:00
715d89a57a Implement a JSON and a JSON-file renderer.
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2023-04-14 01:14:23 +02:00
81b5d7adac [maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-08 23:49:47 +02:00
1f4284e89f [maven-release-plugin] prepare release v0.0.5
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-08 23:49:41 +02:00
cc8fe0d536 Merge pull request 'Add interactiveness to HTML outputs.' (#4) from feature/interactive-html into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: java/labyrinth-generator#4
2023-04-08 23:48:20 +02:00
dd498e15cd Add interactiveness to HTML outputs.
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2023-04-08 23:46:27 +02:00
57c7359693 [maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-08 22:21:06 +02:00
52 changed files with 1718 additions and 902 deletions

View file

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

View file

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

View file

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

8
maze-generator.iml Normal file
View 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
View file

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

View file

@ -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();
}
}

View file

@ -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()!");
}
}
}

View file

@ -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);
}
}
}

View file

@ -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)!");
}
}
}

View file

@ -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);
}

View file

@ -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>";
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View 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();
}
}

View file

@ -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);
}
}
}

View file

@ -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;
};
}
}

View 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);
}
}
}

View 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);
};
}
}

View file

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

View file

@ -1,9 +1,9 @@
package ch.fritteli.labyrinth.generator.model; package ch.fritteli.maze.generator.model;
import io.vavr.collection.Stream; import io.vavr.collection.Stream;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.ToString; import lombok.ToString;
import org.jetbrains.annotations.NotNull;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.HashSet; import java.util.HashSet;
@ -15,9 +15,9 @@ import java.util.TreeSet;
@ToString @ToString
public class Walls { public class Walls {
private final SortedSet<Direction> directions = new TreeSet<>(); private final SortedSet<Direction> directions = new TreeSet<>();
private final Set<Direction> 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); this.directions.add(direction);
} }
@ -25,30 +25,30 @@ public class Walls {
this.directions.addAll(EnumSet.allOf(Direction.class)); this.directions.addAll(EnumSet.allOf(Direction.class));
} }
public boolean clear(@NonNull final Direction direction) { public boolean clear(@NotNull final Direction direction) {
if (this.hardened.contains(direction)) { if (this.sealed.contains(direction)) {
return false; return false;
} }
return this.directions.remove(direction); return this.directions.remove(direction);
} }
public boolean isSet(@NonNull final Direction direction) { public boolean isSet(@NotNull final Direction direction) {
return this.directions.contains(direction); return this.directions.contains(direction);
} }
public Stream<Direction> getUnhardenedSet() { public Stream<Direction> getUnsealedSet() {
return Stream.ofAll(this.directions) 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)) { 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) { public void unseal(@NotNull final Direction direction) {
this.hardened.remove(direction); this.sealed.remove(direction);
} }
} }

View file

@ -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);
}

View file

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

View file

@ -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>";
}
}

View file

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

View file

@ -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;
}
}

View file

@ -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);
}
}

View file

@ -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;
}
}

View file

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

View file

@ -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 java.io.ByteArrayOutputStream;
import lombok.NonNull;
public class PDFRenderer implements Renderer<ByteArrayOutputStream> { public class PDFRenderer implements Renderer<ByteArrayOutputStream> {
static final float MARGIN = 10; static final float MARGIN = 10;
@ -12,15 +13,15 @@ public class PDFRenderer implements Renderer<ByteArrayOutputStream> {
private PDFRenderer() { private PDFRenderer() {
} }
@NonNull @NotNull
public static PDFRenderer newInstance() { public static PDFRenderer newInstance() {
return new PDFRenderer(); return new PDFRenderer();
} }
@NonNull @NotNull
@Override @Override
public ByteArrayOutputStream render(@NonNull final Labyrinth labyrinth) { public ByteArrayOutputStream render(@NotNull final Maze maze) {
final Generator generator = new Generator(labyrinth); final Generator generator = new Generator(maze);
return generator.generate(); return generator.generate();
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -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;
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}
}
}

View file

@ -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.maze.generator.model.Direction;
import ch.fritteli.labyrinth.generator.model.Labyrinth; import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.labyrinth.generator.model.Tile; import ch.fritteli.maze.generator.model.Tile;
import lombok.NonNull;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
@ -45,7 +45,7 @@ import java.util.EnumSet;
* Extraneous space (poss. last nibble) is ignored. * Extraneous space (poss. last nibble) is ignored.
*/ */
@UtilityClass @UtilityClass
public class SerializerDeserializer { public class SerializerDeserializerV1 {
final byte MAGIC_BYTE_1 = 0x1a; final byte MAGIC_BYTE_1 = 0x1a;
final byte MAGIC_BYTE_2 = (byte) 0xb1; final byte MAGIC_BYTE_2 = (byte) 0xb1;
final byte VERSION_BYTE = 0x01; final byte VERSION_BYTE = 0x01;
@ -57,55 +57,57 @@ public class SerializerDeserializer {
private final byte SOLUTION_BIT = 0b0001_0000; 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. * @return The resulting byte array.
*/ */
@NonNull @NotNull
public byte[] serialize(@NonNull final Labyrinth labyrinth) { public byte[] serialize(@NotNull final Maze maze) {
final LabyrinthOutputStream stream = new LabyrinthOutputStream(); final MazeOutputStreamV1 stream = new MazeOutputStreamV1();
stream.writeHeader(); stream.writeHeader();
stream.writeLabyrinthData(labyrinth); stream.writeMazeData(maze);
return stream.toByteArray(); 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. * @param bytes The byte array to be deserialized.
* @return An instance of {@link Labyrinth}. * @return An instance of {@link Maze}.
*/ */
@NonNull @NotNull
public Labyrinth deserialize(@NonNull final byte[] bytes) { public Maze deserialize(@NotNull final byte[] bytes) {
final LabyrinthInputStream stream = new LabyrinthInputStream(bytes); final MazeInputStreamV1 stream = new MazeInputStreamV1(bytes);
stream.checkHeader(); stream.checkHeader();
return stream.readLabyrinthData(); return stream.readMazeData();
} }
@NonNull @NotNull
Labyrinth createLabyrinth(@NonNull final Tile[][] field, final int width, final int height, final long randomSeed) { Maze createMaze(@NotNull final Tile[][] field, final int width, final int height, final long randomSeed) {
try { 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); constructor.setAccessible(true);
return constructor.newInstance(field, width, height, randomSeed); return constructor.newInstance(field, width, height, randomSeed);
} catch (@NonNull final NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { } catch (@NotNull final NoSuchMethodException | IllegalAccessException | InstantiationException |
throw new RuntimeException("Can not deserialize Labyrinth from labyrinth data.", e); InvocationTargetException e) {
throw new RuntimeException("Can not deserialize Maze from maze data.", e);
} }
} }
@NonNull @NotNull
private Tile createTile(@NonNull final EnumSet<Direction> walls, boolean solution) { private Tile createTile(@NotNull final EnumSet<Direction> walls, boolean solution) {
try { try {
final Constructor<Tile> constructor = Tile.class.getDeclaredConstructor(EnumSet.class, Boolean.TYPE); final Constructor<Tile> constructor = Tile.class.getDeclaredConstructor(EnumSet.class, Boolean.TYPE);
constructor.setAccessible(true); constructor.setAccessible(true);
return constructor.newInstance(walls, solution); return constructor.newInstance(walls, solution);
} catch (@NonNull final NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { } catch (@NotNull final NoSuchMethodException | InstantiationException | IllegalAccessException |
throw new RuntimeException("Can not deserialize Tile from labyrinth data.", e); 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; byte bitmask = 0;
if (tile.hasWallAt(Direction.TOP)) { if (tile.hasWallAt(Direction.TOP)) {
bitmask |= TOP_BIT; bitmask |= TOP_BIT;
@ -125,7 +127,7 @@ public class SerializerDeserializer {
return bitmask; return bitmask;
} }
@NonNull @NotNull
Tile getTileForBitmask(final byte bitmask) { Tile getTileForBitmask(final byte bitmask) {
final EnumSet<Direction> walls = EnumSet.noneOf(Direction.class); final EnumSet<Direction> walls = EnumSet.noneOf(Direction.class);
if ((bitmask & TOP_BIT) == TOP_BIT) { if ((bitmask & TOP_BIT) == TOP_BIT) {

View file

@ -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);
}
}

View file

@ -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);
}
}
}
}

View file

@ -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>
* ==&gt; bits 0..2: always 0; bit 3: 1=solution, 0=not solution; bits 4..7: encode walls ==&gt; first bytes are:
* <pre>
* byte hex meaning
* 00 0x1a magic
* 01 0xb1 magic
* 02 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);
}
}

View 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
}
}
}
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

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

View 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))
);
}
}

View file

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

View file

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

View file

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

View file

@ -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 org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;

View file

@ -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);
}
}