Exemple #1
0
        public void PurchaseArea(NWPlayer player, NWArea area, string sector)
        {
            if (sector != AreaSector.Northwest && sector != AreaSector.Northeast &&
                sector != AreaSector.Southwest && sector != AreaSector.Southeast)
            {
                throw new ArgumentException(nameof(sector) + " must match one of the valid sector values: NE, NW, SE, SW");
            }

            if (area.Width < 32)
            {
                throw new Exception("Area must be at least 32 tiles wide.");
            }
            if (area.Height < 32)
            {
                throw new Exception("Area must be at least 32 tiles high.");
            }


            var  dbArea        = _data.Single <Area>(x => x.Resref == area.Resref);
            Guid?existingOwner = null;

            switch (sector)
            {
            case AreaSector.Northwest: existingOwner = dbArea.NorthwestOwner; break;

            case AreaSector.Northeast: existingOwner = dbArea.NortheastOwner; break;

            case AreaSector.Southwest: existingOwner = dbArea.SouthwestOwner; break;

            case AreaSector.Southeast: existingOwner = dbArea.SoutheastOwner; break;
            }

            if (existingOwner != null)
            {
                player.SendMessage("Another player already owns that sector.");
                return;
            }

            var dbPlayer      = _data.Get <Player>(player.GlobalID);
            int purchasePrice = dbArea.PurchasePrice + (int)(dbArea.PurchasePrice * (dbPlayer.LeaseRate * 0.01f));

            if (player.Gold < purchasePrice)
            {
                player.SendMessage("You do not have enough credits to purchase that sector.");
                return;
            }

            player.AssignCommand(() => _.TakeGoldFromCreature(purchasePrice, player.Object, TRUE));

            switch (sector)
            {
            case AreaSector.Northwest: dbArea.NorthwestOwner = player.GlobalID; break;

            case AreaSector.Northeast: dbArea.NortheastOwner = player.GlobalID; break;

            case AreaSector.Southwest: dbArea.SouthwestOwner = player.GlobalID; break;

            case AreaSector.Southeast: dbArea.SoutheastOwner = player.GlobalID; break;
            }

            _data.SubmitDataChange(dbArea, DatabaseActionType.Update);

            PCBase pcBase = new PCBase
            {
                AreaResref          = dbArea.Resref,
                PlayerID            = player.GlobalID,
                DateInitialPurchase = DateTime.UtcNow,
                DateRentDue         = DateTime.UtcNow.AddDays(7),
                DateFuelEnds        = DateTime.UtcNow,
                Sector       = sector,
                PCBaseTypeID = (int)Enumeration.PCBaseType.RegularBase,
                CustomName   = string.Empty
            };

            _data.SubmitDataChange(pcBase, DatabaseActionType.Insert);

            PCBasePermission permission = new PCBasePermission
            {
                PCBaseID = pcBase.ID,
                PlayerID = player.GlobalID
            };

            _data.SubmitDataChange(permission, DatabaseActionType.Insert);

            // Grant all base permissions to owner.
            var allPermissions = Enum.GetValues(typeof(BasePermission)).Cast <BasePermission>().ToArray();

            _perm.GrantBasePermissions(player, pcBase.ID, allPermissions);

            player.FloatingText("You purchase " + area.Name + " (" + sector + ") for " + purchasePrice + " credits.");
        }
Exemple #2
0
        public string CanPlaceStructure(NWCreature user, NWItem structureItem, NWLocation targetLocation, int baseStructureID)
        {
            NWPlayer player = user.Object;
            string   sector = GetSectorOfLocation(targetLocation);

            if (sector == "INVALID")
            {
                return("Invalid location selected.");
            }

            if (structureItem == null || !structureItem.IsValid || !Equals(structureItem.Possessor, user))
            {
                return("Unable to locate structure item.");
            }

            NWArea       area = _.GetAreaFromLocation(targetLocation);
            string       buildingStructureID   = area.GetLocalString("PC_BASE_STRUCTURE_ID");
            Guid         buildingStructureGuid = string.IsNullOrWhiteSpace(buildingStructureID) ? Guid.Empty : new Guid(buildingStructureID);
            string       pcBaseID   = area.GetLocalString("PC_BASE_ID");
            Guid         pcBaseGUID = string.IsNullOrWhiteSpace(pcBaseID) ? Guid.Empty : new Guid(pcBaseID);
            BuildingType buildingType;

            if (!string.IsNullOrWhiteSpace(pcBaseID))
            {
                buildingType = BuildingType.Apartment;
            }
            else if (string.IsNullOrWhiteSpace(buildingStructureID))
            {
                buildingType = BuildingType.Exterior;
            }
            else
            {
                buildingType = BuildingType.Interior;
            }

            Area dbArea = _data.SingleOrDefault <Area>(x => x.Resref == area.Resref);

            if (dbArea == null || !dbArea.IsBuildable)
            {
                return("Structures cannot be placed in this area.");
            }
            PCBase pcBase = !string.IsNullOrWhiteSpace(pcBaseID) ?
                            _data.Get <PCBase>(pcBaseGUID) :
                            _data.SingleOrDefault <PCBase>(x => x.AreaResref == area.Resref && x.Sector == sector);

            if (pcBase == null && buildingType == BuildingType.Interior)
            {
                var parentStructure     = _data.Get <PCBaseStructure>(buildingStructureGuid);
                var parentBaseStructure = _data.Get <BaseStructure>(parentStructure.BaseStructureID);
                pcBase = _data.Get <PCBase>(parentStructure.PCBaseID);

                int buildingStructureCount = _data.GetAll <PCBaseStructure>().Count(x => x.ParentPCBaseStructureID == parentStructure.ID) + 1;
                if (buildingStructureCount > parentBaseStructure.Storage)
                {
                    return("No more structures can be placed inside this building.");
                }
            }

            if (pcBase == null)
            {
                return("This area is unclaimed but not owned by you. You may purchase a lease on it from the planetary government by using your Base Management Tool (found under feats).");
            }

            var canPlaceOrEditStructures = buildingType == BuildingType.Apartment || buildingType == BuildingType.Exterior ?
                                           _perm.HasBasePermission(player, pcBase.ID, BasePermission.CanPlaceEditStructures) :                      // Bases
                                           _perm.HasStructurePermission(player, buildingStructureGuid, StructurePermission.CanPlaceEditStructures); // Buildings

            if (!canPlaceOrEditStructures)
            {
                return("You do not have permission to place or edit structures in this territory.");
            }

            var structure     = _data.Get <BaseStructure>(baseStructureID);
            var structureType = _data.Get <Data.Entity.BaseStructureType>(structure.BaseStructureTypeID);

            if (!structureType.CanPlaceOutside && buildingType == BuildingType.Exterior)
            {
                return("That structure can only be placed inside buildings.");
            }

            if (!structureType.CanPlaceInside && (buildingType == BuildingType.Interior || buildingType == BuildingType.Apartment))
            {
                return("That structure can only be placed outside of buildings.");
            }

            if (buildingType == BuildingType.Exterior)
            {
                var structures = _data.Where <PCBaseStructure>(x => x.PCBaseID == pcBase.ID).ToList();

                bool hasControlTower = structures
                                       .SingleOrDefault(x =>
                {
                    var baseStructure = _data.Get <BaseStructure>(x.BaseStructureID);
                    return(baseStructure.BaseStructureTypeID == (int)BaseStructureType.ControlTower);
                }) != null;

                if (!hasControlTower && structureType.ID != (int)BaseStructureType.ControlTower)
                {
                    return("A control tower must be placed down in the sector first.");
                }

                if (hasControlTower && structureType.ID == (int)BaseStructureType.ControlTower)
                {
                    return("Only one control tower can be placed down per sector.");
                }
            }

            return(null);
        }
Exemple #3
0
        public bool Run(params object[] args)
        {
            NWPlaceable drill       = Object.OBJECT_SELF;
            string      structureID = drill.GetLocalString("PC_BASE_STRUCTURE_ID");

            if (string.IsNullOrWhiteSpace(structureID))
            {
                string areaName = drill.Area.Name;
                Console.WriteLine("There was an error retrieving the PC_BASE_STRUCTURE_ID variable on drill in area: " + areaName);
                return(false);
            }

            Guid            structureGUID = new Guid(structureID);
            PCBaseStructure pcStructure   = _data.Get <PCBaseStructure>(structureGUID);
            PCBase          pcBase        = _data.Get <PCBase>(pcStructure.PCBaseID);
            PCBaseStructure tower         = _base.GetBaseControlTower(pcBase.ID);

            // Check whether there's space in this tower.
            int capacity = _base.CalculateResourceCapacity(pcBase.ID);
            int count    = _data.Where <PCBaseStructureItem>(x => x.PCBaseStructureID == tower.ID).Count() + 1;

            if (count >= capacity)
            {
                return(false);
            }

            BaseStructure baseStructure = _data.Get <BaseStructure>(pcStructure.BaseStructureID);
            DateTime      now           = DateTime.UtcNow;

            var outOfPowerEffect = drill.Effects.SingleOrDefault(x => _.GetEffectTag(x) == "CONTROL_TOWER_OUT_OF_POWER");

            if (now >= pcBase.DateFuelEnds)
            {
                if (outOfPowerEffect == null)
                {
                    outOfPowerEffect = _.EffectVisualEffect(VFX_DUR_AURA_RED);
                    outOfPowerEffect = _.TagEffect(outOfPowerEffect, "CONTROL_TOWER_OUT_OF_POWER");
                    _.ApplyEffectToObject(DURATION_TYPE_PERMANENT, outOfPowerEffect, drill);
                }

                return(true);
            }
            else if (now < pcBase.DateFuelEnds && outOfPowerEffect != null)
            {
                _.RemoveEffect(drill, outOfPowerEffect);
            }

            int minuteReduce    = 2 * pcStructure.StructureBonus;
            int increaseMinutes = 60 - minuteReduce;
            int retrievalRating = baseStructure.RetrievalRating;

            if (increaseMinutes <= 20)
            {
                increaseMinutes = 20;
            }
            if (pcStructure.DateNextActivity == null)
            {
                pcStructure.DateNextActivity = now.AddMinutes(increaseMinutes);
                _data.SubmitDataChange(pcStructure, DatabaseActionType.Update);
            }

            if (!(now >= pcStructure.DateNextActivity))
            {
                return(true);
            }

            // Time to spawn a new item and reset the timer.
            var    dbArea      = _data.Single <Area>(x => x.Resref == pcBase.AreaResref);
            string sector      = pcBase.Sector;
            int    lootTableID = 0;

            switch (sector)
            {
            case "NE": lootTableID = dbArea.NortheastLootTableID ?? 0; break;

            case "NW": lootTableID = dbArea.NorthwestLootTableID ?? 0; break;

            case "SE": lootTableID = dbArea.SoutheastLootTableID ?? 0; break;

            case "SW": lootTableID = dbArea.SouthwestLootTableID ?? 0; break;
            }

            if (lootTableID <= 0)
            {
                Console.WriteLine("WARNING: Loot table ID not defined for area " + dbArea.Name + ". Drills cannot retrieve items.");
                return(false);
            }

            pcStructure.DateNextActivity = now.AddMinutes(increaseMinutes);

            var controlTower = _base.GetBaseControlTower(pcStructure.PCBaseID);
            var itemDetails  = _loot.PickRandomItemFromLootTable(lootTableID);

            var    tempStorage = _.GetObjectByTag("TEMP_ITEM_STORAGE");
            NWItem item        = _.CreateItemOnObject(itemDetails.Resref, tempStorage, itemDetails.Quantity);

            // Guard against invalid resrefs and missing items.
            if (!item.IsValid)
            {
                Console.WriteLine("ERROR: Could not create base drill item with resref '" + itemDetails.Resref + "'. Is this item valid?");
                return(false);
            }

            if (!string.IsNullOrWhiteSpace(itemDetails.SpawnRule))
            {
                App.ResolveByInterface <ISpawnRule>("SpawnRule." + itemDetails.SpawnRule, action =>
                {
                    action.Run(item, retrievalRating);
                });
            }

            var dbItem = new PCBaseStructureItem
            {
                PCBaseStructureID = controlTower.ID,
                ItemGlobalID      = item.GlobalID.ToString(),
                ItemName          = item.Name,
                ItemResref        = item.Resref,
                ItemTag           = item.Tag,
                ItemObject        = _serialization.Serialize(item)
            };

            _data.SubmitDataChange(pcStructure, DatabaseActionType.Update);
            _data.SubmitDataChange(dbItem, DatabaseActionType.Insert);
            item.Destroy();
            return(true);
        }
Exemple #4
0
        public NWPlaceable SpawnStructure(NWArea area, Guid pcBaseStructureID)
        {
            PCBaseStructure pcStructure = _data.Get <PCBaseStructure>(pcBaseStructureID);

            NWLocation location = _.Location(area.Object,
                                             _.Vector((float)pcStructure.LocationX, (float)pcStructure.LocationY, (float)pcStructure.LocationZ),
                                             (float)pcStructure.LocationOrientation);

            BaseStructure     baseStructure = _data.Get <BaseStructure>(pcStructure.BaseStructureID);
            BaseStructureType structureType = (BaseStructureType)baseStructure.BaseStructureTypeID;
            string            resref        = baseStructure.PlaceableResref;
            var exteriorStyle = pcStructure.ExteriorStyleID == null ? null : _data.Get <BuildingStyle>(pcStructure.ExteriorStyleID);

            List <AreaStructure> areaStructures = area.Data["BASE_SERVICE_STRUCTURES"];

            if (string.IsNullOrWhiteSpace(resref) &&
                structureType == BaseStructureType.Building)
            {
                resref = exteriorStyle.Resref;
            }

            NWPlaceable plc = (_.CreateObject(OBJECT_TYPE_PLACEABLE, resref, location));

            plc.SetLocalString("PC_BASE_STRUCTURE_ID", pcStructure.ID.ToString());
            plc.SetLocalInt("REQUIRES_BASE_POWER", baseStructure.RequiresBasePower ? 1 : 0);
            plc.SetLocalString("ORIGINAL_SCRIPT_CLOSED", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_CLOSED));
            plc.SetLocalString("ORIGINAL_SCRIPT_DAMAGED", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_DAMAGED));
            plc.SetLocalString("ORIGINAL_SCRIPT_DEATH", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_DEATH));
            plc.SetLocalString("ORIGINAL_SCRIPT_HEARTBEAT", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_HEARTBEAT));
            plc.SetLocalString("ORIGINAL_SCRIPT_INVENTORYDISTURBED", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_INVENTORYDISTURBED));
            plc.SetLocalString("ORIGINAL_SCRIPT_LOCK", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_LOCK));
            plc.SetLocalString("ORIGINAL_SCRIPT_MELEEATTACKED", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_MELEEATTACKED));
            plc.SetLocalString("ORIGINAL_SCRIPT_OPEN", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_OPEN));
            plc.SetLocalString("ORIGINAL_SCRIPT_SPELLCASTAT", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_SPELLCASTAT));
            plc.SetLocalString("ORIGINAL_SCRIPT_UNLOCK", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_UNLOCK));
            plc.SetLocalString("ORIGINAL_SCRIPT_USED", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_USED));
            plc.SetLocalString("ORIGINAL_SCRIPT_USER_DEFINED_EVENT", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_USER_DEFINED_EVENT));
            plc.SetLocalString("ORIGINAL_SCRIPT_LEFT_CLICK", _.GetEventScript(plc.Object, EVENT_SCRIPT_PLACEABLE_ON_LEFT_CLICK));
            plc.SetLocalString("ORIGINAL_JAVA_SCRIPT_1", _.GetLocalString(plc.Object, "JAVA_SCRIPT_1"));

            if (!string.IsNullOrWhiteSpace(pcStructure.CustomName))
            {
                plc.Name = pcStructure.CustomName;
            }

            NWPlaceable door = null;

            if (structureType == BaseStructureType.Building)
            {
                door = SpawnBuildingDoor(exteriorStyle.DoorRule, plc);
                areaStructures.Add(new AreaStructure(pcStructure.PCBaseID, pcStructure.ID, door, false, null));
            }
            areaStructures.Add(new AreaStructure(pcStructure.PCBaseID, pcStructure.ID, plc, true, door));

            if (area.IsInstance && !string.IsNullOrWhiteSpace(area.GetLocalString("PC_BASE_STRUCTURE_ID")))
            {
                PCBase pcBase = _data.Get <PCBase>(pcStructure.PCBaseID);
                if (DateTime.UtcNow > pcBase.DateFuelEnds && pcBase.Fuel <= 0)
                {
                    ToggleInstanceObjectPower(area, false);
                }
            }

            return(plc);
        }
Exemple #5
0
        public bool Run(params object[] args)
        {
            NWPlaceable     drill         = Object.OBJECT_SELF;
            int             structureID   = drill.GetLocalInt("PC_BASE_STRUCTURE_ID");
            PCBaseStructure structure     = _data.Get <PCBaseStructure>(structureID);
            PCBase          pcBase        = _data.Get <PCBase>(structure.PCBaseID);
            BaseStructure   baseStructure = _data.Get <BaseStructure>(structure.BaseStructureID);
            DateTime        now           = DateTime.UtcNow;

            if (now >= pcBase.DateFuelEnds)
            {
                var outOfPowerEffect = drill.Effects.SingleOrDefault(x => _.GetEffectTag(x) == "CONTROL_TOWER_OUT_OF_POWER");
                if (outOfPowerEffect == null)
                {
                    outOfPowerEffect = _.EffectVisualEffect(VFX_DUR_AURA_RED);
                    outOfPowerEffect = _.TagEffect(outOfPowerEffect, "CONTROL_TOWER_OUT_OF_POWER");
                    _.ApplyEffectToObject(DURATION_TYPE_PERMANENT, outOfPowerEffect, drill);
                }

                return(true);
            }

            int minuteReduce    = 2 * structure.StructureBonus;
            int increaseMinutes = 60 - minuteReduce;
            int retrievalRating = baseStructure.RetrievalRating;

            if (increaseMinutes <= 20)
            {
                increaseMinutes = 20;
            }
            if (structure.DateNextActivity == null)
            {
                structure.DateNextActivity = now.AddMinutes(increaseMinutes);
                _data.SubmitDataChange(structure, DatabaseActionType.Update);
            }

            if (!(now >= structure.DateNextActivity))
            {
                return(true);
            }

            // Time to spawn a new item and reset the timer.
            var    dbArea      = _data.Single <Area>(x => x.Resref == pcBase.AreaResref);
            string sector      = pcBase.Sector;
            int    lootTableID = 0;

            switch (sector)
            {
            case "NE": lootTableID = dbArea.NortheastLootTableID ?? 0; break;

            case "NW": lootTableID = dbArea.NorthwestLootTableID ?? 0; break;

            case "SE": lootTableID = dbArea.SoutheastLootTableID ?? 0; break;

            case "SW": lootTableID = dbArea.SouthwestLootTableID ?? 0; break;
            }

            if (lootTableID <= 0)
            {
                Console.WriteLine("WARNING: Loot table ID not defined for area " + dbArea.Name + ". Drills cannot retrieve items.");
                return(false);
            }

            structure.DateNextActivity = now.AddMinutes(increaseMinutes);

            var controlTower = _base.GetBaseControlTower(structure.PCBaseID);
            var itemDetails  = _loot.PickRandomItemFromLootTable(lootTableID);

            var    tempStorage = _.GetObjectByTag("TEMP_ITEM_STORAGE");
            NWItem item        = _.CreateItemOnObject(itemDetails.Resref, tempStorage, itemDetails.Quantity);

            if (!string.IsNullOrWhiteSpace(itemDetails.SpawnRule))
            {
                App.ResolveByInterface <ISpawnRule>("SpawnRule." + itemDetails.SpawnRule, action =>
                {
                    action.Run(item, retrievalRating);
                });
            }

            var dbItem = new PCBaseStructureItem
            {
                PCBaseStructureID = controlTower.ID,
                ItemGlobalID      = item.GlobalID.ToString(),
                ItemName          = item.Name,
                ItemResref        = item.Resref,
                ItemTag           = item.Tag,
                ItemObject        = _serialization.Serialize(item)
            };

            _data.SubmitDataChange(structure, DatabaseActionType.Update);
            _data.SubmitDataChange(dbItem, DatabaseActionType.Insert);
            item.Destroy();
            return(true);
        }
Exemple #6
0
        public override void Initialize()
        {
            Guid            structureID = new Guid(GetDialogTarget().GetLocalString("PC_BASE_STRUCTURE_ID"));
            PCBaseStructure structure   = DataService.PCBaseStructure.GetByID(structureID);
            Guid            pcBaseID    = structure.PCBaseID;
            PCBase          pcBase      = DataService.PCBase.GetByID(pcBaseID);

            double currentCPU   = BaseService.GetCPUInUse(pcBaseID);
            double currentPower = BaseService.GetPowerInUse(pcBaseID);
            double maxCPU       = BaseService.GetMaxBaseCPU(pcBaseID);
            double maxPower     = BaseService.GetMaxBasePower(pcBaseID);

            int currentReinforcedFuel = pcBase.ReinforcedFuel;
            int currentFuel           = pcBase.Fuel;
            int currentResources      = DataService.PCBaseStructureItem.GetNumberOfItemsContainedBy(structure.ID);
            int maxReinforcedFuel     = BaseService.CalculateMaxReinforcedFuel(pcBaseID);
            int maxFuel      = BaseService.CalculateMaxFuel(pcBaseID);
            int maxResources = BaseService.CalculateResourceCapacity(pcBaseID);

            string time;

            if (pcBase.DateFuelEnds > DateTime.UtcNow)
            {
                TimeSpan deltaTime = pcBase.DateFuelEnds - DateTime.UtcNow;

                var tower = BaseService.GetBaseControlTower(pcBaseID);

                if (tower == null)
                {
                    Console.WriteLine("Could not locate control tower in ControlTower -> Initialize. PCBaseID = " + pcBaseID);
                    return;
                }

                var towerStructure = DataService.BaseStructure.GetByID(tower.BaseStructureID);
                int fuelRating     = towerStructure.FuelRating;
                int minutes;

                switch (fuelRating)
                {
                case 1:     // Small
                    minutes = 45;
                    break;

                case 2:     // Medium
                    minutes = 15;
                    break;

                case 3:     // Large
                    minutes = 5;
                    break;

                default:
                    throw new Exception("Invalid fuel rating value: " + fuelRating);
                }

                TimeSpan timeSpan = TimeSpan.FromMinutes(minutes * currentFuel) + deltaTime;
                time = TimeService.GetTimeLongIntervals(timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, false);

                time = "Fuel will expire in " + time;
            }
            else
            {
                time = ColorTokenService.Red("Fuel has expired.");
            }



            string header = ColorTokenService.Green("Power: ") + currentPower + " / " + maxPower + "\n";

            header += ColorTokenService.Green("CPU: ") + currentCPU + " / " + maxCPU + "\n";
            header += ColorTokenService.Green("Fuel: ") + currentFuel + " / " + maxFuel + "\n";
            header += ColorTokenService.Green("Reinforced Fuel: ") + currentReinforcedFuel + " / " + maxReinforcedFuel + "\n";
            header += ColorTokenService.Green("Resource Bay: ") + currentResources + " / " + maxResources + "\n";
            header += time + "\n";
            header += "What would you like to do with this control tower?";

            SetPageHeader("MainPage", header);

            if (!BasePermissionService.HasBasePermission(GetPC(), structure.PCBaseID, BasePermission.CanManageBaseFuel))
            {
                SetResponseVisible("MainPage", 1, false);
                SetResponseVisible("MainPage", 2, false);
            }

            if (!BasePermissionService.HasBasePermission(GetPC(), structure.PCBaseID, BasePermission.CanAccessStructureInventory))
            {
                SetResponseVisible("MainPage", 3, false);
            }
        }
Exemple #7
0
        public override PlayerDialog SetUp(NWPlayer player)
        {
            PlayerDialog dialog = new PlayerDialog("MainPage");

            string structureID = _.GetLocalString(_.GetArea(player), "PC_BASE_STRUCTURE_ID");

            if (string.IsNullOrWhiteSpace(structureID))
            {
                player.SendMessage("Base structure ID not found on area.  Please report this problem.");
                return(null);
            }

            Guid            pcBaseStructureID = new Guid(structureID);
            PCBaseStructure structure         = DataService.PCBaseStructure.GetByID(pcBaseStructureID);
            PCBase          pcBase            = DataService.PCBase.GetByID(structure.PCBaseID);

            bool bSpace = SpaceService.IsLocationSpace(pcBase.ShipLocation);

            List <string> options = new List <string>();

            if (bSpace && BasePermissionService.HasStructurePermission(player, structure.ID, StructurePermission.CanFlyStarship))
            {
                // See if we are near enough to the planet to land.
                if (SpaceService.CanLandOnPlanet(player.Area))
                {
                    options.Add("Land");
                }

                options.Add("Pilot Ship");
                options.Add("Hyperspace Jump");
            }
            else if (BasePermissionService.HasStructurePermission(player, structure.ID, StructurePermission.CanFlyStarship))
            {
                options.Add("Take Off");
            }

            if (!bSpace && BasePermissionService.HasBasePermission(player, structure.PCBaseID, BasePermission.CanManageBaseFuel))
            {
                options.Add("Access Fuel Bay");
                options.Add("Access Stronidium Bay");
            }

            if (BasePermissionService.HasBasePermission(player, structure.PCBaseID, BasePermission.CanAccessStructureInventory))
            {
                if (!bSpace)
                {
                    options.Add("Access Resource Bay");
                }
                options.Add("Export Starcharts");
            }

            DialogPage mainPage = new DialogPage("", options.ToArray());

            dialog.AddPage("MainPage", mainPage);

            // Hyperspace destinations.
            string[]   responses       = SpaceService.GetHyperspaceDestinationList(pcBase);
            DialogPage destinationPage = new DialogPage("Please select a destination to fly to.", responses);

            dialog.AddPage("HyperDestPage", destinationPage);

            // Landing destinations.
            Hashtable     landingspots = SpaceService.GetLandingDestinationList(player, pcBase);
            List <String> responseList = landingspots.Keys.Cast <String>().ToList();
            DialogPage    landingPage  = new DialogPage("Where do you want to land?", responseList.ToArray());

            dialog.AddPage("LandingDestPage", landingPage);

            // Save off the landing responses in CustomData.  This ensures we can access the structure IDs later.
            foreach (var key in landingspots.Keys)
            {
                dialog.CustomData.Add("LAND_" + key, landingspots[key]);
            }

            return(dialog);
        }
        private void DoRetrieveStructure()
        {
            var               data           = _base.GetPlayerTempData(GetPC());
            PCBaseStructure   structure      = _data.Get <PCBaseStructure>(data.ManipulatingStructure.PCBaseStructureID);
            BaseStructure     baseStructure  = _data.Get <BaseStructure>(structure.BaseStructureID);
            PCBase            pcBase         = _data.Get <PCBase>(structure.PCBaseID);
            BaseStructureType structureType  = (BaseStructureType)baseStructure.BaseStructureTypeID;
            var               tempStorage    = _.GetObjectByTag("TEMP_ITEM_STORAGE");
            var               pcStructureID  = structure.ID;
            int               impoundedCount = 0;

            var controlTower = _base.GetBaseControlTower(pcBase.ID);
            int maxShields   = _base.CalculateMaxShieldHP(controlTower);

            if (pcBase.ShieldHP < maxShields && structureType != BaseStructureType.ControlTower)
            {
                GetPC().FloatingText("You cannot retrieve any structures because the control tower has less than 100% shields.");
                return;
            }

            bool canRetrieveStructures;

            if (data.BuildingType == Enumeration.BuildingType.Exterior ||
                data.BuildingType == Enumeration.BuildingType.Apartment)
            {
                canRetrieveStructures = _perm.HasBasePermission(GetPC(), data.ManipulatingStructure.PCBaseID, BasePermission.CanRetrieveStructures);
            }
            else if (data.BuildingType == Enumeration.BuildingType.Interior)
            {
                var structureID = new Guid(data.ManipulatingStructure.Structure.Area.GetLocalString("PC_BASE_STRUCTURE_ID"));
                canRetrieveStructures = _perm.HasStructurePermission(GetPC(), structureID, StructurePermission.CanRetrieveStructures);
            }
            else
            {
                throw new Exception("BaseManagementTool -> DoRetrieveStructure: Cannot handle building type " + data.BuildingType);
            }

            if (!canRetrieveStructures)
            {
                GetPC().FloatingText("You don't have permission to retrieve structures.");
                return;
            }


            if (structureType == BaseStructureType.ControlTower)
            {
                var structureCount = _data.GetAll <PCBaseStructure>().Count(x => x.PCBaseID == structure.PCBaseID);

                if (structureCount > 1)
                {
                    GetPC().FloatingText("You must remove all structures in this sector before picking up the control tower.");
                    return;
                }

                // Impound resources retrieved by drills.
                var items = _data.Where <PCBaseStructureItem>(x => x.PCBaseStructureID == structure.ID).ToList();
                foreach (var item in items)
                {
                    _impound.Impound(item);
                    _data.SubmitDataChange(item, DatabaseActionType.Delete);
                    impoundedCount++;
                }
            }
            else if (structureType == BaseStructureType.Building)
            {
                var childStructures = _data.Where <PCBaseStructure>(x => x.ParentPCBaseStructureID == structure.ID).ToList();
                for (int x = childStructures.Count - 1; x >= 0; x--)
                {
                    var    furniture     = childStructures.ElementAt(x);
                    NWItem furnitureItem = _base.ConvertStructureToItem(furniture, tempStorage);
                    _impound.Impound(GetPC().GlobalID, furnitureItem);
                    furnitureItem.Destroy();

                    _data.SubmitDataChange(furniture, DatabaseActionType.Delete);
                    impoundedCount++;
                }

                var primaryOwner = _data.SingleOrDefault <Player>(x => x.PrimaryResidencePCBaseStructureID == structure.ID);
                if (primaryOwner != null)
                {
                    primaryOwner.PrimaryResidencePCBaseStructureID = null;
                    _data.SubmitDataChange(primaryOwner, DatabaseActionType.Update);
                }
            }


            _base.ConvertStructureToItem(structure, GetPC());
            _data.SubmitDataChange(structure, DatabaseActionType.Delete);
            data.ManipulatingStructure.Structure.Destroy();

            // Impound any fuel that's over the limit.
            if (structureType == BaseStructureType.StronidiumSilo || structureType == BaseStructureType.FuelSilo)
            {
                int maxFuel           = _base.CalculateMaxFuel(pcBase.ID);
                int maxReinforcedFuel = _base.CalculateMaxReinforcedFuel(pcBase.ID);

                if (pcBase.Fuel > maxFuel)
                {
                    int    returnAmount = pcBase.Fuel - maxFuel;
                    NWItem refund       = _.CreateItemOnObject("fuel_cell", tempStorage, returnAmount);
                    pcBase.Fuel = maxFuel;
                    _impound.Impound(pcBase.PlayerID, refund);
                    GetPC().SendMessage("Excess fuel cells have been impounded by the planetary government. The owner of the base will need to retrieve it.");
                    refund.Destroy();
                }

                if (pcBase.ReinforcedFuel > maxReinforcedFuel)
                {
                    int    returnAmount = pcBase.ReinforcedFuel - maxReinforcedFuel;
                    NWItem refund       = _.CreateItemOnObject("stronidium", tempStorage, returnAmount);
                    pcBase.ReinforcedFuel = maxReinforcedFuel;
                    _impound.Impound(pcBase.PlayerID, refund);
                    GetPC().SendMessage("Excess stronidium units have been impounded by the planetary government. The owner of the base will need to retrieve it.");
                    refund.Destroy();
                }
            }
            else if (structureType == BaseStructureType.ResourceSilo)
            {
                int maxResources = _base.CalculateResourceCapacity(pcBase.ID);
                var items        = _data.Where <PCBaseStructureItem>(x => x.PCBaseStructureID == controlTower.ID).ToList();

                while (items.Count > maxResources)
                {
                    var item = items.ElementAt(0);

                    var impoundItem = new PCImpoundedItem
                    {
                        PlayerID      = pcBase.PlayerID,
                        ItemResref    = item.ItemResref,
                        ItemObject    = item.ItemObject,
                        DateImpounded = DateTime.UtcNow,
                        ItemName      = item.ItemName,
                        ItemTag       = item.ItemTag
                    };

                    _data.SubmitDataChange(impoundItem, DatabaseActionType.Insert);
                    GetPC().SendMessage(item.ItemName + " has been impounded by the planetary government because your base ran out of space to store resources. The owner of the base will need to retrieve it.");
                    _data.SubmitDataChange(item, DatabaseActionType.Delete);
                }
            }

            // Update the cache
            List <AreaStructure> areaStructures = data.TargetArea.Data["BASE_SERVICE_STRUCTURES"];
            var records = areaStructures.Where(x => x.PCBaseStructureID == pcStructureID).ToList();

            for (int x = records.Count() - 1; x >= 0; x--)
            {
                var record = records[x];
                record.ChildStructure?.Destroy();
                areaStructures.Remove(record);
            }

            EndConversation();

            if (impoundedCount > 0)
            {
                GetPC().FloatingText(impoundedCount + " item(s) were sent to the planetary impound.");
            }
        }
Exemple #9
0
        public override void DoAction(NWPlayer player, string pageName, int responseID)
        {
            PlayerDialog    dialog      = DialogService.LoadPlayerDialog(GetPC().GlobalID);
            Guid            structureID = new Guid(_.GetLocalString(player.Area, "PC_BASE_STRUCTURE_ID"));
            PCBaseStructure structure   = DataService.PCBaseStructure.GetByID(structureID);
            PCBase          pcBase      = DataService.PCBase.GetByID(structure.PCBaseID);

            DialogPage     page     = dialog.GetPageByName(pageName);
            DialogResponse response = page.Responses[responseID - 1];

            bool carefulPilot = PerkService.GetCreaturePerkLevel(player, PerkType.CarefulPilot) > 0;

            if (pageName == "MainPage")
            {
                // The number of dialog options available can vary.  So query based on the actual text of the response.
                if (response.Text == "Land")
                {
                    ChangePage("LandingDestPage");
                }
                else if (response.Text == "Pilot Ship")
                {
                    SpaceService.CreateShipInSpace(player.Area); // In case we logged in here.
                    SpaceService.DoFlyShip(GetPC(), GetPC().Area);
                    EndConversation();
                }
                else if (response.Text == "Hyperspace Jump")
                {
                    // Build the list of destinations.
                    ChangePage("HyperDestPage");
                }
                else if (response.Text == "Take Off")
                {
                    // Check fuel
                    if (pcBase.Fuel < 1)
                    {
                        GetPC().SendMessage("You don't have enough fuel! You need 1 fuel to take off.");
                        dialog.ResetPage();
                    }
                    else
                    {
                        // Fuel is good - we have liftoff.
                        if (!SpaceService.DoPilotingSkillCheck(GetPC(), 2, carefulPilot))
                        {
                            // Failed our skill check.  Deduct fuel but don't do anything else.
                            GetPC().FloatingText("The ship shudders a bit, but your awkwardness on the throttle shows, and it doesn't make it off the dock.  Try again.");
                            pcBase.Fuel -= 1;
                            DataService.SubmitDataChange(pcBase, DatabaseActionType.Update);
                            return;
                        }

                        EndConversation();

                        // Save details of the current dock for later.
                        Guid            shipPCBaseID = new Guid(pcBase.ShipLocation);
                        PCBaseStructure dock         = DataService.PCBaseStructure.GetByIDOrDefault(shipPCBaseID);

                        pcBase.Fuel        -= 1;
                        pcBase.DateRentDue  = DateTime.UtcNow.AddDays(99);
                        pcBase.ShipLocation = SpaceService.GetPlanetFromLocation(pcBase.ShipLocation) + " - Orbit";
                        DataService.SubmitDataChange(pcBase, DatabaseActionType.Update);

                        SpaceService.CreateShipInSpace(player.Area);

                        // Give the impression of movement
                        foreach (var creature in player.Area.Objects)
                        {
                            if (creature.IsPC || creature.IsDM)
                            {
                                _.FloatingTextStringOnCreature("The ship is taking off", creature);
                            }
                        }

                        _.ApplyEffectToObject(DurationType.Instant, _.EffectVisualEffect(VisualEffect.Vfx_Fnf_Screen_Shake), player);

                        // Clean up the base structure, if we were in a PC dock not public starport.
                        // Get a reference to our placeable (and door), and delete them with some VFX.
                        if (dock != null)
                        {
                            PCBase dockBase = DataService.PCBase.GetByID(dock.PCBaseID);

                            IEnumerable <NWArea> areas = NWModule.Get().Areas;
                            NWArea landingArea         = new NWArea(_.GetFirstArea());

                            foreach (var area in areas)
                            {
                                if (_.GetResRef(area) == dockBase.AreaResref)
                                {
                                    landingArea = area;
                                }
                            }

                            List <AreaStructure> areaStructures = landingArea.Data["BASE_SERVICE_STRUCTURES"];
                            foreach (var plc in areaStructures)
                            {
                                if (plc.PCBaseStructureID == dock.ID)
                                {
                                    // Found our dock.  Clear its variable and play some VFX.
                                    plc.Structure.SetLocalInt("DOCKED_STARSHIP", 0);
                                    DoDustClouds(plc.Structure.Location);
                                    _.ApplyEffectToObject(DurationType.Instant, _.EffectVisualEffect(VisualEffect.Vfx_Fnf_Screen_Shake), plc.Structure);
                                }
                                else if (plc.PCBaseStructureID == structure.ID)
                                {
                                    // found either our ship or our entrance (both are saved with our structure ID).  Delete them.
                                    // Dp NOT remove the PC base structure object from the database.  We still need that.
                                    plc.Structure.Destroy();
                                }
                            }
                        }
                    }
                }
                else if (response.Text == "Access Fuel Bay")
                {
                    OpenFuelBay(false);
                    EndConversation();
                }
                else if (response.Text == "Access Stronidium Bay")
                {
                    OpenFuelBay(true);
                    EndConversation();
                }
                else if (response.Text == "Access Resource Bay")
                {
                    NWPlaceable bay = SpaceService.GetCargoBay(player.Area, GetPC());
                    if (bay != null)
                    {
                        GetPC().AssignCommand(() => _.ActionInteractObject(bay.Object));
                    }
                    EndConversation();
                }
                else if (response.Text == "Export Starcharts")
                {
                    NWItem item = _.CreateItemOnObject("starcharts", player, 1, _.Random(10000).ToString());

                    // Initialise the list, in case it hasn't been populated yet.
                    SpaceService.GetHyperspaceDestinationList(pcBase);

                    item.SetLocalInt("Starcharts", (int)pcBase.Starcharts);
                }
            }
            else if (pageName == "HyperDestPage")
            {
                // Check fuel
                if (pcBase.Fuel < 50)
                {
                    GetPC().SendMessage("You don't have enough fuel! You need 50 fuel to make a hyperspace jump.");
                    dialog.ResetPage();
                }
                else
                {
                    // Fuel is good - make the jump
                    if (!SpaceService.DoPilotingSkillCheck(GetPC(), 13, carefulPilot))
                    {
                        // Failed our skill check.  Deduct fuel but don't do anything else.
                        GetPC().FloatingText("Jump failed!  You forgot to whatsit the thingummyjig.");
                        pcBase.Fuel -= 50;
                        DataService.SubmitDataChange(pcBase, DatabaseActionType.Update);
                        EndConversation();
                        return;
                    }

                    // Move the ship out of the old orbit.
                    SpaceService.RemoveShipInSpace(player.Area);

                    // Fade to black for hyperspace.
                    EndConversation();
                    pcBase.Fuel        -= 50;
                    pcBase.ShipLocation = response.Text + " - Orbit";
                    DataService.SubmitDataChange(pcBase, DatabaseActionType.Update);

                    // Put the ship in its new orbit.
                    SpaceService.CreateShipInSpace(player.Area);

                    // Give the impression of movement - would be great to have the actual hyperspace jump graphics here.
                    foreach (var creature in player.Area.Objects)
                    {
                        if (creature.IsPC || creature.IsDM)
                        {
                            _.FloatingTextStringOnCreature("Making a hyperspace jump!", creature);
                            _.FadeToBlack(creature, 0.5f);
                            _.DelayCommand(1.0f, () => { _.FadeFromBlack(creature, 0.5f); });
                        }
                    }
                }
            }
            else if (pageName == "LandingDestPage")
            {
                // Skill check.
                if (!SpaceService.DoPilotingSkillCheck(GetPC(), 5, carefulPilot))
                {
                    // Failed our skill check.  Land anyway but burn more fuel.
                    if (pcBase.Fuel > 0)
                    {
                        GetPC().FloatingText("You overshoot the landing spot, burning extra fuel getting your ship into position.");
                        pcBase.Fuel -= 1;
                        DataService.SubmitDataChange(pcBase, DatabaseActionType.Update);
                    }
                }

                // Get the response, then find the structure ID.
                Guid dockStructureID = dialog.CustomData["LAND_" + response.Text];

                // This could be a public startport ID or a private dock base structure ID.
                Starport starport = DataService.Starport.GetByStarportIDOrDefault(dockStructureID);
                if (starport != null)
                {
                    // We have a public starport.
                    if (player.Gold < starport.Cost)
                    {
                        player.SendMessage("You do not have enough credits to land here.");
                        return;
                    }
                    else
                    {
                        _.TakeGoldFromCreature(starport.Cost, player, true);

                        // Land.
                        pcBase.ShipLocation = starport.StarportID.ToString();
                        pcBase.DateRentDue  = DateTime.UtcNow.AddDays(1);
                        DataService.SubmitDataChange(pcBase, DatabaseActionType.Update);

                        // Notify PC.
                        player.SendMessage("You have paid your first day's berthing fees. Use the Base Management System to extend your lease if you plan to stay longer, or your ship will be impounded.");

                        EndConversation();
                    }
                }
                else
                {
                    LoggingService.Trace(TraceComponent.Space, "Landing in PC base dock, ID: " + dockStructureID.ToString());
                    PCBaseStructure dock = DataService.PCBaseStructure.GetByIDOrDefault(dockStructureID);

                    if (dock == null)
                    {
                        player.SendMessage("ERROR: Could not find landing dock by ID.  Please report this.");
                        LoggingService.Trace(TraceComponent.Space, "Could not find landing dock ID " + dockStructureID.ToString());
                        return;
                    }

                    NWPlaceable plc = BaseService.FindPlaceableFromStructureID(dock.ID.ToString());

                    if (plc == null)
                    {
                        LoggingService.Trace(TraceComponent.Space, "Failed to find dock placeable.");
                        player.SendMessage("ERROR: Could not find landing dock placeable.  Please report this.");
                        return;
                    }

                    LoggingService.Trace(TraceComponent.Space, "Found dock, landing ship.");

                    // We've found our dock. Update our record of where the ship's exterior should spawn.
                    NWLocation loc = plc.Location;

                    structure.LocationX           = loc.X;
                    structure.LocationY           = loc.Y;
                    structure.LocationZ           = loc.Z;
                    structure.LocationOrientation = _.GetFacingFromLocation(loc);

                    DataService.SubmitDataChange(structure, DatabaseActionType.Update);

                    // And update the base to mark the parent dock as the location.
                    pcBase.ShipLocation = dock.ID.ToString();
                    DataService.SubmitDataChange(pcBase, DatabaseActionType.Update);

                    // Now use the Base Service to spawn the ship exterior.
                    BaseService.SpawnStructure(plc.Area, structure.ID);

                    // Mark the dock as occupied.
                    plc.SetLocalInt("DOCKED_STARSHIP", 1);

                    // Notify PCs in the landing area.
                    foreach (var creature in plc.Area.Objects)
                    {
                        if (creature.IsPC || creature.IsDM)
                        {
                            _.FloatingTextStringOnCreature("A ship has just landed!", creature);
                        }
                    }

                    // And shake the screen, because stuff.
                    _.ApplyEffectAtLocation(DurationType.Instant, _.EffectVisualEffect(VisualEffect.Vfx_Fnf_Screen_Shake), loc);
                    DoDustClouds(loc);
                }

                // We're landing.  Make sure any pilot or gunner get out of flight mode.
                SpaceService.LandCrew(player.Area);

                // If we are still here, we landed successfully.  Shake the screen about and notify PCs on the ship.
                // Give the impression of movement
                foreach (var creature in player.Area.Objects)
                {
                    if (creature.IsPC || creature.IsDM)
                    {
                        _.FloatingTextStringOnCreature("The ship is landing.", creature);
                    }
                }

                _.ApplyEffectToObject(DurationType.Instant, _.EffectVisualEffect(VisualEffect.Vfx_Fnf_Screen_Shake), player);
                SpaceService.RemoveShipInSpace(player.Area);

                EndConversation();
            }
        }
Exemple #10
0
        public void Main()
        {
            NWCreature      attacker    = (_.GetLastDamager(NWGameObject.OBJECT_SELF));
            NWPlaceable     tower       = (NWGameObject.OBJECT_SELF);
            NWItem          weapon      = (_.GetLastWeaponUsed(attacker.Object));
            int             damage      = _.GetTotalDamageDealt();
            var             structureID = tower.GetLocalString("PC_BASE_STRUCTURE_ID");
            PCBaseStructure structure   = DataService.PCBaseStructure.GetByID(new Guid(structureID));
            int             maxShieldHP = BaseService.CalculateMaxShieldHP(structure);
            PCBase          pcBase      = DataService.PCBase.GetByID(structure.PCBaseID);
            var             playerIDs   = DataService.PCBasePermission.GetAllByHasPrivatePermissionToBase(structure.PCBaseID)
                                          .Select(s => s.PlayerID);
            var      toNotify = NWModule.Get().Players.Where(x => playerIDs.Contains(x.GlobalID));
            DateTime timer    = DateTime.UtcNow.AddSeconds(30);
            string   clock    = timer.ToString(CultureInfo.InvariantCulture);
            string   sector   = BaseService.GetSectorOfLocation(attacker.Location);

            if (DateTime.UtcNow <= DateTime.Parse(clock))
            {
                foreach (NWPlayer player in toNotify)
                {
                    player.SendMessage("Your base in " + attacker.Area.Name + " " + sector + " is under attack!");
                }
            }

            // Apply damage to the shields. Never fall below 0.
            pcBase.ShieldHP -= damage;
            if (pcBase.ShieldHP <= 0)
            {
                pcBase.ShieldHP = 0;
            }

            // Calculate the amount of shield percentage remaining. If the tower is in reinforced mode, HP
            // will always be set back to 25% of shields.
            float hpPercentage = (float)pcBase.ShieldHP / (float)maxShieldHP * 100.0f;

            if (hpPercentage <= 25.0f && pcBase.ReinforcedFuel > 0)
            {
                pcBase.IsInReinforcedMode = true;
                pcBase.ShieldHP           = (int)(maxShieldHP * 0.25f);
                hpPercentage = (float)pcBase.ShieldHP / (float)maxShieldHP * 100.0f;
            }

            // Notify the attacker.
            attacker.SendMessage("Tower Shields: " + hpPercentage.ToString("0.00") + "%");
            if (pcBase.IsInReinforcedMode)
            {
                attacker.SendMessage("Control tower is in reinforced mode and cannot be damaged. Reinforced mode will be disabled when the tower runs out of fuel.");
            }

            // HP is tracked in the database. Heal the placeable so it doesn't get destroyed.
            _.ApplyEffectToObject(_.DURATION_TYPE_INSTANT, _.EffectHeal(9999), tower.Object);

            if (attacker.IsPlayer)
            {
                DurabilityService.RunItemDecay(attacker.Object, weapon, RandomService.RandomFloat(0.01f, 0.03f));
            }

            // If the shields have fallen to zero, the tower will begin to take structure damage.
            if (pcBase.ShieldHP <= 0)
            {
                pcBase.ShieldHP = 0;

                structure.Durability -= RandomService.RandomFloat(0.5f, 2.0f);
                if (structure.Durability < 0.0f)
                {
                    structure.Durability = 0.0f;
                }
                attacker.SendMessage("Structure Durability: " + structure.Durability.ToString("0.00"));

                // If the structure durability drops to zero, destroy everything in the base.
                if (structure.Durability <= 0.0f)
                {
                    structure.Durability = 0.0f;
                    BaseService.ClearPCBaseByID(pcBase.ID, true, false);
                    MessageHub.Instance.Publish(new OnBaseDestroyed(pcBase, attacker));
                    return;
                }
            }

            DataService.SubmitDataChange(pcBase, DatabaseActionType.Update);
            DataService.SubmitDataChange(structure, DatabaseActionType.Update);
        }
Exemple #11
0
        public bool Run(params object[] args)
        {
            NWCreature      attacker    = (_.GetLastDamager(Object.OBJECT_SELF));
            NWPlaceable     tower       = (Object.OBJECT_SELF);
            NWItem          weapon      = (_.GetLastWeaponUsed(attacker.Object));
            int             damage      = _.GetTotalDamageDealt();
            var             structureID = tower.GetLocalString("PC_BASE_STRUCTURE_ID");
            PCBaseStructure structure   = _data.Single <PCBaseStructure>(x => x.ID == new Guid(structureID));
            int             maxShieldHP = _base.CalculateMaxShieldHP(structure);
            PCBase          pcBase      = _data.Get <PCBase>(structure.PCBaseID);
            var             playerIDs   = _data.Where <PCBasePermission>(x => x.PCBaseID == structure.PCBaseID &&
                                                                         !x.IsPublicPermission)
                                          .Select(s => s.PlayerID);
            var      toNotify = NWModule.Get().Players.Where(x => playerIDs.Contains(x.GlobalID));
            DateTime timer    = DateTime.UtcNow.AddSeconds(30);
            string   clock    = timer.ToString(CultureInfo.InvariantCulture);
            string   sector   = _base.GetSectorOfLocation(attacker.Location);

            if (DateTime.UtcNow <= DateTime.Parse(clock))
            {
                foreach (NWPlayer player in toNotify)
                {
                    player.SendMessage("Your base in " + attacker.Area.Name + " " + sector + " is under attack!");
                }
            }
            pcBase.ShieldHP -= damage;
            if (pcBase.ShieldHP <= 0)
            {
                pcBase.ShieldHP = 0;
            }
            float hpPercentage = (float)pcBase.ShieldHP / (float)maxShieldHP * 100.0f;

            if (hpPercentage <= 25.0f && pcBase.ReinforcedFuel > 0)
            {
                pcBase.IsInReinforcedMode = true;
                pcBase.ShieldHP           = (int)(maxShieldHP * 0.25f);
            }

            attacker.SendMessage("Tower Shields: " + hpPercentage.ToString("0.00") + "%");

            if (pcBase.IsInReinforcedMode)
            {
                attacker.SendMessage("Control tower is in reinforced mode and cannot be damaged. Reinforced mode will be disabled when the tower runs out of fuel.");
            }

            _.ApplyEffectToObject(DURATION_TYPE_INSTANT, _.EffectHeal(9999), tower.Object);

            var durability = _durability.GetDurability(weapon) - _random.RandomFloat(0.01f, 0.03f);

            _durability.SetDurability(weapon, durability);

            if (pcBase.ShieldHP <= 0)
            {
                pcBase.ShieldHP = 0;

                structure.Durability -= _random.RandomFloat(0.5f, 2.0f);
                if (structure.Durability < 0.0f)
                {
                    structure.Durability = 0.0f;
                }
                attacker.SendMessage("Structure Durability: " + structure.Durability.ToString("0.00"));

                if (structure.Durability <= 0.0f)
                {
                    structure.Durability = 0.0f;
                    BlowUpBase(pcBase);
                    return(true);
                }
            }

            _data.SubmitDataChange(pcBase, DatabaseActionType.Update);
            _data.SubmitDataChange(structure, DatabaseActionType.Update);
            return(true);
        }
Exemple #12
0
        private void BlowUpBase(PCBase pcBase)
        {
            NWArea area = (_.GetArea(Object.OBJECT_SELF));
            List <AreaStructure> cache = area.Data["BASE_SERVICE_STRUCTURES"];

            cache = cache.Where(x => x.PCBaseID == pcBase.ID).ToList();

            foreach (var structure in cache)
            {
                // Child structures will be picked up later on in the process.
                // Just destroy the structure and continue on.
                if (structure.ChildStructure != null)
                {
                    structure.Structure.Destroy();
                    continue;
                }

                var dbStructure   = _data.Get <PCBaseStructure>(structure.PCBaseStructureID);
                var baseStructure = _data.Get <BaseStructure>(dbStructure.BaseStructureID);
                var items         = _data.Where <PCBaseStructureItem>(x => x.PCBaseStructureID == structure.PCBaseStructureID).ToList();
                var children      = _data.Where <PCBaseStructure>(x => x.ParentPCBaseStructureID == dbStructure.ParentPCBaseStructureID).ToList();

                // Explosion effect
                Location location = structure.Structure.Location;
                _.ApplyEffectAtLocation(DURATION_TYPE_INSTANT, _.EffectVisualEffect(VFX_FNF_FIREBALL), location);

                // Boot from instance, if any
                _base.BootPlayersOutOfInstance(structure.PCBaseStructureID);

                // Spawn container for items
                NWPlaceable container = (_.CreateObject(OBJECT_TYPE_PLACEABLE, "structure_rubble", structure.Structure.Location));
                container.Name = baseStructure.Name + " Rubble";

                // Drop item storage into container
                for (int i = items.Count - 1; i >= 0; i--)
                {
                    var dbItem = items.ElementAt(i);
                    _serialization.DeserializeItem(dbItem.ItemObject, container);
                    _data.SubmitDataChange(dbItem, DatabaseActionType.Delete);
                }

                // Convert child placeables to items and drop into container
                for (int f = children.Count - 1; f >= 0; f--)
                {
                    var child      = children.ElementAt(f);
                    var childItems = _data.Where <PCBaseStructureItem>(x => x.PCBaseStructureID == child.ID).ToList();

                    // Move child items to container
                    for (int i = childItems.Count - 1; i >= 0; i++)
                    {
                        var dbItem = childItems.ElementAt(i);
                        _serialization.DeserializeItem(dbItem.ItemObject, container);
                        _data.SubmitDataChange(dbItem, DatabaseActionType.Delete);
                    }

                    // Convert child structure to item
                    _base.ConvertStructureToItem(child, container);
                    _data.SubmitDataChange(child, DatabaseActionType.Delete);
                }


                // Clear structure permissions
                var structurePermissions = _data.Where <PCBaseStructurePermission>(x => x.PCBaseStructureID == dbStructure.ID).ToList();
                for (int p = structurePermissions.Count - 1; p >= 0; p--)
                {
                    var permission = structurePermissions.ElementAt(p);
                    _data.SubmitDataChange(permission, DatabaseActionType.Delete);
                }

                // Destroy structure placeable
                _data.SubmitDataChange(dbStructure, DatabaseActionType.Delete);
                structure.Structure.Destroy();
            }

            // Remove from cache
            foreach (var record in cache)
            {
                ((List <AreaStructure>)area.Data["BASE_SERVICE_STRUCTURES"]).Remove(record);
            }
            var basePermissions = _data.Where <PCBasePermission>(x => x.PCBaseID == pcBase.ID).ToList();

            // Clear base permissions
            for (int p = basePermissions.Count - 1; p >= 0; p--)
            {
                var permission = basePermissions.ElementAt(p);
                _data.SubmitDataChange(permission, DatabaseActionType.Delete);
            }

            _data.SubmitDataChange(pcBase, DatabaseActionType.Delete);

            Area dbArea = _data.Single <Area>(x => x.Resref == pcBase.AreaResref);

            if (pcBase.Sector == AreaSector.Northeast)
            {
                dbArea.NortheastOwner = null;
            }
            else if (pcBase.Sector == AreaSector.Northwest)
            {
                dbArea.NorthwestOwner = null;
            }
            else if (pcBase.Sector == AreaSector.Southeast)
            {
                dbArea.SoutheastOwner = null;
            }
            else if (pcBase.Sector == AreaSector.Southwest)
            {
                dbArea.SouthwestOwner = null;
            }
        }
Exemple #13
0
 public OnBaseLeaseExpired(PCBase pcBase)
 {
     PCBase = pcBase;
 }