Esempio n. 1
0
        private static RoomConnector CreateRoomConnector(Room otherRoom, Direction direction)
        {
            var random    = new Random();
            var connector = new RoomConnector();

            connector.ConnectedTo   = otherRoom;
            connector.Direction     = direction;
            connector.ConnectorType = new[] { RoomConnectorType.DOOR, RoomConnectorType.WINDOW, RoomConnectorType.STAIRS }[random.Next(0, 2)];

            if (direction == Direction.NORTH && otherRoom.Connectors.ContainsKey(Direction.SOUTH))
            {
                connector.ConnectorType = otherRoom.Connectors[Direction.SOUTH].ConnectorType;
            }
            if (direction == Direction.SOUTH && otherRoom.Connectors.ContainsKey(Direction.NORTH))
            {
                connector.ConnectorType = otherRoom.Connectors[Direction.NORTH].ConnectorType;
            }
            if (direction == Direction.WEST && otherRoom.Connectors.ContainsKey(Direction.EAST))
            {
                connector.ConnectorType = otherRoom.Connectors[Direction.EAST].ConnectorType;
            }
            if (direction == Direction.EAST && otherRoom.Connectors.ContainsKey(Direction.WEST))
            {
                connector.ConnectorType = otherRoom.Connectors[Direction.WEST].ConnectorType;
            }

            return(connector);
        }
    // Use this for initialization
    void Start()
    {
        if (FailureScene == null)
        {
            Logs.Error("Failure scene is not set");
        }

        if (!Msf.Client.Connection.IsConnected)
        {
            // If we're not connected to master, jump back to maion screen
            SceneManager.LoadScene(FailureScene.SceneName);
            return;
        }

        // Get access to the zone we are supposed to be in.
        Msf.Client.Connection.SendMessage(WorldDemoOpCodes.GetCurrentZoneAccess, (status, response) =>
        {
            if (status != ResponseStatus.Success)
            {
                // If we've failed to request a teleport
                Logs.Warn("Teleport request failed. Reason: " + response.AsString() + "." +
                          "This might be intentional(when quitting a game)");
                SceneManager.LoadScene(FailureScene.SceneName);
                return;
            }

            var access = response.Deserialize(new RoomAccessPacket());

            // Make sure that we won't try to start a game server
            // on the game scene
            Msf.Client.Rooms.ForceClientMode = true;

            RoomConnector.Connect(access);
        });
    }
    public bool Equals(RoomConnector roomConnector)
    {
        bool room1 = this.room1.Equals(roomConnector.room1);
        bool room2 = this.room2.Equals(roomConnector.room2);

        return(room1 && room2);
    }
Esempio n. 4
0
 public virtual void OnRoomAccessReceived(RoomAccessPacket access)
 {
     // Connect via room connector
     if (RoomConnector.Instance != null)
     {
         RoomConnector.Connect(access);
     }
 }
    bool TryAligning(RoomConnector emptySpace, Room newRoom)
    {
        Vector3 originalPosition = new Vector3(
            newRoom.transform.position.x,
            newRoom.transform.position.y,
            newRoom.transform.position.z
            );

        Room prevRoom = emptySpace.transform.parent.gameObject.GetComponent <Room>();

        for (float x = 0f; x <= 20f; x += 0.5f)
        {
            for (float y = 0f; y <= 20f; y += 0.5f)
            {
                newRoom.transform.position = originalPosition + new Vector3(x, y, 0);

                if (AreDoorsAligned(newRoom, prevRoom))
                {
                    if (!IsOverlappingWithOtherRooms(newRoom))
                    {
                        return(true);
                    }
                }

                newRoom.transform.position = originalPosition + new Vector3(-x, y, 0);

                if (AreDoorsAligned(newRoom, prevRoom))
                {
                    if (!IsOverlappingWithOtherRooms(newRoom))
                    {
                        return(true);
                    }
                }

                newRoom.transform.position = originalPosition + new Vector3(x, -y, 0);

                if (AreDoorsAligned(newRoom, prevRoom))
                {
                    if (!IsOverlappingWithOtherRooms(newRoom))
                    {
                        return(true);
                    }
                }
                newRoom.transform.position = originalPosition + new Vector3(-x, -y, 0);

                if (AreDoorsAligned(newRoom, prevRoom))
                {
                    if (!IsOverlappingWithOtherRooms(newRoom))
                    {
                        return(true);
                    }
                }
            }
        }

        return(false);
    }
Esempio n. 6
0
 /// <summary>
 /// Closes the exit and sets the connection to the other exit.
 /// </summary>
 /// <param name="connectedTo">The exit to be set as a connection.</param>
 /// <param name="connStatus">Why the exit is being closed.</param>
 public void CloseExit(RoomConnector connectedTo, ExitStatus connStatus = ExitStatus.Connected)
 {
     isOpen   = false;
     connStat = connStatus;
     if (connectedTo != null)
     {
         this.connectedTo = connectedTo;
     }
 }
Esempio n. 7
0
 private static void RemoveOriginalChildrenIfNeeded(RoomConnector conn)
 {
     if (conn.removeOriginal)
     {
         foreach (Transform child in conn.transform)
         {
             Object.Destroy(child.gameObject);
         }
     }
 }
Esempio n. 8
0
    /// <summary>
    /// Rotate the new room so it faces and matches the current rooms exit.
    /// </summary>
    /// <param name="currExit">Current rooms exit.</param>
    /// <param name="newExit">New rooms exit.</param>
    public void MatchExits(RoomConnector newExit)
    {
        var newRoom = newExit.transform.parent;
        var forwardVectorToMatch = -this.transform.forward;
        var correctiveRotation   = CalculateAzimuth(forwardVectorToMatch) - CalculateAzimuth(newExit.transform.forward);

        newRoom.RotateAround(newExit.transform.position, Vector3.up, correctiveRotation);
        var correctiveTranslation = this.transform.position - newExit.transform.position;

        newRoom.transform.position += correctiveTranslation;
    }
Esempio n. 9
0
 /// <summary>
 /// Close exit due to a collision.
 /// </summary>
 /// <param name="exit">Exit to be closed.</param>
 public void CloseCollidingExit(RoomConnector exit)
 {
     foreach (var roomExit in exitsList)
     {
         if (roomExit.GetExit().Equals(exit))
         {
             roomExit.CloseExit(null, RoomExit.ExitStatus.ClosedDueToCollision);
         }
     }
     //exit.DestroyCollider(); //remove collider as it's no longer necessary
 }
Esempio n. 10
0
 /// <summary>
 /// Finds the specified RoomConnector in the exits list,
 /// and closes it by invoking the CloseExit function.
 /// </summary>
 /// <param name="connectingFrom">The Exit to close.</param>
 /// <param name="connectingTo">The Exit that the first exit is connecting to.</param>
 public void ConnectExits(RoomConnector connectingFrom, RoomConnector connectTo)
 {
     foreach (var roomExit in exitsList)
     {
         if (roomExit.GetExit().Equals(connectingFrom))
         {
             roomExit.CloseExit(connectTo, RoomExit.ExitStatus.Connected);
         }
     }
     connectingFrom.DestroyCollider(); //remove collider as it's no longer necessary
 }
Esempio n. 11
0
 /// <summary>
 /// Checks if the passed in exit is still open.
 /// </summary>
 /// <param name="exit">The exit to check whether is still open or not.</param>
 /// <returns>Returns TRUE if the exit is open. Otherwise, returns FALSE.</returns>
 public bool IsExitOpen(RoomConnector exit)
 {
     foreach (var roomExit in exitsList)
     {
         if (roomExit.GetExit().Equals(exit) && roomExit.IsExitOpen())
         {
             return(true);
         }
     }
     return(false);
 }
Esempio n. 12
0
 public void AddRoomConnector(RoomConnector roomConnector)
 {
     roomConnectors.Add(roomConnector);
     if (roomConnector is Door)
     {
         doors.Add((Door)roomConnector);
     }
     else if (roomConnector is Stair)
     {
         stairs.Add((Stair)roomConnector);
     }
 }
Esempio n. 13
0
    private static void PlaceNewRoom(RoomConnector randomConnectorStart, DungeonRoom roomInstance, RoomConnector randomConnectorEnd)
    {
        Vector3 newRoomOffset = (roomInstance.transform.position - randomConnectorEnd.transform.position);

        roomInstance.transform.position = randomConnectorStart.transform.position + newRoomOffset;

        float angle = Vector3.SignedAngle(randomConnectorStart.transform.forward, randomConnectorEnd.transform.forward, Vector3.up);

        angle = -angle + 180f;
        roomInstance.transform.RotateAround(randomConnectorStart.transform.position, Vector3.up, angle);

        randomConnectorStart.other = randomConnectorEnd;
        randomConnectorEnd.other   = randomConnectorStart;
    }
Esempio n. 14
0
        public override void Update()
        {
            var survivor = (Survivor)Brain.Actor;

            if (Brain.Actor.IsTransitioning)
            {
                return;
            }

            //See if it's time to move to a new location
            if (DateTime.Now >= NextMoveTime)
            {
                RoomConnector connector = Room.Connectors.Values.ToArray()[random.Next(0, Room.Connectors.Count - 1)];
                if (Brain.Memory.ContainsKey(BrainMemoryType.PREVIOUS_DIRECTION))
                {
                    Brain.Memory[BrainMemoryType.PREVIOUS_DIRECTION]          = connector.Direction;
                    Brain.Memory[BrainMemoryType.PREVIOUS_ROOM_TERROR_RADIUS] = survivor.Heartbeat.TerrorRadius;
                }
                else
                {
                    Brain.Memory.Add(BrainMemoryType.PREVIOUS_DIRECTION, connector.Direction);
                    Brain.Memory.Add(BrainMemoryType.PREVIOUS_ROOM_TERROR_RADIUS, survivor.Heartbeat.TerrorRadius);
                }

                if (connector.ConnectorType == RoomConnectorType.DOOR)
                {
                    ((Survivor)Brain.Actor).Move(connector.Direction, ActionSpeed.FAST);
                }
                else if (connector.ConnectorType == RoomConnectorType.WINDOW)
                {
                    ((Survivor)Brain.Actor).Vault(connector.Direction, ActionSpeed.FAST);
                }
                NextMoveTime = GetNextMoveTime();

                return;
            }

            //Check if there's a generator we could be doing
            var generator = (Generator)Room.Objects.FirstOrDefault(x => x.Type == Interest.GENERATOR);

            if (generator != null && generator.Progress < 100)
            {
                survivor.Repair();
                Brain.SwitchTo(BrainStateType.REPAIR_GENERATOR);
            }

            base.Update();
        }
Esempio n. 15
0
    /// <summary>
    /// Go through all of the generated rooms that match the parameter and add a small room to them so they don't lead to nowhere.
    /// </summary>
    /// <param name="typeToCloseOff">The room type to look for.</param>
    private void CloseOffPaths()
    {
        if (closeOffParent == null)
        {
            closeOffParent = new GameObject("Path closing rooms - ");
            closeOffParent.transform.parent = emptyGameObject.transform;
        }

        foreach (var roomType in RoomTypesToCloseOff)
        {
            foreach (GameObject go in GameObject.FindGameObjectsWithTag("RoomInstance"))
            {
                currRoom = go.GetComponent <Room>();
                if (currRoom.GetRoomType().Equals(roomType))
                {
                    foreach (var exit in currRoom.GetRoomExits())
                    {
                        if (exit.GetConnectionStatus().Equals(RoomExit.ExitStatus.Connected)) //if exit is connected, skip it
                        {
                            continue;
                        }

                        Room newRoom = (Room)Instantiate(rnd.GetRandom(RoomsToUseToClosePath));
                        newRoom.SetupCollider();
                        currExit = exit.GetExit();
                        var newRoomExits = newRoom.GetExits();
                        var exitToMatch  = rnd.GetRandom(newRoomExits);
                        newRoom.tag = "RoomInstance";
                        newRoom.gameObject.layer = LayerMask.NameToLayer("RoomInstances");

                        currExit.MatchExits(exitToMatch);

                        if (collision.DetectCollision(newRoom))
                        {
                            MarkRoomForDestruction(newRoom);
                            currRoom.CloseCollidingExit(currExit); // cannot add room here so close the exit
                            continue;
                        }
                        currRoom.ConnectExits(currExit, exitToMatch);
                        newRoom.ConnectExits(exitToMatch, currExit);

                        newRoom.transform.SetParent(closeOffParent.transform);
                    }
                }
            }
        }
        closeOffParent.name += closeOffParent.GetComponentsInChildren <Room>().Count();
    }
Esempio n. 16
0
    private void AddCloseOffsToDungeon(List <RoomConnector> openConnections)
    {
        for (int i = openConnections.Count - 1; i >= 0; i--)
        {
            RoomConnector connectorStart = openConnections[i];
            openConnections.RemoveAt(i);

            GameObject  instance         = Instantiate(closeoffPrefab);
            DungeonRoom closeoffInstance = instance.GetComponent <DungeonRoom>();
            generatedRooms.Add(closeoffInstance);
            RoomConnector connectorEnd = closeoffInstance.roomConnectors[0];
            PlaceNewRoom(connectorStart, closeoffInstance, connectorEnd);

            AddRoomBounds(closeoffInstance, true);
        }
    }
Esempio n. 17
0
    /// <summary>
    /// Scans through all of the instantiated rooms and find the RoomExit that contains the specified roomConnector.
    /// </summary>
    /// <param name="exitToFind"></param>
    /// <returns></returns>
    public RoomExit FindRoomExit(RoomConnector exitToFind)
    {
        RoomExit exit = null;

        foreach (var roomObj in GameObject.FindGameObjectsWithTag("RoomInstance"))
        {
            foreach (var roomExit in roomObj.GetComponent <Room>().GetRoomExits())
            {
                if (roomExit.GetExit().Equals(exitToFind))
                {
                    exit = roomExit;
                    break;
                }
            }
        }
        return(exit);
    }
