На Java реализуй профессионально проект соблюдая принципы SOLID и качество кода в профессиональном проекте 1)Реализуй 2 мощных алгоритма генерации лабиринтов. Состоящих только из
⬜️: Проход (путь по которому можно передвигаться, размер пути не больше одной клеточки)
⬛️: Стена (не проходимый путь, размер стены не больше одной клеточки)
🟫: Болото (-1 к привлекательности пути, встречается на местах прохода вкраплениями)
🟨: монетка (+1 к привлекательности пути, встречается на местах прохода вкраплениями)
Мы вводим в консоль ширину и высоту лабиринта и затем выбираем алгоритм построения и в консоль выводится наш сгенерированный лабиринт
2)Затем мы в этом лабиринте указываем начальную и конечную точку нашего пути по координатам. Если это невозможно просим переопределить точки.
Реализация как минимум 2-х алгоритмов для поиска пути из заданной начальной точки А в конечную точку Б.
Мы выбираем один из предложенных алгоритмов, и программа строит самый оптимальный путь. 🪙 – так обозначить каждую клетку нашего оптимального маршрута между заданными нами координатами.
Затем программа выводит изменённый лабиринт, но уже с построенным путём
Assistant
Конечно! Давайте разработаем профессиональный Java-проект для генерации лабиринтов и поиска пути в них, соблюдая принципы SOLID и обеспечивая высокое качество кода. Проект будет разделен на несколько модулей:
Модель Лабиринта и Клеток
Алгоритмы Генерации Лабиринта
Алгоритмы Поиска Пути
Сервис для Управления Лабиринтом
Консольный Интерфейс Пользователя
Каждый модуль будет реализован в соответствии с принципами SOLID для обеспечения расширяемости и поддерживаемости кода.
1. Модель Лабиринта и Клеток
1.1. Перечисление CellType
Определим типы клеток лабиринта:
java
public enum CellType {
PATH("⬜️"),
WALL("⬛️"),
SWAMP("🟫"),
COIN("🟨"),
PATH_MARKED("🪙");
private final String symbol;
CellType(String symbol) {
this.symbol = symbol;
}
public String getSymbol() {
return symbol;
}
}
1.2. Класс Cell
Класс представляет клетку лабиринта с координатами и типом.
java
public class Cell {
private final int x;
private final int y;
private CellType type;
public Cell(int x, int y, CellType type) {
this.x = x;
this.y = y;
this.type = type;
}
// Геттеры и сеттеры
public int getX() {
return x;
}
public int getY() {
return y;
}
public CellType getType() {
return type;
}
public void setType(CellType type) {
this.type = type;
}
@Override
public String toString() {
return type.getSymbol();
}
}
1.3. Класс Maze
Класс представляет лабиринт как двумерный массив клеток.
java
public class Maze {
private final int width;
private final int height;
private final Cell[][] grid;
public Maze(int width, int height) {
this.width = width;
this.height = height;
grid = new Cell[height][width];
initializeMaze();
}
private void initializeMaze() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
grid[y][x] = new Cell(x, y, CellType.WALL);
}
}
}
public void setCell(int x, int y, CellType type) {
grid[y][x].setType(type);
}
public Cell getCell(int x, int y) {
return grid[y][x];
}
public boolean isInBounds(int x, int y) {
return x >= 0 && x < width && y >= 0 && y < height;
}
public void printMaze() {
for (Cell[] row : grid) {
for (Cell cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
2. Алгоритмы Генерации Лабиринта
Создадим интерфейс MazeGenerator и две его реализации: RecursiveBacktrackerGenerator и RandomizedPrimGenerator.
2.1. Интерфейс MazeGenerator
java
public interface MazeGenerator {
Maze generate(int width, int height);
}
2.2. Генератор RecursiveBacktrackerGenerator
Реализует алгоритм рекурсивного обхода для генерации лабиринта.
java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Stack;
public class RecursiveBacktrackerGenerator implements MazeGenerator {
private final Random random = new Random();
@Override
public Maze generate(int width, int height) {
Maze maze = new Maze(width, height);
Stack<Cell> stack = new Stack<>();
int startX = random.nextInt(width);
int startY = random.nextInt(height);
Cell start = maze.getCell(startX, startY);
start.setType(CellType.PATH);
stack.push(start);
while (!stack.isEmpty()) {
Cell current = stack.peek();
List<Cell> neighbors = getUnvisitedNeighbors(maze, current);
if (!neighbors.isEmpty()) {
Cell chosen = neighbors.get(random.nextInt(neighbors.size()));
removeWall(maze, current, chosen);
chosen.setType(CellType.PATH);
stack.push(chosen);
} else {
stack.pop();
}
}
addTerrainFeatures(maze);
return maze;
}
private List<Cell> getUnvisitedNeighbors(Maze maze, Cell cell) {
List<Cell> neighbors = new ArrayList<>();
int x = cell.getX();
int y = cell.getY();
// Преобразуем координаты для двух клеток в каждом направлении
int[][] deltas = { {0, -2}, {2, 0}, {0, 2}, {-2, 0} };
for (int[] delta : deltas) {
int nx = x + delta[0];
int ny = y + delta[1];
if (maze.isInBounds(nx, ny) && maze.getCell(nx, ny).getType() == CellType.WALL) {
neighbors.add(maze.getCell(nx, ny));
}
}
Collections.shuffle(neighbors, random);
return neighbors;
}
private void removeWall(Maze maze, Cell current, Cell chosen) {
int x = (current.getX() + chosen.getX()) / 2;
int y = (current.getY() + chosen.getY()) / 2;
maze.setCell(x, y, CellType.PATH);
}
private void addTerrainFeatures(Maze maze) {
for (int y = 0; y < maze.getHeight(); y++) {
for (int x = 0; x < maze.getWidth(); x++) {
Cell cell = maze.getCell(x, y);
if (cell.getType() == CellType.PATH) {
int rand = random.nextInt(100);
if (rand < 10) { // 10% вероятность болот
cell.setType(CellType.SWAMP);
} else if (rand < 20) { // Дополнительные 10% вероятность монет
cell.setType(CellType.COIN);
}
}
}
}
}
}
2.3. Генератор RandomizedPrimGenerator
Реализует алгоритм Прима для генерации лабиринта.
java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class RandomizedPrimGenerator implements MazeGenerator {
private final Random random = new Random();
@Override
public Maze generate(int width, int height) {
Maze maze = new Maze(width, height);
List<Cell> frontier = new ArrayList<>();
int startX = random.nextInt(width);
int startY = random.nextInt(height);
Cell start = maze.getCell(startX, startY);
start.setType(CellType.PATH);
addFrontier(maze, start, frontier);
while (!frontier.isEmpty()) {
Cell current = frontier.remove(random.nextInt(frontier.size()));
List<Cell> neighbors = getPathNeighbors(maze, current);
if (!neighbors.isEmpty()) {
Cell neighbor = neighbors.get(random.nextInt(neighbors.size()));
int x = (current.getX() + neighbor.getX()) / 2;
int y = (current.getY() + neighbor.getY()) / 2;
maze.setCell(x, y, CellType.PATH);
current.setType(CellType.PATH);
addFrontier(maze, current, frontier);
}
}
addTerrainFeatures(maze);
return maze;
}
private void addFrontier(Maze maze, Cell cell, List<Cell> frontier) {
int x = cell.getX();
int y = cell.getY();
int[][] deltas = { {0, -2}, {2, 0}, {0, 2}, {-2, 0} };
for (int[] delta : deltas) {
int nx = x + delta[0];
int ny = y + delta[1];
if (maze.isInBounds(nx, ny) && maze.getCell(nx, ny).getType() == CellType.WALL) {
Cell frontierCell = maze.getCell(nx, ny);
if (!frontier.contains(frontierCell)) {
frontier.add(frontierCell);
}
}
}
}
private List<Cell> getPathNeighbors(Maze maze, Cell cell) {
List<Cell> neighbors = new ArrayList<>();
int x = cell.getX();
int y = cell.getY();
int[][] deltas = { {0, -2}, {2, 0}, {0, 2}, {-2, 0} };
for (int[] delta : deltas) {
int nx = x + delta[0];
int ny = y + delta[1];
if (maze.isInBounds(nx, ny) && maze.getCell(nx, ny).getType() == CellType.PATH) {
neighbors.add(maze.getCell(nx, ny));
}
}
return neighbors;
}
private void addTerrainFeatures(Maze maze) {
for (int y = 0; y < maze.getHeight(); y++) {
for (int x = 0; x < maze.getWidth(); x++) {
Cell cell = maze.getCell(x, y);
if (cell.getType() == CellType.PATH) {
int rand = random.nextInt(100);
if (rand < 10) { // 10% вероятность болот
cell.setType(CellType.SWAMP);
} else if (rand < 20) { // Дополнительные 10% вероятность монет
cell.setType(CellType.COIN);
}
}
}
}
}
}
3. Алгоритмы Поиска Пути
Создадим интерфейс PathFinder и две его реализации: AStarPathFinder и DijkstraPathFinder.
Этот проект демонстрирует применение принципов SOLID и обеспечение высокого качества кода через разделение ответственности, использование интерфейсов для расширяемости и модульности, а также четкую структуру пакетов. Вы можете расширять функционал, добавляя новые алгоритмы генерации или поиска пути, улучшая существующие алгоритмы или интегрируя более сложные типы клеток и их взаимодействие.