public void GeneratePathToEnd(Map map, int maxIterations, Room startRoom) { Room room = startRoom; int counter = 2; int iteration = 0; while (iteration < maxIterations) { IEnumerable<Room> neighbours = map.GetNeighbours(room); if (neighbours.Any(n => n.X == map.EndX && n.Y == map.EndY)) { room.Id = 99; map.ReachedEnd = true; break; } foreach (Room neighbour in neighbours.OrderBy(x => _rand.Next())) { if (neighbour.Id == 0 && map.CountNeighbours(neighbour) == 1) { neighbour.Id = counter; room = neighbour; counter++; break; } } iteration++; } map.RoomsInPath = counter - 2; }
private void AddSideRooms(Room room, Map map) { if (room.X - 1 >= 0 && map[room.X - 1, room.Y].Id == 0){ map[room.X - 1, room.Y].Id = 88; } if (room.X + 1 < map.Width && map[room.X + 1, room.Y].Id == 0) { map[room.X + 1, room.Y].Id = 88; } if (room.Y - 1 >= 0 && map[room.X, room.Y - 1].Id == 0){ map[room.X, room.Y - 1].Id = 88; } if (room.Y + 1 < map.Height && map[room.X, room.Y + 1].Id == 0){ map[room.X, room.Y + 1].Id = 88; } }
public static int CountNeighbours(this Map map, Room room) { int neighbourCount = 0; // left if (room.X - 1 >= 0 && map[room.X - 1, room.Y].Id != 0) neighbourCount++; // right if (room.X + 1 < map.Width && map[room.X + 1, room.Y].Id != 0) neighbourCount++; // top if (room.Y - 1 >= 0 && map[room.X, room.Y - 1].Id != 0) neighbourCount++; // bottom if (room.Y + 1 < map.Height && map[room.X, room.Y + 1].Id != 0) neighbourCount++; return neighbourCount; }
public static IEnumerable<Room> GetNeighbours(this Map map, Room room) { List<Room> neighbours = new List<Room>(); // left if (room.X - 1 >= 0) neighbours.Add(map[room.X - 1, room.Y]); // right if (room.X + 1 < map.Width) neighbours.Add(map[room.X + 1, room.Y]); // top if (room.Y - 1 >= 0) neighbours.Add(map[room.X, room.Y - 1]); // bottom if (room.Y + 1 < map.Height) neighbours.Add(map[room.X, room.Y + 1]); return neighbours; }
private void RemoveUnconnectedRooms(Map map) { for (int y = 0; y < map.Height; y++) { for (int x = 0; x < map.Width; x++) { if (map.CountNeighbours(map[x, y]) == 0) map[x, y] = new Room { X = x, Y = y }; else if (RoomHasOnlySideRoomConnections(map, map[x, y])) map[x, y] = new Room { X = x, Y = y }; } } }
private bool RoomHasOnlySideRoomConnections(Map map, Room room) { var neighbours = map.GetNeighbours(room); if (room.Id == 88 && neighbours.All(n => n.Id == 88 || n.Id == 0)) return true; return false; }
/** * Return the smallest distance between the collision boxes */ public double getDistance(Room other) { double smallest = 0; Rectangle[] ocb = other.getCollisionBoxes(); Rectangle[] cb = getCollisionBoxes(); for (int i = 0; i < ocb.Length; i++) { for (int j = 0; j < cb.Length; j++) { double distance = Helpers.Distance(ocb[i], cb[j]); if (distance == 0) { return 0; } smallest = (i == 0 && j == 0) ? distance : Math.Min(distance, smallest); } } return smallest; }