Esempio n. 18
0
        public void ConnectToParent(RoomConnector connectionToParentRoom, RoomPrototypeConnection parentRoomConnection)
        {
            if (parentRoomConnection != null)
            {
                if (parentRoomConnection.State != PrototypeConnectionState.FREE)
                {
                    throw new Exception("parent connection already filled");
                }

                ParentRoomConnection = parentRoomConnection;
                ParentRoomConnection.SetChild(this, connectionToParentRoom);
            }

            ChildRoomConnections = RoomResource.GetConnections()
                                   .Where(x => x != connectionToParentRoom)
                                   .Select(x => new RoomPrototypeConnection(this, x))
                                   .ToList();
        }
Esempio n. 19
0
 bool IsDoorPairAligned(RoomConnector door1, RoomConnector door2)
 {
     if (door1.transform.position.x == door2.transform.position.x)
     {
         if (Mathf.Abs(door1.transform.position.y - door2.transform.position.y) == 2f)
         {
             return(true);
         }
     }
     if (door1.transform.position.y == door2.transform.position.y)
     {
         if (Mathf.Abs(door1.transform.position.x - door2.transform.position.x) == 2f)
         {
             return(true);
         }
     }
     return(false);
 }
Esempio n. 20
0
        private static void CreateClosedReplacement(RoomConnector conn)
        {
            RemoveOriginalChildrenIfNeeded(conn);

            if (conn.closedPrefab != null)
            {
                if (conn.closedPrefab.scene.name == null)
                {
                    Object.Instantiate(conn.closedPrefab, conn.transform);
                }
                else
                {
                    conn.closedPrefab.SetActive(true);
                }
            }

            if (conn.openPrefab != null)
            {
                if (conn.openPrefab.scene.name != null)
                {
                    Object.Destroy(conn.openPrefab);
                }
            }
        }
Esempio n. 21
0
        private static Room BuildDungeonInUnitySpaceRecur(RoomPrototype actualElement, Transform parent)
        {
            var instantiatedRoom = Object.Instantiate(actualElement.RoomResource, actualElement.GlobalPosition, actualElement.Rotation, parent);

            actualElement.ActualGraphElement.Room = instantiatedRoom;
            instantiatedRoom.DungeonStructureNode = actualElement.ActualGraphElement;

            foreach (var prototypeConnection in actualElement.ChildRoomConnections)
            {
                var parentConn = instantiatedRoom.GetConnections().Single(c =>
                                                                          c.name == prototypeConnection.ParentConnection.name &&
                                                                          c.transform.localPosition == prototypeConnection.ParentConnection.transform.localPosition);

                if (prototypeConnection.State == PrototypeConnectionState.CONNECTED)
                {
                    var nextRoom  = BuildDungeonInUnitySpaceRecur(prototypeConnection.ChildRoomPrototype, parent);
                    var childConn = nextRoom.GetConnections().Single(c => c.name == prototypeConnection.ChildConnection.name &&
                                                                     c.transform.localPosition == prototypeConnection.ChildConnection.transform.localPosition);
                    RoomConnector.Connect(parentConn, childConn);

                    CreateOpenReplacement(parentConn);
                    CreateOpenReplacement(childConn);
                }
                else if (prototypeConnection.State == PrototypeConnectionState.CLOSED)
                {
                    parentConn.Close();
                    CreateClosedReplacement(parentConn);
                }
                else
                {
                    throw new Exception("No other state should be possible");
                }
            }

            return(instantiatedRoom);
        }
Esempio n. 22
0
    /// <summary>
    /// Try and add the specified 'ExitRoom' to one of the open exits.
    /// </summary>
    private void SetupExitRoom()
    {
        if (ExitRoom == null) //no exit room prefab was provided
        {
            hasExitRoomBeenSuccessfullyAdded = true;
            if (_DEBUG_MODE)
            {
                FileLogger.Log(">No Exit Room Specified. Terminating SetupExitRoom function.<");
            }
            return;
        }

        if (_DEBUG_MODE)
        {
            FileLogger.Log(">Starting SetupExitRoom...");
        }

        if ((supportFunctions.GetAllRoomsWithActiveExits().Count < 3 || supportFunctions.GetRoomsWithPossibleExits().Count < 5) && expandPathBy > 1)
        {
            //Make sure there are enough exits before spawning an exit room as it would certainly be a dead end
            if (_DEBUG_MODE)
            {
                FileLogger.Log("Postponing SetupExitRoom due to possibility of creating a dead-end.");
            }
            hasExitRoomBeenSuccessfullyAdded = false;
            return;
        }

        //Select a room to connect the exit to.
        int excludeRooms = 0; //counter to keep track of how many rooms we've backtracked so we do not check the same ones again

        currRoom = supportFunctions.BacktrackToLastRoomWithActiveExits(GetComponent <ConnectionRules>().GetPossibleConnectionBetweenRoomsByRoomType(ExitRoom.GetRoomType()),
                                                                       ref excludeRooms);; //find a room to add the exit to(needs to meet one of the connection rules criteria)

        if (currRoom.Equals(InitialRoom))
        {
            if (_DEBUG_MODE)
            {
                FileLogger.Log(">Attempted to connect exit room to initial room. Returning and awaiting more available rooms.<");
            }

            hasExitRoomBeenSuccessfullyAdded = true;
            return;
        }

        if (currRoom == null)
        {
            //force stop the execution of the function if a suitable room wasn't found
            if (_DEBUG_MODE)
            {
                FileLogger.Log(">!< Could not add exit room to any of the rooms. Terminating SetupExitRoom function! >!<");
            }

            hasExitRoomBeenSuccessfullyAdded = false;
            return;
        }

        Room exitRoom = (Room)Instantiate(ExitRoom);

        exitRoom.SetupCollider();
        exitRoom.tag = "RoomInstance";
        exitRoom.gameObject.layer = LayerMask.NameToLayer("RoomInstances");
        var           exitRoomExits     = exitRoom.GetExits(); //get exits for the new room
        RoomConnector exitToMatch       = null;
        bool          collisionDetected = false;

        do
        {
            if (currRoom == null || currRoom.Equals(InitialRoom))
            {
                //force stop the execution of the function if a suitable room wasn't found
                if (_DEBUG_MODE)
                {
                    FileLogger.Log(">!< Could not add exit room to any of the rooms. Terminating SetupExitRoom function! >!<");
                }

                MarkRoomForDestruction(exitRoom);
                hasExitRoomBeenSuccessfullyAdded = false;
                return;
            }

            currExit = rnd.GetRandom(currRoom.GetActiveExits());

            if (collisionDetected)
            {
                currRoom = supportFunctions.BacktrackToLastRoomWithActiveExits(GetComponent <ConnectionRules>().GetPossibleConnectionBetweenRoomsByRoomType(exitRoom.GetRoomType()),
                                                                               ref excludeRooms); //find a room to add the exit to
                excludeRooms++;                                                                   //if this room cannot be connected to the one that was just found, then ignore it next time as we don't close the exit / prevent inf loop
                continue;
            }

            exitToMatch = rnd.GetRandom(exitRoomExits);                   //select default exit or choose one at random
            currExit.MatchExits(exitToMatch);                             //rotate the new room so it connects correctly
        }while (collisionDetected = collision.DetectCollision(exitRoom)); //deal with the collision

        currRoom.ConnectExits(currExit, exitToMatch);
        exitRoom.ConnectExits(exitToMatch, currExit);

        exitRoom.transform.parent        = emptyGameObject.transform;
        exitRoom.name                    = "ExitRoom";
        hasExitRoomBeenSuccessfullyAdded = true;
        if (markEndRoom)
        {
            exitRoom.GetComponent <Renderer>().material.color = Color.red;
        }

        if (_DEBUG_MODE)
        {
            FileLogger.Log("<SetupExitRoom was successful.");
        }
    }
