Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Created April 16, 2020 18:16
Show Gist options
  • Save shiracamus/653e8cad7c87a7741aebc99e0abede8f to your computer and use it in GitHub Desktop.
Save shiracamus/653e8cad7c87a7741aebc99e0abede8f to your computer and use it in GitHub Desktop.
enum Cell { WALL, ROAD };
class Map {
public final int width;
public final int height;
private final Cell[][] cells;
public Map(int width, int height) {
if (width < 5 || height < 5 || width % 2 == 0 || height % 2 == 0) {
new IllegalArgumentException("縦・横共に5以上の奇数で作成してください。");
}
this.width = width;
this.height = height;
cells = new Cell[height][width];
}
public void fillWall() {
for (var row: cells) {
for (int x = 0; x < row.length; x++) {
row[x] = Cell.WALL;
}
}
}
public void dig(int x, int y) {
cells[y][x] = Cell.ROAD;
}
public boolean isInside(int x, int y) {
return 1 <= x && x < width - 1 && 1 <= y && y < height - 1;
}
public boolean isDigable(int x, int y) {
return isInside(x, y) && cells[y][x] == Cell.WALL;
}
public boolean isDigableForward(int x, int y) {
return isDigable(x, y - 2) || isDigable(x, y + 2) ||
isDigable(x - 2, y) || isDigable(x + 2, y);
}
public boolean isDigable() {
for (int y = 1; y < height; y += 2) {
for (int x = 1; x < width; x += 2) {
if (cells[y][x] == Cell.WALL) {
return true;
}
}
}
return false;
}
public void show() {
for (var row: cells) {
for (var cell: row) {
System.out.print(cell == Cell.WALL ? "##" : " ");
}
System.out.println();
}
}
}
class Digger {
private Map map;
private static final int DIR_X[] = { -1, 1, 0, 0 };
private static final int DIR_Y[] = { 0, 0, -1, 1 };
public Digger(Map map) {
this.map = map;
}
private int random(int max) {
return 1 + 2 * (int) ((Math.random() * (max - 1)) / 2);
}
public void dig() {
map.fillWall();
while (map.isDigable()) {
int x, y;
do {
x = random(map.width);
y = random(map.height);
} while (!map.isDigable(x, y));
dig(x, y);
}
}
private void dig(int x, int y) {
map.dig(x, y);
while (map.isDigableForward(x, y)) {
int dx, dy;
do {
int direction = (int) Math.floor(Math.random() * DIR_X.length);
dx = DIR_X[direction];
dy = DIR_Y[direction];
} while (!map.isDigable(x + dx * 2, y + dy * 2));
map.dig(x + dx, y + dy);
dig(x + dx * 2, y + dy * 2);
}
}
}
public class Maze {
private final Map map;
public Maze(int width, int height) {
map = new Map(width, height);
}
public void make() {
new Digger(map).dig();
}
public void show() {
map.show();
}
public static void main(String[] args) {
Maze maze = new Maze(21, 21);
maze.make();
maze.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment