46 lines
1.0 KiB
Dart
46 lines
1.0 KiB
Dart
class Maze {
|
|
final int width;
|
|
final int height;
|
|
late List<List<int>> grid;
|
|
|
|
Maze(this.width, this.height) {
|
|
grid = List.generate(height, (y) => List.generate(width, (x) => 1));
|
|
_generate();
|
|
}
|
|
|
|
void _generate() {
|
|
_carve(1, 1);
|
|
// Ensure start and end are open
|
|
grid[1][1] = 0;
|
|
grid[height - 2][width - 2] = 0;
|
|
}
|
|
|
|
void _carve(int x, int y) {
|
|
grid[y][x] = 0;
|
|
final dirs = [
|
|
[0, -2],
|
|
[0, 2],
|
|
[-2, 0],
|
|
[2, 0],
|
|
]..shuffle();
|
|
|
|
for (final d in dirs) {
|
|
final nx = x + d[0];
|
|
final ny = y + d[1];
|
|
if (ny > 0 && ny < height - 1 && nx > 0 && nx < width - 1 && grid[ny][nx] == 1) {
|
|
grid[y + d[1] ~/ 2][x + d[0] ~/ 2] = 0;
|
|
_carve(nx, ny);
|
|
}
|
|
}
|
|
}
|
|
|
|
bool isWall(int x, int y) {
|
|
if (x < 0 || x >= width || y < 0 || y >= height) return true;
|
|
return grid[y][x] == 1;
|
|
}
|
|
|
|
bool isGoal(double x, double y) {
|
|
return (x - (width - 2)).abs() < 0.5 && (y - (height - 2)).abs() < 0.5;
|
|
}
|
|
}
|