Esempio n. 23
0
    /// <summary>
    /// Instantiates a room and adds it to the level. Based on the passed in argument it will either
    /// add a room to the main path of the level(true) or to a random room(false).
    /// Returns 1 if function was successful. 0 if collision occured. -1 if there are no more active exits.
    /// </summary>
    /// <param name="onMainPath">True: generate the main path. False: expand the level</param>
    /// <returns>-1 if dead end has been found; 0 if a collision has occured; 1 if room was generated successfully.</returns>
    private int GenerateRoom(bool onMainPath = true)
    {
        if (supportFunctions.GetTotalNumberOfActiveExits() == 0)
        {
            return(-1);
        }

        //try and add the exit room if the previous attempt was unsuccessful
        if (!onMainPath && supportFunctions.GetAllRoomsWithActiveExits().Count > 3 && !hasExitRoomBeenSuccessfullyAdded && CURRENT_UNSUCCESSFUL_ROOM_REPLACMENT_ATTEMPTS == 0)
        {//dont generate during main path generation, but also make sure the function is not trying to add another room at this time
            if (_DEBUG_MODE)
            {
                FileLogger.Log(">!< Trying SetupExitRoom during Expansion >!<");
            }
            SetupExitRoom();
        }

        //if expanding level( NOT onMainPath) and not re-trying due to collision ( curr unsuccessful attempts is 0)
        if (!onMainPath && CURRENT_UNSUCCESSFUL_ROOM_REPLACMENT_ATTEMPTS == 0)
        {
            currRoom = rnd.GetRandom(supportFunctions.GetAllRoomsWithActiveExits().ToArray()); //pick a random open exit from the list to use
        }
        //if we're not trying to replace a room due to collision, get a new random exit
        if (CURRENT_UNSUCCESSFUL_ROOM_REPLACMENT_ATTEMPTS == 0)
        {
            currExit = rnd.GetRandom(currRoom.GetActiveExits()); //get the exit's room component
        }
        var possibleRoomConnections = GetComponent <ConnectionRules>().GetPossibleConnectionBetweenRoomsByRoomType(currExit.transform.parent.GetComponent <Room>().GetRoomType());
        var pickRandomRoomType      = rnd.GetRandom(possibleRoomConnections);             //pick randomly a room type which can be connected to the current one's exit
        var newRoomPrefab           = rnd.GetRandomByRoomType(Rooms, pickRandomRoomType); //find item with specific room type

        if (onMainPath)
        {
            //avoid dead end if the new room will have only 1 exit which will be closed upon conneciton with the current room, or if there are few exits left
            if (newRoomPrefab.GetExits().Length <= 1 || supportFunctions.GetTotalNumberOfActiveExits() <= 3)
            {
                supportFunctions.AvoidDeadEnd(ref newRoomPrefab, possibleRoomConnections);
            }
        }
        else
        {
            if (supportFunctions.GetTotalNumberOfActiveExits() <= 5)
            {
                supportFunctions.AvoidDeadEnd(ref newRoomPrefab, possibleRoomConnections);
            }
        }

        var newRoom = (Room)Instantiate(newRoomPrefab);

        if (onMainPath)
        {
            newRoom.name += "SP" + uniqueID;
        }
        else
        {
            newRoom.name += "EXP" + uniqueID;
        }


        newRoom.SetupCollider();
        newRoom.tag = "RoomInstance";
        newRoom.gameObject.layer = LayerMask.NameToLayer("RoomInstances");

        var newRoomExits = newRoom.GetExits();          //get exits for the new room
        var exitToMatch  = rnd.GetRandom(newRoomExits); //select default exit or choose one at random

        currExit.MatchExits(exitToMatch);               //rotate the new room so it connects correctly

        if (collision.DetectCollision(newRoom))         //deal with the collision
        {
            MarkRoomForDestruction(newRoom);
            CURRENT_UNSUCCESSFUL_ROOM_REPLACMENT_ATTEMPTS++;

            if (CURRENT_UNSUCCESSFUL_ROOM_REPLACMENT_ATTEMPTS >= MAX_UNSUCCESSFUL_ROOM_REPLACEMENT_ATTEMPTS) //close off exit and backtrack
            {
                //close off exit only if there are other exits still open - otherwise it would lead to a complete dead end
                CURRENT_UNSUCCESSFUL_ROOM_REPLACMENT_ATTEMPTS = 0;
                currRoom.CloseCollidingExit(currExit);

                //find a new room with active exits.
                if (onMainPath)
                {
                    currRoom = supportFunctions.BacktrackToLastRoomWithActiveExits();
                }

                //else case will be executed next time the function is called as currRoom will be randomly picked if not onMainPath
            }

            return(0);
        }
        //reset attempts and connect the rooms
        CURRENT_UNSUCCESSFUL_ROOM_REPLACMENT_ATTEMPTS = 0;
        currRoom.ConnectExits(currExit, exitToMatch);
        newRoom.ConnectExits(exitToMatch, currExit);

        if (allowLoops)
        {
            newRoom.ConnectActiveExitsInProximity();
        }

        if (onMainPath)
        {
            newRoom.transform.SetParent(spParent.transform);
            if (highlightMainPath)
            {
                // "highlight" the main path
                currRoom.GetComponent <Renderer>().material.color = Color.green;
                newRoom.GetComponent <Renderer>().material.color  = Color.green;
            }

            //if the new room doesn't have an exit, don't move into it
            if (newRoom.GetActiveExits().Length >= 1)
            {
                currRoom = newRoom;
            }

            if (currRoom.GetActiveExits().Length == 0)
            {
                currRoom = supportFunctions.BacktrackToLastRoomWithActiveExits();
                CURRENT_UNSUCCESSFUL_ROOM_REPLACMENT_ATTEMPTS = 0;
            }
        }
        else
        {
            newRoom.transform.SetParent(expParent.transform);
        }
        uniqueID++;

        return(1);
    }
Esempio n. 24
0
 /// <summary>
 /// Invoke the Physics.OverlapSphere function and check for hit colliders in the RoomConnections layer.
 /// </summary>
 /// <param name="exit">The RoomConnector to be used as a starting point for the OverlapSphere.</param>
 /// <returns>An array of the colliders hit by the cast.</returns>
 public Collider[] DetectCollision(RoomConnector exit, float radius)
 {
     return(Physics.OverlapSphere(exit.gameObject.GetComponent <SphereCollider>().transform.position,
                                  radius,
                                  LayerMask.GetMask("RoomConnections")));
 }
Esempio n. 25
0
 public void SetChild(RoomPrototype childRoomPrototype, RoomConnector childConnection)
 {
     ChildConnection    = childConnection;
     ChildRoomPrototype = childRoomPrototype;
     State = PrototypeConnectionState.CONNECTED;
 }
Esempio n. 26
0
        public override void Update()
        {
            if (Brain.Actor.IsTransitioning)
            {
                return;
            }

            //Look at surroundings
            var survivors = Room.Actors
                            .FindAll(x => x is Survivor)
                            .Select(x => (Survivor)x)
                            .Where(x => !x.InLocker && x.HealthState < HealthState.DYING)
                            .ToArray();

            var damageableGen = (Generator)Room.Objects.Find(x => x.Type == Interest.GENERATOR && ((Generator)x).Touched);
            var locker        = (Locker)Room.Objects
                                .Find(x => x.Type == Interest.LOCKER);

            //There's a survivor, enter a chase with them
            if (survivors.Length > 0)
            {
                var canSeeRandom = random.Next(0, 100) > 60;

                if (canSeeRandom)
                {
                    var target = survivors[random.Next(0, survivors.Length - 1)];
                    Game.Current.AddHistory($"The ^red:KILLER$ begins ^yellow:CHASING$ ^green:{target.Name}$");
                    Brain.Memory.Add(BrainMemoryType.TARGET, target);
                    Brain.SwitchTo(BrainStateType.CHASE);
                }
            }
            else if (damageableGen != null) //No survivor, but there's a generator that's been touched. damage it
            {
                damageableGen.Damage();
            }
            else if (locker != null && !locker.Checked) //if there's a locker, check it
            {
                if (locker.Check() != null)
                {
                    ((Killer)Brain.Actor).Pickup(locker.SurvivorInside);
                    locker.SurvivorInside = null;
                    Brain.SwitchTo(BrainStateType.FIND_HOOK);
                }
            }
            else
            {
                //See if it's time to wander to a new place
                if (DateTime.Now >= NextMoveTime)
                {
                    RoomConnector connector = null;

                    var scratchedConnector = Room.GetScratchedObjects().FirstOrDefault(x => x.Type == Interest.CONNECTOR);
                    if (scratchedConnector != null)
                    {
                        connector = (RoomConnector)scratchedConnector;
                    }
                    else
                    {
                        connector = Room.Connectors.Values
                                    .Where(x =>
                                           !Brain.Memory.ContainsKey(BrainMemoryType.PREVIOUS_ROOM) ||
                                           x.ConnectedTo != Brain.Memory[BrainMemoryType.PREVIOUS_ROOM]
                                           )
                                    .ToArray()[random.Next(0, Room.Connectors.Count - 1)];
                    }

                    if (Brain.Memory.ContainsKey(BrainMemoryType.PREVIOUS_ROOM))
                    {
                        Brain.Memory[BrainMemoryType.PREVIOUS_ROOM] = Room;
                    }
                    else
                    {
                        Brain.Memory.Add(BrainMemoryType.PREVIOUS_ROOM, Room);
                    }
                    Brain.Actor.Move(connector.Direction, ActionSpeed.SLOW);
                    NextMoveTime = GetNextMoveTime();

                    return;
                }
            }

            base.Update();
        }
Esempio n. 27
0
 public void ClearChild()
 {
     ChildConnection    = null;
     ChildRoomPrototype = null;
     State = PrototypeConnectionState.FREE;
 }
    private IEnumerator generationProcess(int targetRoomCount, Room firstRoom)
    {
        int currentRoomCount = 1; //Count our starting room.
        List <RoomConnector> connectorSet = firstRoom.getRoomConnectors();

        while (currentRoomCount < targetRoomCount)
        {
            List <RoomConnector> nextConnectorSet = new List <RoomConnector>();
            foreach (RoomConnector initialConnector in connectorSet)
            {
                Room initialRoom = initialConnector.getRoom();
                if (initialConnector.getConnectedRoom() != null)   //If, for some reason, a connector is already occupied (set manually?), skip this iteration.
                {
                    continue;
                }
                List <Room> possibleRooms = getConnectableRooms(initialConnector.getWidth()).ToList();
                //Until we reach our targetRoomCount, we must try and pick at least one room with more than one connector per iteration.
                List <Room> filteredRooms = new List <Room>();
                if (currentRoomCount < targetRoomCount)
                {
                    filteredRooms = getBranchingRooms(possibleRooms).ToList();
                }
                else
                {
                    filteredRooms = possibleRooms;
                }
                while (filteredRooms.Count > 0 && initialConnector.getConnectedRoom() == null)
                {
                    //Instantiate the rooms, filter the ones from the list that cause bad collisions, etc.
                    //If there are no possible working results, close off this connector.
                    Room newRoomPrefab = filteredRooms[Random.Range(0, filteredRooms.Count)];
                    //Randomly filter through connectors until one works:
                    List <RoomConnector> filteredConnectors = newRoomPrefab.getRoomConnectors().ToList();
                    while (filteredConnectors.Count > 0 && initialConnector.getConnectedRoom() == null)
                    {
                        RoomConnector chosenConnector = filteredConnectors[Random.Range(0, filteredConnectors.Count)];
                        //Initialize and test the chosen room:
                        Room      newRoom          = Instantiate(newRoomPrefab, Vector3.zero, Quaternion.identity) as Room;
                        Transform newRoomConnector = newRoom.getRoomConnectors()[newRoomPrefab.getRoomConnectors().IndexOf(chosenConnector)].transform;
                        alignRoom(firstRoom.transform, initialConnector.transform, newRoom.transform, newRoomConnector);
                        //Start collision check:
                        newRoom.activateBoundsDetection();
                        yield return(new WaitForFixedUpdate()); //Wait for any collisions to register.

                        if (!newRoom.getBoundsValidity())
                        {
                            filteredConnectors.Remove(chosenConnector); //This connector does not work, remove it from the list.
                            Destroy(newRoom.gameObject);
                        }
                        else
                        {
                            //Set these rooms as connected to each other.
                            newRoom.getRoomConnectors()[newRoomPrefab.getRoomConnectors().IndexOf(chosenConnector)].setConnectedRoom(initialRoom);
                            initialConnector.setConnectedRoom(newRoom); //This step will break the loop.
                            newRoom.completeSetup();
                            currentRoomCount++;
                            nextConnectorSet.AddRange(newRoom.getUnusedRoomConnectors());
                        }
                    }
                    if (initialConnector.getConnectedRoom() == null)   //If this connector doesn't have a room yet, the newRoomPrefab cannot work in this instance.
                    {
                        filteredRooms.Remove(newRoomPrefab);
                    }
                }
                if (initialConnector.getConnectedRoom() == null)   //If this connector still does not have a room, we close it off.
                {
                    initialConnector.closeOffConnector();
                    //TODO: Set this connector's connected room to a dummy value to indicate that it is filled with a door and should not be processed again.
                }
            }
            connectorSet = nextConnectorSet;
            if (connectorSet.Count <= 0)
            {
                break;
            }

            //Just before the next iteration, check if we are going to stop - and if so, we need to close off all of the nextConnectors:
            if (currentRoomCount >= targetRoomCount)
            {
                foreach (RoomConnector connector in connectorSet)
                {
                    connector.closeOffConnector();
                }
            }
        }
    }
Esempio n. 29
0
    bool PlaceRoom(Room room, int spaceIdx)
    {
        RoomConnector space = availableSpaces[spaceIdx];

        room.transform.SetParent(transform);

        bool          isAligned = false;
        RoomConnector entrance  = null;

        List <RoomConnector> shuffledExits = new List <RoomConnector>();

        System.Random rand;

        if (seed == 0)
        {
            rand = new System.Random();
        }

        rand = new System.Random(seed);

        for (int i = 0; i < room.exits.Count; i++)
        {
            shuffledExits.Add(room.exits[rand.Next(0, room.exits.Count)]);
        }

        foreach (RoomConnector conn in shuffledExits)
        {
            room.transform.position = new Vector3(
                space.transform.position.x,
                space.transform.position.y,
                0f
                );

            bool roomPlaced = TryAligning(space, room);

            if (roomPlaced == true)
            {
                isAligned = true;
                room.transform.position = new Vector3(
                    Mathf.Round(room.transform.position.x),
                    Mathf.Round(room.transform.position.y),
                    Mathf.Round(room.transform.position.z)
                    );
                entrance = conn;
                generatedRooms.Add(room);
                break;
            }
        }

        if (isAligned)
        {
            foreach (RoomConnector conn in room.exits)
            {
                availableSpaces.Add(conn);
            }
            availableSpaces.Remove(space);
            availableSpaces.Remove(entrance);
            return(true);
        }
        else
        {
            Destroy(room.gameObject);
            return(false);
        }
    }
Esempio n. 30
0
    private void AddRoomToDungeon(List <RoomConnector> openConnections, DungeonRoom newRoom, RoomConnector randomConnectorEnd, int openIndex)
    {
        generatedRooms.Add(newRoom);
        openConnections.RemoveAt(openIndex);

        foreach (var connector in newRoom.roomConnectors)
        {
            if (connector != randomConnectorEnd)
            {
                openConnections.Add(connector);
            }
        }

        AddRoomBounds(newRoom);
    }