Beispiel #1
0
    public static RoomTemplate ParseCompressedRoomTemplate(CompressedRoomTemplate compressedRoomTemplate)
    {
        RoomTemplate roomTemplate = new RoomTemplate();

        XmlDocument roomTemplateXML = new XmlDocument();
        roomTemplateXML.LoadXml(compressedRoomTemplate.xml);

        roomTemplate.m_templateName = compressedRoomTemplate.templateName;
        roomTemplate.m_floor = TileGridTemplate.ParseXML(roomTemplateXML.SelectSingleNode(".//Floor"));
        roomTemplate.m_walls = TileGridTemplate.ParseXML(roomTemplateXML.SelectSingleNode(".//Walls"));
        roomTemplate.m_backgroundObjects = TileGridTemplate.ParseXML(roomTemplateXML.SelectSingleNode(".//BackgroundObjects"));
        roomTemplate.m_navMeshTemplate =
            AsyncRPGSharedLib.Navigation.NavMesh.FromCompressedNavMeshData(
                compressedRoomTemplate.compressedNavCells,
                compressedRoomTemplate.compressedVisibility);
        roomTemplate.m_forgroundObjects = TileGridTemplate.ParseXML(roomTemplateXML.SelectSingleNode(".//ForegroundObjects"));

        return roomTemplate;
    }
Beispiel #2
0
        /// <summary>
        /// Place a room template aligned with an existing door.
        /// Returns Connection(Source = existing room or corridor to new room, Target = new room))
        /// </summary>
        public Connection PlaceRoomTemplateAlignedWithExistingDoor(RoomTemplate roomTemplateToPlace, RoomTemplate corridorTemplate, DoorInfo existingDoor, int newRoomDoorIndex, int distanceApart)
        {
            var newRoomIndex = NextRoomIndex();

            Point existingDoorLoc = existingDoor.MapCoords;

            Tuple <TemplatePositioned, Point> newRoomTuple = RoomTemplateUtilities.AlignRoomFacing(roomTemplateToPlace, newRoomIndex, existingDoor.OwnerRoom,
                                                                                                   newRoomDoorIndex, existingDoor.DoorIndexInRoom, distanceApart);

            var alignedNewRoom      = newRoomTuple.Item1;
            var alignedDoorLocation = newRoomTuple.Item2;

            var alignedDoorIndex = alignedNewRoom.PotentialDoors.IndexOf(alignedDoorLocation);
            var alignedDoor      = new DoorInfo(alignedNewRoom, newRoomIndex, alignedDoorIndex, RoomTemplateUtilities.GetDoorLocation(alignedNewRoom.Room, alignedDoorIndex));

            //In order to place this successfully, we need to be able to both place the room and a connecting corridor

            if (!mapBuilder.CanBePlacedWithoutOverlappingOtherTemplates(alignedNewRoom))
            {
                throw new ApplicationException("Room failed to place because overlaps existing room");
            }

            //Increase next room for any corridor we may add
            IncreaseNextRoomIndex();

            TemplatePositioned corridorTemplateConnectingRooms = null;
            Connection         connectionToNewRoom             = null;

            if (distanceApart > 1)
            {
                //Need points that are '1-in' from the doors
                var  doorOrientation = RoomTemplateUtilities.GetDoorLocation(existingDoor.OwnerRoom.Room, existingDoor.DoorIndexInRoom);
                bool isHorizontal    = doorOrientation == RoomTemplate.DoorLocation.Left || doorOrientation == RoomTemplate.DoorLocation.Right;

                var corridorTermini = RoomTemplateUtilities.CorridorTerminalPointsBetweenDoors(existingDoorLoc, existingDoor.DoorLocation, alignedDoorLocation, RoomTemplateUtilities.GetOppositeDoorLocation(existingDoor.DoorLocation));
                var corridorIndex   = NextRoomIndex();

                if (corridorTermini.Item1 == corridorTermini.Item2)
                {
                    corridorTemplateConnectingRooms =
                        RoomTemplateUtilities.GetTemplateForSingleSpaceCorridor(corridorTermini.Item1,
                                                                                RoomTemplateUtilities.ArePointsOnVerticalLine(corridorTermini.Item1, corridorTermini.Item2), 0, corridorTemplate, corridorIndex);
                }
                else
                {
                    corridorTemplateConnectingRooms =
                        RoomTemplateUtilities.GetTemplateForCorridorBetweenPoints(corridorTermini.Item1, corridorTermini.Item2, 0, corridorTemplate, corridorIndex);
                }

                //Implicit guarantee that the corridor won't overlap with the new room we're about to place
                //(but it may overlap other previously placed rooms or corridors)
                if (!mapBuilder.CanBePlacedWithoutOverlappingOtherTemplates(corridorTemplateConnectingRooms))
                {
                    throw new ApplicationException("Room failed to place because corridor overlaps existing room");
                }

                //Place the corridor
                mapBuilder.AddPositionedTemplate(corridorTemplateConnectingRooms);
                templates[corridorIndex] = corridorTemplateConnectingRooms;
                IncreaseNextRoomIndex();

                //Add connections to the old and new rooms
                connectionToNewRoom = new Connection(corridorIndex, newRoomIndex);

                connectivityMap.AddRoomConnection(existingDoor.OwnerRoomIndex, corridorIndex);
                LogFile.Log.LogEntryDebug("Adding connection: " + existingDoor.OwnerRoomIndex + " to " + corridorIndex, LogDebugLevel.Medium);
                connectivityMap.AddRoomConnection(corridorIndex, newRoomIndex);
                LogFile.Log.LogEntryDebug("Adding connection: " + corridorIndex + " to " + newRoomIndex, LogDebugLevel.Medium);

                connectionDoors.Add(new Connection(existingDoor.OwnerRoomIndex, corridorIndex).Ordered, existingDoor);
                connectionDoors.Add(connectionToNewRoom.Ordered, alignedDoor);
            }
            else
            {
                //No corridor - a direct connection between the rooms
                connectionToNewRoom = new Connection(existingDoor.OwnerRoomIndex, newRoomIndex);

                connectivityMap.AddRoomConnection(existingDoor.OwnerRoomIndex, newRoomIndex);
                connectionDoors.Add(connectionToNewRoom.Ordered, alignedDoor);
                LogFile.Log.LogEntryDebug("Adding connection: " + existingDoor.OwnerRoomIndex + " to " + newRoomIndex, LogDebugLevel.Medium);
            }

            //Place the room
            bool successfulPlacement = mapBuilder.AddPositionedTemplate(alignedNewRoom);

            if (!successfulPlacement)
            {
                LogFile.Log.LogEntryDebug("Room failed to place because overlaps own corridor - bug", LogDebugLevel.High);
                throw new ApplicationException("Room failed to place because overlaps own corridor - bug");
            }
            templates[newRoomIndex] = alignedNewRoom;

            //Add the new potential doors (excluding the one we are linked on)
            //Can't find a nice linq alternative
            int noDoors = alignedNewRoom.PotentialDoors.Count();

            for (int i = 0; i < noDoors; i++)
            {
                if (alignedNewRoom.PotentialDoors[i] == alignedDoorLocation)
                {
                    continue;
                }
                potentialDoors.Add(new DoorInfo(alignedNewRoom, newRoomIndex, i, RoomTemplateUtilities.GetDoorLocation(alignedNewRoom.Room, i)));
            }

            //If successful, remove the candidate door from the list
            potentialDoors.Remove(existingDoor);

            return(connectionToNewRoom);
        }
Beispiel #3
0
        /// <summary>
        /// Join 2 doors with a corridor. They must be on the opposite sides of their parent rooms (for now)
        /// </summary>
        public bool JoinDoorsWithCorridor(DoorInfo firstDoor, DoorInfo secondDoor, RoomTemplate corridorTemplate)
        {
            try
            {
                if (connectionDoors.ContainsKey(new Connection(firstDoor.OwnerRoomIndex, secondDoor.OwnerRoomIndex).Ordered))
                {
                    LogFile.Log.LogEntryDebug("No allowing 2nd connection between rooms for now - revisit past 7DRL", LogDebugLevel.High);
                    return(false);
                }

                var firstDoorLoc  = RoomTemplateUtilities.GetDoorLocation(firstDoor.OwnerRoom.Room, firstDoor.DoorIndexInRoom);
                var secondDoorLoc = RoomTemplateUtilities.GetDoorLocation(secondDoor.OwnerRoom.Room, secondDoor.DoorIndexInRoom);

                var firstDoorCoord  = firstDoor.MapCoords;
                var secondDoorCoord = secondDoor.MapCoords;

                var corridorTermini = RoomTemplateUtilities.CorridorTerminalPointsBetweenDoors(firstDoor.MapCoords, firstDoor.DoorLocation, secondDoor.MapCoords, secondDoor.DoorLocation);

                bool canDoLSharedCorridor  = RoomTemplateUtilities.CanBeConnectedWithLShapedCorridor(firstDoorCoord, firstDoorLoc, secondDoorCoord, secondDoorLoc);
                bool canDoBendCorridor     = RoomTemplateUtilities.CanBeConnectedWithBendCorridor(firstDoorCoord, firstDoorLoc, secondDoorCoord, secondDoorLoc);
                bool canDoStraightCorridor = RoomTemplateUtilities.CanBeConnectedWithStraightCorridor(firstDoorCoord, firstDoorLoc, secondDoorCoord, secondDoorLoc);
                bool areAdjacent           = corridorTermini.Item1 == secondDoorCoord && corridorTermini.Item2 == firstDoorCoord;
                bool areOverlapping        = firstDoorCoord == secondDoorCoord;

                if (!canDoLSharedCorridor && !canDoBendCorridor && !canDoStraightCorridor && !areAdjacent && !areOverlapping)
                {
                    throw new ApplicationException("No corridor available to connect this type of door");
                }

                if (areAdjacent || areOverlapping)
                {
                    //Add a direct connection in the connectivity graph
                    connectivityMap.AddRoomConnection(firstDoor.OwnerRoomIndex, secondDoor.OwnerRoomIndex);
                    connectionDoors.Add(new Connection(firstDoor.OwnerRoomIndex, secondDoor.OwnerRoomIndex).Ordered, firstDoor);
                }
                else
                {
                    //Create template

                    var horizontal = false;
                    if (firstDoorLoc == RoomTemplate.DoorLocation.Left || firstDoorLoc == RoomTemplate.DoorLocation.Right)
                    {
                        horizontal = true;
                    }

                    int xOffset = corridorTermini.Item2.x - corridorTermini.Item1.x;
                    int yOffset = corridorTermini.Item2.y - corridorTermini.Item1.y;

                    RoomTemplate expandedCorridor;
                    Point        corridorTerminus1InTemplate;

                    if (canDoBendCorridor)
                    {
                        int transition = (int)Math.Floor(yOffset / 2.0);
                        if (horizontal == true)
                        {
                            transition = (int)Math.Floor(xOffset / 2.0);
                        }
                        var expandedCorridorAndPoint = RoomTemplateUtilities.ExpandCorridorTemplateBend(xOffset, yOffset, transition, horizontal, corridorTemplate);
                        expandedCorridor            = expandedCorridorAndPoint.Item1;
                        corridorTerminus1InTemplate = expandedCorridorAndPoint.Item2;
                    }
                    else if (canDoLSharedCorridor)
                    {
                        var expandedCorridorAndPoint = RoomTemplateUtilities.ExpandCorridorTemplateLShaped(xOffset, yOffset, horizontal, corridorTemplate);
                        expandedCorridor            = expandedCorridorAndPoint.Item1;
                        corridorTerminus1InTemplate = expandedCorridorAndPoint.Item2;
                    }
                    else
                    {
                        var offsetToUse = horizontal ? xOffset : yOffset;
                        var expandedCorridorAndPoint = RoomTemplateUtilities.ExpandCorridorTemplateStraight(offsetToUse, horizontal, corridorTemplate);
                        expandedCorridor            = expandedCorridorAndPoint.Item1;
                        corridorTerminus1InTemplate = expandedCorridorAndPoint.Item2;
                    }

                    //Place corridor

                    //Match corridor tile to location of door
                    Point topLeftCorridor = corridorTermini.Item1 - corridorTerminus1InTemplate;

                    var corridorRoomIndex  = NextRoomIndex();
                    var positionedCorridor = new TemplatePositioned(topLeftCorridor.x, topLeftCorridor.y, 0, expandedCorridor, corridorRoomIndex);

                    if (!mapBuilder.CanBePlacedWithoutOverlappingOtherTemplates(positionedCorridor))
                    {
                        return(false);
                    }

                    //Place the corridor
                    mapBuilder.AddPositionedTemplate(positionedCorridor);
                    templates[corridorRoomIndex] = positionedCorridor;
                    IncreaseNextRoomIndex();

                    //Add connections to the old and new rooms
                    connectivityMap.AddRoomConnection(firstDoor.OwnerRoomIndex, corridorRoomIndex);
                    connectivityMap.AddRoomConnection(corridorRoomIndex, secondDoor.OwnerRoomIndex);

                    connectionDoors.Add(new Connection(firstDoor.OwnerRoomIndex, corridorRoomIndex).Ordered, firstDoor);
                    connectionDoors.Add(new Connection(corridorRoomIndex, secondDoor.OwnerRoomIndex).Ordered, secondDoor);
                }

                //Remove both doors from the potential list
                potentialDoors.Remove(firstDoor);
                potentialDoors.Remove(secondDoor);

                return(true);
            }
            catch (ApplicationException ex)
            {
                LogFile.Log.LogEntryDebug("Failed to join doors: " + ex.Message, LogDebugLevel.Medium);
                return(false);
            }
        }
Beispiel #4
0
        public static int find_first_step(RoomTemplate src, RoomTemplate target, int maxdist)
        {
            if (src == null || target == null)
            {
                LogManager.Instance.Bug("Illegal value passed to find_first_step");
                return(BFS_ERROR);
            }

            if (src == target)
            {
                return(BFS_ALREADY_THERE);
            }

            if (src.Area != target.Area)
            {
                return(BFS_NO_PATH);
            }

            room_enqueue(src);
            MARK(src);

            var curr_dir = 0;

            foreach (var exit in src.Exits.Where(valid_edge))
            {
                curr_dir = (int)exit.Direction;
                MARK(exit.GetDestination());
                room_enqueue(exit.GetDestination());
                bfs_enqueue(exit.GetDestination(), Convert.ToChar(curr_dir));
            }

            var count = 0;

            var queueHead = BFS_DATA.Peek();

            while (queueHead != null)
            {
                if (++count > maxdist)
                {
                    bfs_clear_queue();
                    clean_room_queue();
                    return(BFS_NO_PATH);
                }
                if (queueHead.Room == target)
                {
                    curr_dir = queueHead.Dir;
                    bfs_clear_queue();
                    clean_room_queue();
                    return(curr_dir);
                }

                foreach (var exit in queueHead.Room.Exits.Where(valid_edge))
                {
                    curr_dir = (int)exit.Direction;
                    MARK(exit.GetDestination());
                    room_enqueue(exit.GetDestination());
                    bfs_enqueue(exit.GetDestination(), queueHead.Dir);
                }
                bfs_dequeue();
            }

            clean_room_queue();
            return(BFS_NO_PATH);
        }
Beispiel #5
0
 public static void bfs_enqueue(RoomTemplate room, char dir)
 {
     BFS_DATA.Enqueue(new BFSQueueData {
         Room = room, Dir = dir
     });
 }
Beispiel #6
0
 public static void UNMARK(RoomTemplate room)
 {
     room.Flags.RemoveBit(BFS_MARK);
 }
    public void ExploreNextRoom()
    {
        int x = (int)selectedUnit.transform.position.x;
        int y = (int)selectedUnit.transform.position.y;

        Debug.Log("Selected Unit position: " + x + ", " + y);

        //TODO: Implement this so that it detects valid placement positions for the gateways
        //Change tint of room template when placement is valid or invalid
        //Change so that gateway tiles are held on mouseposition
        //Create tiles adjacent to existing gateways to allow placement on these


        //nextRoomTemplate = Instantiate(Resources.Load("Prefabs/NextRoom", typeof(GameObject))) as GameObject;
        //GameObject prefab;
        nextRoomTemplate = Resources.Load <GameObject>("Prefabs/NestRoom_EastSouth");
        RoomTemplate nextRoom = new RoomTemplate("Nest", 4, 4, 1, 0, Facing.South, 3, 2, Facing.East);

        Debug.Log("Gateway One x Position " + nextRoom.GatewayOneX);
        //Instantiate(nextRoomTemplate, new Vector3(x, y, 0), Quaternion.identity);
        //Debug.Log(prefab.transform);
        //GameObject nextRoomTemplate = Instantiate(prefab, new Vector3(x, y, 0), Quaternion.identity);

        //TODO: Put this into a separate method, so it can be called by the RoomPlacement Class

        if (tiles[x, y] == 3)
        {
            Debug.Log("Unit on open gateway");
            if (tiles[x - 1, y] == 3)
            {
                Debug.Log("Left adjacent square is also open gateway");
                if (tiles[x, y + 1] == 5)
                {
                    Debug.Log("Above tiles are room entrances");
                    placementGatewayX      = x - 1;
                    placementGatewayY      = y + 1;
                    placementGatewayFacing = Facing.South;
                    Instantiate(nextRoomTemplate, new Vector3(placementGatewayX - nextRoom.GatewayOneX, placementGatewayY, 0), Quaternion.identity);

                    //TODO: Add code to handle Room placement
                    //Check that the new room gateways are sitting on acceptable tiles
                    //Allow room rotation and check for collision with existing room
                    //Room will be placed with left click - then call generation code again to generate the room and its map data
                }
                else if (tiles[x, y - 1] == 5)
                {
                    Debug.Log("Below tiles are room entrances");
                    placementGatewayX      = x - 1;
                    placementGatewayY      = y - 1;
                    placementGatewayFacing = Facing.North;
                    Instantiate(nextRoomTemplate, new Vector3((x - 1) - nextRoom.GatewayOneX, y - 1, 0), Quaternion.identity);
                }
            }
            else if (tiles[x + 1, y] == 3)
            {
                Debug.Log("Right adjacent square is also open gateway");
                if (tiles[x, y + 1] == 5)
                {
                    Debug.Log("Above tiles are room entrances");
                    placementGatewayX      = x;
                    placementGatewayY      = y + 1;
                    placementGatewayFacing = Facing.South;
                    //Instantiate(nextRoomTemplate, new Vector3(x, y + 1, 0), Quaternion.identity);
                    Instantiate(nextRoomTemplate, new Vector3(x - nextRoom.GatewayOneX, y + 1, 0), Quaternion.identity);
                }
                else if (tiles[x, y - 1] == 5)
                {
                    Debug.Log("Below tiles are room entrances");
                    placementGatewayX      = x;
                    placementGatewayY      = y - 1;
                    placementGatewayFacing = Facing.North;
                    Instantiate(nextRoomTemplate, new Vector3(x - nextRoom.GatewayOneX, y - 1, 0), Quaternion.identity);
                }
            }
            else if (tiles[x, y - 1] == 3)
            {
                Debug.Log("Bottom adjacent square is also open gateway");
                if (tiles[x + 1, y] == 5)
                {
                    Debug.Log("Right tiles are room entrances");
                    placementGatewayX      = x + 1;
                    placementGatewayY      = y - 1;
                    placementGatewayFacing = Facing.West;
                    Instantiate(nextRoomTemplate, new Vector3(x + 1, (y - 1) - nextRoom.GatewayOneY, 0), Quaternion.identity);
                }
                else if (tiles[x - 1, y] == 5)
                {
                    Debug.Log("Left tiles are room entrances");
                    placementGatewayX      = x - 1;
                    placementGatewayY      = y - 1;
                    placementGatewayFacing = Facing.East;
                    Instantiate(nextRoomTemplate, new Vector3(x - 1, (y - 1) - nextRoom.GatewayOneY, 0), Quaternion.identity);
                }
            }
            else if (tiles[x, y + 1] == 3)
            {
                Debug.Log("Top adjacent square is also open gateway");
                if (tiles[x + 1, y] == 5)
                {
                    Debug.Log("Right tiles are room entrances");
                    placementGatewayX      = x + 1;
                    placementGatewayY      = y;
                    placementGatewayFacing = Facing.West;
                    Instantiate(nextRoomTemplate, new Vector3(x + 1, y - nextRoom.GatewayOneY, 0), Quaternion.identity);
                }
                else if (tiles[x - 1, y] == 5)
                {
                    Debug.Log("Left tiles are room entrances");
                    placementGatewayX      = x - 1;
                    placementGatewayY      = y;
                    placementGatewayFacing = Facing.East;
                    Instantiate(nextRoomTemplate, new Vector3(x - 1, y - nextRoom.GatewayOneY, 0), Quaternion.identity);
                }
            }
        }
        else if ((tiles[x, y] == 4))
        {
            Debug.Log("Unit on connected gateway");
        }
        else
        {
            Debug.Log("Unit NOT on gateway");
        }
    }
Beispiel #8
0
    public static RoomTemplate ParseXML(string templateName, XmlNode roomTemplateXML)
    {
        RoomTemplate roomTemplate = new RoomTemplate();

        roomTemplate.m_templateName = templateName;
        roomTemplate.m_floor = TileGridTemplate.ParseXML(roomTemplateXML.SelectSingleNode(".//Floor"));
        roomTemplate.m_walls = TileGridTemplate.ParseXML(roomTemplateXML.SelectSingleNode(".//Walls"));
        roomTemplate.m_backgroundObjects = TileGridTemplate.ParseXML(roomTemplateXML.SelectSingleNode(".//BackgroundObjects"));
        roomTemplate.m_navMeshTemplate =
            AsyncRPGSharedLib.Navigation.NavMesh.FromNavMeshXML(roomTemplateXML.SelectSingleNode(".//NavMesh"));
        roomTemplate.m_forgroundObjects = TileGridTemplate.ParseXML(roomTemplateXML.SelectSingleNode(".//ForegroundObjects"));

        return roomTemplate;
    }
Beispiel #9
0
        /// <summary>
        /// If in graphical client mode, returns the character pair representing foreground
        /// and background terrain types.
        ///
        /// Otherwise, returns the colorized ASCII string representing that map square.
        /// </summary>
        /// <param name="room"></param>
        /// <param name="graphicalClient"></param>
        /// <returns></returns>
        public static string GetMapCharacters(RoomTemplate room, bool graphicalClient)
        {
            int offset = 64;

            if (graphicalClient)
            {
                // Convert terrain type to terminal-friendly characters.
                char val1 = (char)(room.TerrainType + offset);
                char val2 = (char)offset;
                if (room.WorldmapTerrainType != 0)
                {
                    val2 = (char)(room.WorldmapTerrainType + offset);
                }
                else
                {
                    // Set default overlays for certain terrain types (trees, mountains, hills).
                    switch (room.TerrainType)
                    {
                    default:
                        break;

                    case TerrainType.city:
                        // Neutral city by default.
                        val2 = (char)(41 + offset);
                        break;

                    case TerrainType.forest:
                        // Oak tree by default.
                        val2 = (char)(42 + offset);
                        break;

                    case TerrainType.hills:
                        // Green hills by default.
                        val2 = (char)(19 + offset);
                        break;

                    case TerrainType.jungle:
                        val2 = (char)(31 + offset);
                        break;

                    case TerrainType.mountain:
                        val2 = (char)(37 + offset);
                        break;

                    case TerrainType.road:
                        val2 = (char)(55 + offset);
                        // TODO: Determine tile type based on roads nearby, or populate the map with better data.
                        // for example, these are the road tiles available in the Basternae client:
                        //
                        //_foregroundTile[52] =  new wxBitmap( pathPrefix + _("road_ew.png"), wxBITMAP_TYPE_PNG ) ;
                        //_foregroundTile[53] =  new wxBitmap( pathPrefix + _("road_ns.png"), wxBITMAP_TYPE_PNG ) ;
                        //_foregroundTile[54] =  new wxBitmap( pathPrefix + _("road_4way.png"), wxBITMAP_TYPE_PNG ) ;
                        //_foregroundTile[55] =  new wxBitmap( pathPrefix + _("road_corner_ne.png"), wxBITMAP_TYPE_PNG ) ;
                        //_foregroundTile[56] =  new wxBitmap( pathPrefix + _("road_corner_nw.png"), wxBITMAP_TYPE_PNG ) ;
                        //_foregroundTile[57] =  new wxBitmap( pathPrefix + _("road_corner_se.png"), wxBITMAP_TYPE_PNG ) ;
                        //_foregroundTile[58] =  new wxBitmap( pathPrefix + _("road_corner_sw.png"), wxBITMAP_TYPE_PNG ) ;
                        //_foregroundTile[59] =  new wxBitmap( pathPrefix + _("road_tshape_e.png"), wxBITMAP_TYPE_PNG ) ;
                        //_foregroundTile[60] =  new wxBitmap( pathPrefix + _("road_tshape_n.png"), wxBITMAP_TYPE_PNG ) ;
                        //_foregroundTile[61] =  new wxBitmap( pathPrefix + _("road_tshape_s.png"), wxBITMAP_TYPE_PNG ) ;
                        //_foregroundTile[62] =  new wxBitmap( pathPrefix + _("road_tshape_w.png"), wxBITMAP_TYPE_PNG ) ;
                        break;
                    }
                }
                return(val1.ToString() + val2.ToString());
            }

            if (room.WorldmapTerrainType == 0)
            {
                switch (room.TerrainType)
                {
                default:
                    return("&+w.&n");

                case TerrainType.city:
                    return("&+W^&n");

                case TerrainType.field:
                    return("&+G.&n");

                case TerrainType.forest:
                    return("&+g*&n");

                case TerrainType.hills:
                    return("&+y^&n");

                case TerrainType.jungle:
                    return("&+G*&n");

                case TerrainType.lava:
                    return("&+r#&n");

                case TerrainType.mountain:
                    return("&+yM&n");

                case TerrainType.ocean:
                case TerrainType.unswimmable_water:
                    return("&-b&+B~&n");

                case TerrainType.underground_wild:
                    return("&+m.&n");

                case TerrainType.underground_unswimmable_water:
                case TerrainType.underground_ocean:
                    return("&-b&+L~&n");

                case TerrainType.underground_frozen:
                    return("&+W.&n");

                case TerrainType.tundra:
                    return("&+W.&n");

                case TerrainType.underground_swimmable_water:
                case TerrainType.swimmable_water:
                    return("&-B &n");

                case TerrainType.swamp:
                    return("&+G#&n");

                case TerrainType.road:
                    return("&+w+&n");

                case TerrainType.glacier:
                    return("&+W#&n");

                case TerrainType.desert:
                    return("&+Y~&n");
                }
            }
            else
            {
                return("&-L &n");
            }
        }
        public MapDescription <int> GetMapDescription()
        {
            // Create boss room template and room description
            var bossRoom = new RoomTemplate(
                new PolygonGrid2DBuilder()
                .AddPoint(2, 0).AddPoint(2, 1).AddPoint(1, 1).AddPoint(1, 2)
                .AddPoint(0, 2).AddPoint(0, 7).AddPoint(1, 7).AddPoint(1, 8)
                .AddPoint(2, 8).AddPoint(2, 9).AddPoint(7, 9).AddPoint(7, 8)
                .AddPoint(8, 8).AddPoint(8, 7).AddPoint(9, 7).AddPoint(9, 2)
                .AddPoint(8, 2).AddPoint(8, 1).AddPoint(7, 1).AddPoint(7, 0)
                .Build().Scale(new Vector2Int(2, 2)),
                new SimpleDoorMode(1, 1)
                );

            var bossRoomDescription = new BasicRoomDescription(new List <RoomTemplate>()
            {
                bossRoom
            });

            // Create basic room templates and room description
            var doorMode = new SimpleDoorMode(1, 1);

            var squareRoom = new RoomTemplate(
                PolygonGrid2D.GetSquare(8),
                doorMode
                );

            var rectangleRoom = new RoomTemplate(
                PolygonGrid2D.GetRectangle(6, 10),
                doorMode,
                new List <TransformationGrid2D>()
            {
                TransformationGrid2D.Identity, TransformationGrid2D.Rotate90
            }
                );

            var basicRoomDescription = new BasicRoomDescription(new List <RoomTemplate>()
            {
                squareRoom, rectangleRoom
            });

            // Create map description
            var mapDescription = new MapDescription <int>();

            // Get graph
            var graph = GraphsDatabase.GetExample2();

            // Add boss room
            mapDescription.AddRoom(8, bossRoomDescription);

            // Add other rooms
            foreach (var vertex in graph.Vertices.Where(x => x != 8))
            {
                mapDescription.AddRoom(vertex, basicRoomDescription);
            }

            // Add connections
            foreach (var connection in graph.Edges)
            {
                mapDescription.AddConnection(connection.From, connection.To);
            }

            return(mapDescription);
        }
Beispiel #11
0
        public RoomFilling(RoomTemplate template)
        {
            this.template = template;

            BuildPathableMap();
        }
Beispiel #12
0
        private static bool MakeFleeAttempt(CharacterInstance ch, RoomTemplate wasIn)
        {
            var door = db.number_door();
            var exit = wasIn.GetExit(door);

            if (exit?.GetDestination() == null || exit.Flags.IsSet(ExitFlags.NoFlee) || exit.Flags.IsSet(ExitFlags.Closed) || !ch.IsAffected(AffectedByTypes.PassDoor) || (ch.IsNpc() && exit.GetDestination().Flags.IsSet(RoomFlags.NoMob)))
            {
                return(false);
            }

            var sneak = RepositoryManager.Instance.GetEntity <SkillData>("sneak");

            if (sneak == null)
            {
                return(false);
            }

            ch.StripAffects((int)sneak.ID);
            ch.AffectedBy.RemoveBit((int)AffectedByTypes.Sneak);

            if (ch.CurrentMount?.CurrentFighting != null)
            {
                ch.CurrentMount.StopFighting(true);
            }
            Move.move_char(ch, exit, 0);

            var nowIn = ch.CurrentRoom;

            if (nowIn == wasIn)
            {
                return(false);
            }

            ch.CurrentRoom = wasIn;
            comm.act(ATTypes.AT_FLEE, "$n flees head over heels!", ch, null, null, ToTypes.Room);

            ch.CurrentRoom = nowIn;
            comm.act(ATTypes.AT_FLEE, "$n glances around for signs of pursuit.", ch, null, null, ToTypes.Room);

            if (!ch.IsNpc())
            {
                var wf  = ch.GetMyTarget();
                var pch = (PlayerInstance)ch;

                comm.act(ATTypes.AT_FLEE, "You flee head over heels from combat!", pch, null, null, ToTypes.Character);

                if (pch.Level < LevelConstants.AvatarLevel)
                {
                    LoseExperience(pch);
                }

                if (wf != null)
                {
                    if (pch.PlayerData.CurrentDeity != null)
                    {
                        var ratio = 1.GetNumberThatIsBetween(wf.Level / pch.Level, LevelConstants.MaxLevel);
                        if (wf.CurrentRace == pch.PlayerData.CurrentDeity.NPCRace)
                        {
                            pch.AdjustFavor(DeityFieldTypes.FleeNPCRace, ratio);
                        }
                        else if (wf.CurrentRace == pch.PlayerData.CurrentDeity.NPCFoe)
                        {
                            pch.AdjustFavor(DeityFieldTypes.FleeNPCFoe, ratio);
                        }
                        else
                        {
                            pch.AdjustFavor(DeityFieldTypes.Flee, ratio);
                        }
                    }
                }
            }

            ch.StopFighting(true);
            return(true);
        }
Beispiel #13
0
 private void Start()
 {
     temp        = GameObject.FindGameObjectsWithTag("Room")[0].GetComponent <RoomTemplate>();
     Room_Parent = temp.GetComponentInParent <Transform>();
     Invoke("SetUpClosedRoom", GameManager.instance.WaitTimeBeforeDestroy + 0.1f);
 }
    private static bool ValidateRoomTemplate(
        string templateName,
        RoomTemplate roomTemplate,
        byte[] compressedNavCells,
        byte[] compressedPVS)
    {
        bool success = true;

        // Compressed navCells/PVS can be decompressed back into the same nav-mesh
        success &= ValidateCompressedNavMeshData(roomTemplate, compressedNavCells, compressedPVS);

        return success;
    }
    private static bool ValidateCompressedNavMeshData(
        RoomTemplate roomTemplate,
        byte[] compressedNavCells,
        byte[] compressedPVS)
    {
        bool success = true;
        AsyncRPGSharedLib.Navigation.NavMesh testNavMesh =
            AsyncRPGSharedLib.Navigation.NavMesh.FromCompressedNavMeshData(compressedNavCells, compressedPVS);

        if (!testNavMesh.Equals(roomTemplate.NavMeshTemplate))
        {
            Debug.LogError(
                string.Format("RoomTemplateParser: ERROR: Template {0} nav mesh decompressed incorrectly",
                roomTemplate.TemplateName));
            Assert.Throw("RoomTemplateParser: Nav Mesh decompression error");
            success = false;
        }

        return success;
    }
 public Room(RoomTemplate template)
 {
     _Template = template;
 }
        public NormalRoom(NormalRoom prev, Random rand, bool noEvil)
        {
            var indexes = Enumerable.Range(0, roomTemplates.Length).ToList();
            rand.Shuffle(indexes);
            foreach (var index in indexes) {
                if (prev != null && index == prev.currentId)
                    continue;

                if ((roomTemplates[index].Flags & RoomFlags.Evil) != 0 && noEvil)
                    continue;

                if (prev != null) {
                    bool ok = false;
                    foreach (var conn in prev.ConnectionPoints) {
                        var d = conn.Item1.Reverse();
                        if (roomTemplates[index].Connections.Any(targetConn => targetConn.Item1 == d)) {
                            ok = true;
                            break;
                        }
                    }
                    if (!ok)
                        continue;
                }

                currentId = index;
            }
            current = roomTemplates[currentId];
        }
Beispiel #18
0
 private void UpdateExitButtons(RoomTemplate room)
 {
     if (room.ExitData[(int)Exit.Direction.north] == null)
     {
         btnn.ForeColor = System.Drawing.Color.Gray;
     }
     else
     {
         btnn.ForeColor = System.Drawing.Color.Black;
     }
     if (room.ExitData[(int)Exit.Direction.northwest] == null)
     {
         btnnw.ForeColor = System.Drawing.Color.Gray;
     }
     else
     {
         btnnw.ForeColor = System.Drawing.Color.Black;
     }
     if (room.ExitData[(int)Exit.Direction.northeast] == null)
     {
         btnne.ForeColor = System.Drawing.Color.Gray;
     }
     else
     {
         btnne.ForeColor = System.Drawing.Color.Black;
     }
     if (room.ExitData[(int)Exit.Direction.south] == null)
     {
         btns.ForeColor = System.Drawing.Color.Gray;
     }
     else
     {
         btns.ForeColor = System.Drawing.Color.Black;
     }
     if (room.ExitData[(int)Exit.Direction.southeast] == null)
     {
         btnse.ForeColor = System.Drawing.Color.Gray;
     }
     else
     {
         btnse.ForeColor = System.Drawing.Color.Black;
     }
     if (room.ExitData[(int)Exit.Direction.southwest] == null)
     {
         btnsw.ForeColor = System.Drawing.Color.Gray;
     }
     else
     {
         btnsw.ForeColor = System.Drawing.Color.Black;
     }
     if (room.ExitData[(int)Exit.Direction.east] == null)
     {
         btne.ForeColor = System.Drawing.Color.Gray;
     }
     else
     {
         btne.ForeColor = System.Drawing.Color.Black;
     }
     if (room.ExitData[(int)Exit.Direction.west] == null)
     {
         btnw.ForeColor = System.Drawing.Color.Gray;
     }
     else
     {
         btnw.ForeColor = System.Drawing.Color.Black;
     }
     if (room.ExitData[(int)Exit.Direction.up] == null)
     {
         btnup.ForeColor = System.Drawing.Color.Gray;
     }
     else
     {
         btnup.ForeColor = System.Drawing.Color.Black;
     }
     if (room.ExitData[(int)Exit.Direction.down] == null)
     {
         btndn.ForeColor = System.Drawing.Color.Gray;
     }
     else
     {
         btndn.ForeColor = System.Drawing.Color.Black;
     }
 }
Beispiel #19
0
 private void Start()
 {
     Template = GameObject.FindGameObjectWithTag("Rooms").GetComponent <RoomTemplate>();
     Invoke("Spawn", 0.1f);
 }
Beispiel #20
0
 private void Start()
 {
     Destroy(gameObject, waitTime);
     templates = GameObject.FindGameObjectWithTag("Rooms").GetComponent <RoomTemplate>();
     Invoke("Spawn", 0.05f);
 }
Beispiel #21
0
 public static void MARK(RoomTemplate room)
 {
     room.Flags.IsSet(BFS_MARK);
 }
Beispiel #22
0
    public override void Generate(BoardGenerator boardGenerator)
    {
        char charToWrite;

        if (!useDefaultEmptyChar)
        {
            charToWrite = alternateCharToUse;
        }
        else
        {
            charToWrite = boardGenerator.boardGenerationProfile.boardLibrary.GetDefaultEmptyChar();
        }

        Vector2      startLocation   = startLocations[Random.Range(0, startLocations.Length)];
        GridPosition startPosition   = boardGenerator.Vector2ToGridPosition(startLocation);
        GridPosition targetPosition  = boardGenerator.GetRandomGridPosition();
        GridPosition currentPosition = startPosition;

        for (int i = 0; i < tunnelLength; i++)
        {
            if (RollPercentage(turnPercentChance))
            {
                GridPosition turnPosition = boardGenerator.GetRandomGridPosition();
                while (turnPosition.x == targetPosition.x || turnPosition.y == targetPosition.y)
                {
                    turnPosition = boardGenerator.GetRandomGridPosition();
                }

                targetPosition = turnPosition;
            }

            if (spawnRandomRoomsOnTunnel)
            {
                if (RollPercentage(roomSpawnChance))
                {
                    RoomTemplate randTemplate = roomTemplates[Random.Range(0, roomTemplates.Length)];
                    boardGenerator.DrawTemplate(currentPosition.x, currentPosition.y, randTemplate, overwriteFilledSpaces, generatesEmptySpace);
                }
            }

            List <GeneratorWanderTunnel> branchTunnelerList = new List <GeneratorWanderTunnel>();

            if (RollPercentage(branchPercentChance))
            {
                GeneratorWanderTunnel wanderTunneler = ScriptableObject.CreateInstance <GeneratorWanderTunnel>();

                wanderTunneler.tunnelMaxLength        = branchTunnel.tunnelMaxLength;
                wanderTunneler.overwriteFilledSpaces  = branchTunnel.overwriteFilledSpaces;
                wanderTunneler.useDefaultEmptyChar    = branchTunnel.useDefaultEmptyChar;
                wanderTunneler.alternateCharToUse     = branchTunnel.alternateCharToUse;
                wanderTunneler.startLocations         = new Vector2[1];
                wanderTunneler.startLocations[0]      = new Vector2(currentPosition.x, currentPosition.y);
                wanderTunneler.roomTemplates          = branchTunnel.roomTemplates;
                wanderTunneler.spawnRoomsOnTunnelTurn = branchTunnel.spawnRoomsOnTunnelTurn;
                wanderTunneler.spawnRoomOnTunnelEnd   = branchTunnel.spawnRoomOnTunnelEnd;
                wanderTunneler.turnNoiseValue         = branchTunnel.turnNoiseValue;
                branchTunnelerList.Add(wanderTunneler);
            }

            for (int j = 0; j < branchTunnelerList.Count; j++)
            {
                branchTunnelerList[j].Generate(boardGenerator);
            }


            Dig(boardGenerator, currentPosition, targetPosition, charToWrite);
        }

        if (spawnRandomRoomsOnTunnel)
        {
            RoomTemplate randTemplate = roomTemplates[Random.Range(0, roomTemplates.Length)];
            boardGenerator.DrawTemplate(currentPosition.x, currentPosition.y, randTemplate, overwriteFilledSpaces, generatesEmptySpace);
        }
    }
Beispiel #23
0
 public static bool IS_MARKED(RoomTemplate room)
 {
     return(room.Flags.IsSet(BFS_MARK));
 }
Beispiel #24
0
 public void InitDoorWithRoom(RoomTemplate room)
 {
     roomRef = room;
 }
Beispiel #25
0
 public static void room_enqueue(RoomTemplate room)
 {
     room_queue.Add(new BFSQueueData {
         Room = room
     });
 }
Beispiel #26
0
    public void RebuildRoom(RoomData room)
    {
        if (m_backgroundTiles == null)
        {
            m_backgroundTiles = new TileGridWidget(m_backgroundGroup, "BackgroundTiles", Screen.width, Screen.height, 3, 0.0f, 0.0f);
        }

        if (m_wallTiles == null)
        {
            m_wallTiles = new TileGridWidget(m_backgroundGroup, "WallTiles", Screen.width, Screen.height, 2, 0.0f, 0.0f);
        }

        if (m_backgroundObjectTiles == null)
        {
            m_backgroundObjectTiles = new TileGridWidget(m_backgroundGroup, "BackgroundObjects", Screen.width, Screen.height, 1, 0.0f, 0.0f);
        }

        if (m_foregroundObjectTiles == null)
        {
            m_foregroundObjectTiles = new TileGridWidget(m_foregroundGroup, "ForegroundObjects", Screen.width, Screen.height, 0, 0.0f, 0.0f);
        }

        // Covert the tile IDs over to sprite sheet indices
        RoomTemplate roomTemplate = room.StaticRoomData.RoomTemplate;

        TileGridTemplate floorGrid = roomTemplate.FloorGridTemplate;

        m_backgroundTiles.LoadMap(
            floorGrid.TileIndices,
            floorGrid.RowCount, floorGrid.ColomnCount,
            floorGrid.TileSetImageName, floorGrid.TileWidth, floorGrid.TileHeight);

        TileGridTemplate wallGrid = roomTemplate.WallGridTemplate;

        m_wallTiles.LoadMap(
            wallGrid.TileIndices,
            wallGrid.RowCount, wallGrid.ColomnCount,
            wallGrid.TileSetImageName, wallGrid.TileWidth, wallGrid.TileHeight);

        TileGridTemplate backgroundObjGrid = roomTemplate.BackgroundObjectsTemplate;

        m_backgroundObjectTiles.LoadMap(
            backgroundObjGrid.TileIndices,
            backgroundObjGrid.RowCount, backgroundObjGrid.ColomnCount,
            backgroundObjGrid.TileSetImageName, backgroundObjGrid.TileWidth, backgroundObjGrid.TileHeight);

        TileGridTemplate foregroundObjGroup = roomTemplate.BackgroundObjectsTemplate;

        m_foregroundObjectTiles.LoadMap(
            foregroundObjGroup.TileIndices,
            foregroundObjGroup.RowCount, foregroundObjGroup.ColomnCount,
            foregroundObjGroup.TileSetImageName, foregroundObjGroup.TileWidth, foregroundObjGroup.TileHeight);

        //TODO: rebuildRoom: Use animated tile entities from the room template

        /*var tileIdGrid:Array = room.staticRoomData.backgroundTileGrid;
         * var tileIndices:Array = new Array();
         * for (var listIndex:uint = 0; listIndex < tileIdGrid.length; listIndex++)
         * {
         *      var tileId:uint = tileIdGrid[listIndex];
         *      var tileDescriptor:TileDescriptor= currentTileSet.getTileDescriptorById(tileId);
         *      var sheetIndex:int = tileDescriptor.sheetIndex;
         *
         *      // Create an animated tile for any tile that has more than one frame
         *      if (tileDescriptor.frameCount > 1)
         *      {
         *              var tileColomn:uint = listIndex % room.staticRoomData.tileColomns;
         *              var tileRow:uint = uint(listIndex / room.staticRoomData.tileColomns);
         *              var tileX:Number = Number(tileColomn) * currentTileSet.TileWidth;
         *              var tileY:Number = Number(tileRow) * currentTileSet.TileHeight;
         *
         *              new AnimatedTileWidget(m_backgroundGroup, currentTileSet, tileDescriptor, tileX, tileY);
         *      }
         *
         *      tileIndices.push(sheetIndex);
         * }*/
    }
 void Start()
 {
     templates = GameObject.FindGameObjectWithTag("Rooms").GetComponent <RoomTemplate>();
     templates.rooms.Add(this.gameObject);
 }
Beispiel #28
0
        public static RoomTemplate generate_exit(RoomTemplate room, ExitData exit)
        {
            long         serial;
            long         roomnum;
            long         brvnum;
            long         distance = -1;
            RoomTemplate backroom;
            var          vdir = (int)exit.Direction;

            if (room.ID > 32767)
            {
                serial  = room.ID;
                roomnum = room.TeleportToVnum;
                if ((serial & 65535) == exit.vnum)
                {
                    brvnum = serial >> 16;
                    --roomnum;
                    distance = roomnum;
                }
                else
                {
                    brvnum = serial & 65535;
                    ++roomnum;
                    distance = exit.Distance - 1;
                }
                backroom = RepositoryManager.Instance.ROOMS.CastAs <Repository <long, RoomTemplate> >().Get(brvnum);
            }
            else
            {
                var r1 = room.ID;
                var r2 = exit.vnum;

                brvnum   = r1;
                backroom = room;
                serial   = (r1.GetHighestOfTwoNumbers(r2) << 16) | r1.GetLowestOfTwoNumbers(r2);
                distance = exit.Distance - 1;
                roomnum  = r1 < r2 ? 1 : distance;
            }

            var found = false;

            var foundRoom =
                RepositoryManager.Instance.ROOMS.CastAs <Repository <long, RoomTemplate> >().Values.FirstOrDefault(
                    x => x.ID == serial && x.TeleportToVnum == roomnum);

            if (foundRoom != null)
            {
                found = true;
            }

            // Create room in direction
            RoomTemplate newRoom = null;

            if (!found)
            {
                newRoom = new RoomTemplate(serial, "New room")
                {
                    Area           = room.Area,
                    TeleportToVnum = roomnum,
                    SectorType     = room.SectorType,
                    Flags          = room.Flags
                };
                decorate_room(newRoom);
                RepositoryManager.Instance.ROOMS.CastAs <Repository <long, RoomTemplate> >().Add(newRoom.ID, newRoom);
            }

            var xit = newRoom.GetExit(vdir);

            if (!found || xit == null)
            {
                xit          = db.make_exit(newRoom, exit.GetDestination(), vdir);
                xit.Key      = -1;
                xit.Distance = (int)distance;
            }

            if (!found)
            {
                ExitData bxit = db.make_exit(newRoom, backroom, LookupConstants.rev_dir[vdir]);
                bxit.Key = -1;
                if ((serial & 65536) != exit.vnum)
                {
                    bxit.Distance = (int)roomnum;
                }
                else
                {
                    var tmp = backroom.GetExit(vdir);
                    bxit.Distance = tmp.Distance - (int)distance;
                }
            }

            return(newRoom);
        }
Beispiel #29
0
        /// <summary>
        /// Replace a room template with a smaller one. Aligns new template with old door.
        /// This should only be called on dead-ends
        /// Enforces that replacement rooms can only override floor areas of old rooms (helping to avoid some breakage)
        /// </summary>
        public bool ReplaceRoomTemplate(int roomToReplaceIndex, Connection existingRoomConnection, RoomTemplate replacementRoom, int replaceRoomDoorIndex)
        {
            var templateToReplace = templates[roomToReplaceIndex];

            if (templateToReplace.PotentialDoors.Count() > 1)
            {
                throw new ApplicationException("Can't replace rooms with >1 doors");
            }

            var doorToConnection = GetDoorForConnection(existingRoomConnection);

            Tuple <TemplatePositioned, Point> replacementRoomTuple = RoomTemplateUtilities.AlignRoomOverlapping(replacementRoom, roomToReplaceIndex, templateToReplace,
                                                                                                                replaceRoomDoorIndex, doorToConnection.DoorIndexInRoom);

            var replacementRoomTemplate = replacementRoomTuple.Item1;

            //Check if the overlapping room can be placed
            if (!mapBuilder.CanBePlacedOverlappingOtherTemplates(replacementRoomTemplate))
            {
                return(false);
            }

            //Blank the old room area
            var voidedOldRoomTemplate = RoomTemplateUtilities.TransparentTemplate(templateToReplace);

            mapBuilder.UnconditionallyOverridePositionedTemplate(voidedOldRoomTemplate);

            //Override with new template
            mapBuilder.OverridePositionedTemplate(replacementRoomTemplate);

            //Ensure that the room is replaced in the index
            templates[roomToReplaceIndex] = replacementRoomTemplate;

            //We don't change the connectivity or doors

            return(true);
        }
Beispiel #30
0
        public static void decorate_room(RoomTemplate room)
        {
            var buf      = string.Empty;
            var buf2     = string.Empty;
            var previous = new int[8];

            room.Description = "You're on a pathway.\r\n";

            var sector = room.SectorType;
            var nRand  = SmaugRandom.Between(1, 8.GetLowestOfTwoNumbers(LookupConstants.SentTotals[(int)sector]));

            for (var iRand = 0; iRand < nRand; iRand++)
            {
                previous[iRand] = -1;
            }

            for (var iRand = 0; iRand < nRand; iRand++)
            {
                while (previous[iRand] == -1)
                {
                    var x = SmaugRandom.Between(0, LookupConstants.SentTotals[(int)sector] - 1);

                    int z;
                    for (z = 0; z < iRand; z++)
                    {
                        if (previous[z] == x)
                        {
                            break;
                        }
                    }

                    if (z < iRand)
                    {
                        continue;
                    }

                    previous[iRand] = x;
                    var len = buf.Length;
                    if (len == 0)
                    {
                        buf2 = GetDecorateRoom_PreAndPost_1(iRand, nRand, sector, x);
                    }
                    else if (iRand != nRand - 1)
                    {
                        buf2 = buf.EndsWith(".")
                            ? GetDecorateRoom_PreAndPost_2(sector, x)
                            : GetDecorateRoom_PreAndPost_3(sector, x);
                    }
                    else
                    {
                        buf2 = $"{LookupConstants.RoomSents[(int)sector][x]}.";
                    }

                    if (len > 5 && buf2.EndsWith("."))
                    {
                        buf += "  ";
                        buf2 = buf2.CapitalizeFirst();
                    }
                    else if (len == 0)
                    {
                        buf2 = buf2.CapitalizeFirst();
                    }

                    buf += buf2;
                }
            }

            room.Description = $"{wordwrap(buf, 78)}\r\n";
        }
Beispiel #31
0
        /// <summary>
        ///This function shared by do_transfer and do_mptransfer
        /// Immortals bypass most restrictions on where to transfer victims.
        /// NPCs cannot transfer victims who are:
        /// 1. Not authorized yet.
        /// 2. Outside of the level range for the target room's area.
        /// 3. Being sent to private rooms.
        /// </summary>
        /// <param name="ch"></param>
        /// <param name="victim"></param>
        /// <param name="location"></param>
        public static void transfer_char(CharacterInstance ch, CharacterInstance victim, RoomTemplate location)
        {
            if (victim.CurrentRoom == null)
            {
                LogManager.Instance.Bug("Victim {0} in null room", victim.Name);
                return;
            }

            if (ch.IsNpc() && location.IsPrivate())
            {
                //progbug("Mptransfer - Private room", ch);
                return;
            }

            if (!ch.CanSee(victim))
            {
                return;
            }

            if (ch.IsNpc() && victim.IsNotAuthorized() &&
                location.Area != victim.CurrentRoom.Area)
            {
                var buffer = $"Mptransfer - unauthed char ({victim.Name})";
                //progbug(buffer, ch);
                return;
            }

            // if victim not in area's level range, do not transfer
            if (ch.IsNpc() && !location.Area.IsInHardRange(victim) &&
                !location.Flags.IsSet((int)RoomFlags.Prototype))
            {
                return;
            }

            if (victim.CurrentFighting != null)
            {
                victim.StopFighting(true);
            }

            if (!ch.IsNpc())
            {
                comm.act(ATTypes.AT_MAGIC, "$n disappears in a cloud of swirling colors.", victim, null, null, ToTypes.Room);
                victim.retran = (int)victim.CurrentRoom.ID;
            }

            victim.CurrentRoom.RemoveFrom(victim);
            location.AddTo(victim);

            if (!ch.IsNpc())
            {
                comm.act(ATTypes.AT_MAGIC, "$n arrives from a puff of smoke.", victim, null, null, ToTypes.Room);
                if (ch != victim)
                {
                    comm.act(ATTypes.AT_IMMORT, "$n has transferred you.", ch, null, victim, ToTypes.Victim);
                }
                Look.do_look(victim, "auto");
                if (!victim.IsImmortal() &&
                    !victim.IsNpc() &&
                    !location.Area.IsInHardRange(victim))
                {
                    comm.act(ATTypes.AT_DANGER, "Warning: this player's level is not within the area's level range.", ch, null, null, ToTypes.Character);
                }
            }
        }
Beispiel #32
0
        /// <summary>
        /// Loads the entire MUD database including all classes, races, areas, helps, sytem data, etc.
        /// </summary>
        public void LoadDatabase()
        {
            DatabaseIsBooting = true;

            Log.Trace(DateTime.Now.ToShortDateString() + " BOOT: -------------------------[ Boot Log ]-------------------------");

            Log.Trace("Validating that player directories exist.");
            for (Char letter = 'a'; letter <= 'z'; letter++)
            {
                String directory = FileLocation.PlayerDirectory + letter;
                if (!Directory.Exists(directory))
                {
                    Log.Trace("Creating directory: " + directory + ".");
                    Directory.CreateDirectory(directory);
                }
            }
            Log.Trace("Player directories validated.");

            Log.Trace("Loading Database.SystemData.");
            Sysdata.Load();
            SystemData.CurrentTime  = DateTime.Now;
            SystemData.GameBootTime = SystemData.CurrentTime;

            // Set time and weather.
            Log.Trace("Setting time and weather.");
            SystemData.SetWeather();

            Log.Trace("Loading static rooms.");
            StaticRooms.Load();
            Log.Trace("Loaded " + StaticRooms.Count + " static rooms.");

            Log.Trace("Loading spells.");
            Spell.LoadSpells();
            Log.Trace("Loaded " + Spell.SpellList.Count + " spells.");

            Log.Trace("Loading skills.");
            Skill.LoadSkills();
            Log.Trace("Loaded " + Skill.SkillList.Count + " skills.");

            Log.Trace("Loading races.");
            Race.LoadRaces();
            Log.Trace("Loaded " + Race.Count + " races.");

            Log.Trace("Initializing skill Levels.");
            {
                int cclass;

                foreach (KeyValuePair <String, Skill> kvp in Skill.SkillList)
                {
                    for (cclass = 0; cclass < CharClass.ClassList.Length; cclass++)
                    {
                        kvp.Value.ClassAvailability[cclass] = Limits.LEVEL_LESSER_GOD;
                    }
                }
                foreach (KeyValuePair <String, Spell> kvp in Spell.SpellList)
                {
                    for (cclass = 0; cclass < CharClass.ClassList.Length; cclass++)
                    {
                        kvp.Value.SpellCircle[cclass] = Limits.MAX_CIRCLE + 3;
                    }
                }
            }

            Log.Trace("Loading classes.");
            CharClass.LoadClasses(true);
            Log.Trace("Loaded " + CharClass.Count + " classes.");

            Log.Trace("Assigning spell circles.");
            AssignSpellCircles();
            Log.Trace("Assigned spell circles.");

            Log.Trace("Loading socials.");
            SocialList = Socials.Load();
            Log.Trace("Loaded " + Social.Count + " socials.");

            Log.Trace("Loading bans.");
            LoadBans();
            Log.Trace("Loaded " + BanList.Count + " bans.");

            Log.Trace("Loading help entries.");
            HelpList = Help.Load(FileLocation.SystemDirectory + FileLocation.HelpFile);
            Log.Trace("Loaded " + Help.Count + " help entries.");

            Log.Trace("Loading screens.");
            Screen.Load(FileLocation.SystemDirectory + FileLocation.ScreenFile, FileLocation.BlankSystemFileDirectory + FileLocation.ScreenFile);
            Log.Trace("Loaded " + Screen.Count + " screens.");

            // Chatbots have to be loaded before mobs.
            Log.Trace("Loading chatbots.");
            ChatterBot.Load();
            Log.Trace("Loaded " + ChatterBot.Count + " chatbots.");

            // Read in all the area files.
            Log.Trace("Reading in area files...");
            LoadAreaFiles();
            Log.Trace("Loaded " + Area.Count + " areas.");

            string buf = String.Format("Loaded {0} mobs, {1} objects, {2} rooms, {3} shops, {4} helps, {5} resets, and {6} quests.",
                                       MobTemplate.Count, ObjTemplate.Count, Room.Count, Shop.Count, Help.Count, Reset.Count, QuestData.Count);

            Log.Trace(buf);

            Log.Trace("Loading guilds.");
            Guild.LoadGuilds();
            Log.Trace("Loaded " + Guild.Count + " guilds.");

            Log.Trace("Loading corpses.");
            CorpseList = CorpseData.Load();
            Log.Trace("Loaded " + CorpseData.Count + " corpses.");

            Log.Trace("Loading crimes.");
            Crime.Load();
            Log.Trace("Loaded " + Crime.Count + " crimes.");

            Log.Trace("Loading fraglist.");
            FraglistData.Fraglist.Load();

            Log.Trace("Loading issues.");
            Issue.Load();
            Log.Trace("Loaded " + Issue.Count + " issues.");

            Log.Trace("Loading bounties.");
            Bounty.Load();
            Log.Trace("Loaded " + Bounty.Count + " bounties.");

            Log.Trace("Initializing movement parameters.");
            Movement.Initialize();
            Log.Trace("Movement parameters initialized.");

            // Only compile spells that have attached code.  Otherwise use default handlers.
            Log.Trace("Compiling spells.");
            int good = 0;
            int bad  = 0;

            foreach (KeyValuePair <String, Spell> kvp in Spell.SpellList)
            {
                if (!String.IsNullOrEmpty(kvp.Value.Code))
                {
                    if (!SpellFunction.CompileSpell(kvp.Value))
                    {
                        ++bad;
                    }
                    else
                    {
                        ++good;
                    }
                }
            }
            Log.Trace("Done compiling spells. " + good + " were successful, " + bad + " failed.");

            // Links up exits and makes rooms runtime-ready so we can access them.
            Log.Trace("Linking exits.");
            LinkExits();

            // This has to be after LinkExits().
            Log.Trace("Loading zone connections.");
            ZoneConnectionList = ZoneConnection.Load();
            // Link zones together based on file.
            foreach (ZoneConnection connection in ZoneConnectionList)
            {
                RoomTemplate   room1     = Room.GetRoom(connection.FirstRoomNumber);
                RoomTemplate   room2     = Room.GetRoom(connection.SecondRoomNumber);
                Exit.Direction direction = connection.FirstToSecondDirection;
                if (room1 != null && room2 != null && direction != Exit.Direction.invalid)
                {
                    Exit exit = new Exit();
                    exit.TargetRoom  = room2;
                    exit.IndexNumber = connection.SecondRoomNumber;
                    room1.ExitData[(int)direction] = exit;
                    exit             = new Exit();
                    exit.TargetRoom  = room1;
                    exit.IndexNumber = connection.FirstRoomNumber;
                    room2.ExitData[(int)Exit.ReverseDirection(direction)] = exit;
                    Log.Trace("Connected " + room1.Area.Name + " to " + room2.Area.Name + " at " + room1.IndexNumber);
                }
                else
                {
                    Log.Error("Unable to connect room " + connection.FirstRoomNumber + " to " + connection.SecondRoomNumber + " in direction " + connection.FirstToSecondDirection);
                }
            }
            Log.Trace("Loaded " + ZoneConnectionList.Count + " zone connections.");


            DatabaseIsBooting = false;
            Log.Trace("Resetting areas.");
            AreaUpdate();

            Log.Trace("Creating events.");
            Event.CreateEvent(Event.EventType.save_corpses, Event.TICK_SAVE_CORPSES, null, null, null);
            Event.CreateEvent(Event.EventType.save_sysdata, Event.TICK_SAVE_SYSDATA, null, null, null);
            Event.CreateEvent(Event.EventType.violence_update, Event.TICK_COMBAT_UPDATE, null, null, null);
            Event.CreateEvent(Event.EventType.area_update, Event.TICK_AREA, null, null, null);
            Event.CreateEvent(Event.EventType.room_update, Event.TICK_ROOM, null, null, null);
            Event.CreateEvent(Event.EventType.object_special, Event.TICK_OBJECT, null, null, null);
            Event.CreateEvent(Event.EventType.mobile_update, Event.TICK_MOBILE, null, null, null);
            Event.CreateEvent(Event.EventType.weather_update, Event.TICK_WEATHER, null, null, null);
            Event.CreateEvent(Event.EventType.char_update, Event.TICK_CHAR_UPDATE, null, null, null);
            Event.CreateEvent(Event.EventType.object_update, Event.TICK_OBJ_UPDATE, null, null, null);
            Event.CreateEvent(Event.EventType.aggression_update, Event.TICK_AGGRESS, null, null, null);
            Event.CreateEvent(Event.EventType.memorize_update, Event.TICK_MEMORIZE, null, null, null);
            Event.CreateEvent(Event.EventType.hit_gain, Event.TICK_HITGAIN, null, null, null);
            Event.CreateEvent(Event.EventType.mana_gain, Event.TICK_MANAGAIN, null, null, null);
            Event.CreateEvent(Event.EventType.move_gain, Event.TICK_MOVEGAIN, null, null, null);
            Event.CreateEvent(Event.EventType.heartbeat, Event.TICK_WEATHER, null, null, null);

            return;
        }
Beispiel #33
0
 public void AddRoom(RoomTemplate template)
 {
     roomList.Add(template);
 }
 public RoomTemplateInfo(List <IntAlias <PolygonGrid2D> > aliases, RoomTemplate roomTemplate)
 {
     Aliases      = aliases;
     RoomTemplate = roomTemplate;
 }
Beispiel #35
0
 public RoomGenerator(Environment _env, RoomTemplate _roomTemplate, DunGen.Room _roomBase)
 {
     roomTemplate = _roomTemplate;
     env = _env;
     roomBase = _roomBase;
 }
Beispiel #36
0
    public LevelTemplate GenerateLevelTemplate(int cols                        = DEFAULT_LEVEL_COLS,
                                               int rows                        = DEFAULT_LEVEL_ROWS,
                                               int mainLength                  = DEFAULT_LEVEL_MAIN_LENGTH,
                                               float offshootTemperature       = DEFAULT_LEVEL_OFFSHOOT_TEMPERATURE,
                                               float offshootLengthTemperature = DEFAULT_LEVEL_OFFSHOOT_LENGTH_TEMPERATURE)
    {
        LevelTemplate levelTemplate = new LevelTemplate(cols, rows);

        levelTemplate.SetSpawn(new int[] { cols / 2, rows / 2 });
        SetFirstMain(levelTemplate);

        // connect the spawn to the first main room
        ConnectRooms(levelTemplate, levelTemplate.GetSpawnCoords(), levelTemplate.GetMainHead());

        for (int i = 0; i < mainLength; i++)
        {
            ProceedMain(levelTemplate);
        }
        levelTemplate.SetExit();

        // connect the exit to the last main room
        ConnectRooms(levelTemplate, levelTemplate.GetMainHead(), levelTemplate.GetExitCoords());

        List <int[]> mainCoords = levelTemplate.GetMainCoords();

        foreach (int[] mainCoord in mainCoords)
        {
            List <int[]> surroundingAvailableCoords = GetSurroundingAvailableCoords(levelTemplate, mainCoord);
            if (surroundingAvailableCoords.Count > 0 && rand.NextDouble() < offshootTemperature)
            {
                int[] offshootCoord = surroundingAvailableCoords[rand.Next(surroundingAvailableCoords.Count)];
                levelTemplate.SetOffshoot(offshootCoord);
                RoomTemplate mainRoom     = levelTemplate.GetMap(mainCoord);
                RoomTemplate offshootRoom = levelTemplate.GetMap(offshootCoord);
                ConnectRooms(mainRoom, offshootRoom);
                while (rand.NextDouble() < offshootLengthTemperature)
                {
                    List <int[]> availableNextOffshootCoords = GetSurroundingAvailableCoords(levelTemplate, offshootCoord);
                    if (availableNextOffshootCoords.Count == 0)
                    {
                        break;
                    }
                    int[] oldCoords = offshootCoord;
                    offshootCoord = availableNextOffshootCoords[rand.Next(availableNextOffshootCoords.Count)];
                    levelTemplate.SetOffshoot(offshootCoord);
                    RoomTemplate newOffShootRoom = levelTemplate.GetMap(offshootCoord);
                    ConnectRooms(levelTemplate.GetMap(oldCoords), newOffShootRoom);
                    List <RoomTemplate> potentialConnectRooms = GetPotentialConnectRooms(levelTemplate, offshootCoord, oldCoords);
                    if (potentialConnectRooms.Count < 2)
                    {
                        foreach (RoomTemplate potentialRoom in potentialConnectRooms)
                        {
                            ConnectRooms(newOffShootRoom, potentialRoom);
                        }
                    }
                    offshootLengthTemperature /= 2;
                }
            }
        }

        return(levelTemplate);
    }