Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Level : MonoBehaviour
- {
- public int height;
- public int width;
- Room[,] maze;
- private void Start()
- {
- CreateLevel();
- }
- private void CreateLevel()
- {
- maze = new Room[height, width];
- for (int i = 0; i < height; i++)
- {
- for (int j = 0; j < width; j++)
- {
- if ((i % 2 != 0 && j % 2 != 0) && //если ячейка нечетная по x и y,
- (i < height - 1 && j < width - 1)) //и при этом находится в пределах стен лабиринта
- {
- Room room = new Room();
- room.x = i;
- room.y = j;
- room.visited = false;
- room.wall = false;
- maze[i, j] = room;
- }
- else
- {
- Room wall = new Room();
- wall.x = i;
- wall.y = j;
- wall.visited = false;
- wall.wall = true;
- maze[i, j] = wall;
- }
- }
- }
- Room startRoom = new Room();
- startRoom.x = 1;
- startRoom.y = 1;
- startRoom.visited = true;
- Room currentRoom = startRoom;
- Room neighbourRoom;
- List<Room> neighboursNoVisited = new List<Room>();
- do
- {
- neighboursNoVisited = NeighboursNoVisited(currentRoom.x, currentRoom.y);
- neighbourRoom = neighboursNoVisited[Random.Range(0, neighboursNoVisited.Count)];
- RemoveWall(currentRoom, neighbourRoom);
- neighbourRoom.visited = true;
- currentRoom = neighbourRoom;
- } while (neighboursNoVisited.Count > 0);
- string map = "";
- for(int i = 0; i < height; i++)
- {
- for(int j = 0; j < width; j++)
- {
- if (maze[i, j].wall)
- {
- map += "*";
- }
- else
- {
- map += "_";
- }
- if(j + 1 == width)
- {
- map += "\n";
- }
- }
- }
- Debug.Log(map);
- }
- struct Room
- {
- public int x;
- public int y;
- public bool visited;
- public bool wall;
- }
- private List<Room> NeighboursNoVisited(int x, int y)
- {
- List<Room> rooms = new List<Room>();
- if( x - 2 > 0 && !maze[x - 2, y].visited)
- {
- rooms.Add(maze[x - 2, y]);
- }
- if (x + 2 < height && !maze[x + 2, y].visited)
- {
- rooms.Add(maze[x + 2, y]);
- }
- if (y - 2 > 0 && !maze[x, y - 2].visited)
- {
- rooms.Add(maze[x, y - 2]);
- }
- if (y + 2 < width && !maze[x, y + 2].visited)
- {
- rooms.Add(maze[x, y + 2]);
- }
- return rooms;
- }
- private void RemoveWall(Room currentRoom, Room neighbourRoom)
- {
- if(currentRoom.x < neighbourRoom.x)
- {
- maze[currentRoom.x + 1, currentRoom.y].wall = false;
- }
- else if(currentRoom.x > neighbourRoom.x)
- {
- maze[currentRoom.x - 1, currentRoom.y].wall = false;
- }
- else if (currentRoom.y < neighbourRoom.y)
- {
- maze[currentRoom.x, currentRoom.y + 1].wall = false;
- }
- else if (currentRoom.y > neighbourRoom.y)
- {
- maze[currentRoom.x, currentRoom.y + 1].wall = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement