示例#1
0
        /// <summary>
        /// This function regresses crops
        /// </summary>
        /// <param name="loc">Location of the crop</param>
        /// <param name="h">Hoe Dirt of the crop</param>
        /// <param name="position">The position of the crop</param>
        /// <param name="numSteps">The number of steps the crop is being regressed by</param>
        /// <param name="giantCropRequiredSteps">The number of minimum steps to affect the giant crop (default: 4)</param>
        /// <param name="giantCropDestructionOdds">The chance of the giant crop being affected (default: 50%)</param>
        /// <exception cref="">Throws a generic exception if it finds a giant crop that doesn't have an actual crop backing.</exception>
        public static void DeAdvanceCrop(GameLocation loc, HoeDirt h, Vector2 position, int numSteps, IMonitor Logger, int giantCropRequiredSteps = 4, double giantCropDestructionOdds = .5)
        {
            //determine the phase of the crop
            Crop currentCrop = h.crop;

            //data on the crop. Outputting to debug.
            Logger.Log($"BEFORE CROP DEADVANCEMENT: {PrintCropData(loc, h, position)}", LogLevel.Debug);

            if (!(currentCrop is null))
            {
                int countPhases = currentCrop.phaseDays.Count;
                int finalPhase  = countPhases - 1;

                for (int i = 0; i < numSteps; i++)
                {
                    //now, check the phase - handle the final phase.
                    if (currentCrop.currentPhase.Value == finalPhase && currentCrop.regrowAfterHarvest.Value == -1)
                    {
                        if (currentCrop.dayOfCurrentPhase.Value > 0)
                        {
                            currentCrop.dayOfCurrentPhase.Value--;
                        }
                        else if (currentCrop.dayOfCurrentPhase.Value == 0)
                        {
                            currentCrop.fullyGrown.Value = false;
                            currentCrop.currentPhase.Value--;
                            currentCrop.dayOfCurrentPhase.Value = currentCrop.phaseDays[currentCrop.currentPhase.Value];
                        }
                        Logger.Log($"AFTER CROP DEADVANCEMENT: {PrintCropData(loc, h, position)}", LogLevel.Debug);
                        continue;
                    }

                    //handle regrowth crops.
                    if (currentCrop.regrowAfterHarvest.Value != -1 && currentCrop.currentPhase.Value == finalPhase)
                    {
                        currentCrop.dayOfCurrentPhase.Value++;
                        Logger.Log($"AFTER CROP DEADVANCEMENT: {PrintCropData(loc, h, position)}", LogLevel.Debug);
                        continue;
                    }

                    //now handle it being any phase but 0.
                    if (currentCrop.currentPhase.Value != finalPhase || currentCrop.currentPhase.Value != 0)
                    {
                        if (currentCrop.dayOfCurrentPhase.Value >= currentCrop.phaseDays[currentCrop.currentPhase.Value] && currentCrop.currentPhase.Value > 0)
                        {
                            currentCrop.currentPhase.Value--;
                            currentCrop.dayOfCurrentPhase.Value = currentCrop.phaseDays[currentCrop.currentPhase.Value];
                        }
                        else
                        {
                            currentCrop.dayOfCurrentPhase.Value++;
                        }
                        Logger.Log($"AFTER CROP DEADVANCEMENT: {PrintCropData(loc, h, position)}", LogLevel.Debug);
                        continue;
                    }

                    //final check. Phase 0.
                    if (currentCrop.currentPhase.Value == 0)
                    {
                        if (currentCrop.dayOfCurrentPhase.Value != 0 && currentCrop.dayOfCurrentPhase.Value > 0)
                        {
                            currentCrop.dayOfCurrentPhase.Value--;
                        }
                        Logger.Log($"AFTER CROP DEADVANCEMENT: {PrintCropData(loc, h, position)}", LogLevel.Debug);
                        continue;
                    }

                    //Sanity check here.
                    if (currentCrop.currentPhase.Value < 0)
                    {
                        currentCrop.currentPhase.Value = 0;
                    }
                }
            }

            //check for giant crop.
            if (loc is Farm f)
            {
                foreach (ResourceClump rc in f.resourceClumps)
                {
                    if (rc is GiantCrop gc && CheckIfPositionIsWithinGiantCrop(position, gc))
                    {
                        //This breaks my heart, given the requirements...
                        if (numSteps > giantCropRequiredSteps && Game1.random.NextDouble() < giantCropDestructionOdds)
                        {
                            numSteps -= giantCropRequiredSteps;
                            Vector2 upperLeft = gc.tile.Value;
                            int     cropReplacement = gc.parentSheetIndex.Value, width = gc.width.Value, height = gc.height.Value;

                            int?cropSeed = GetCropForSheetIndex(cropReplacement);
                            if (cropSeed == null)
                            {
                                throw new Exception($"Somehow, this giant crop has no valid seed from it's stored parent index. This needs to be troubleshooted. Parent seed index is {cropReplacement}");
                            }

                            f.resourceClumps.Remove(gc);
                            for (int i = 0; i < width; i++)
                            {
                                for (int j = 0; j < height; j++)
                                {
                                    Vector2 currPos = new Vector2(upperLeft.X + i, upperLeft.Y + i);
                                    HoeDirt hd      = new HoeDirt(1)
                                    {
                                        crop = new Crop((int)cropSeed, (int)currPos.X, (int)currPos.Y)
                                    };
                                    hd.crop.growCompletely();
                                    loc.terrainFeatures.Add(currPos, hd);
                                }
                            }
                        }
                    }
                }
            }
            Logger.Log($"AFTER CROP DEADVANCEMENT: {PrintCropData(loc, h, position)}", LogLevel.Debug);
            //we aren't handling forage crops here.
        }
示例#2
0
        public static int CreateWeeds(GameLocation spawnLoc, int numOfWeeds)
        {
            if (spawnLoc == null)
            {
                throw new Exception("The passed spawn location cannot be null!");
            }

            int CreatedWeeds = 0;

            for (int i = 0; i <= numOfWeeds; i++)
            {
                //limit number of attempts per attempt to 10.
                int numberOfAttempts = 0;
                while (numberOfAttempts < 3)
                {
                    //get a random tile.
                    int     xTile        = Game1.random.Next(spawnLoc.map.DisplayWidth / Game1.tileSize);
                    int     yTile        = Game1.random.Next(spawnLoc.map.DisplayHeight / Game1.tileSize);
                    Vector2 randomVector = new Vector2(xTile, yTile);
                    spawnLoc.objects.TryGetValue(randomVector, out SObject @object);

                    if (SDVUtilities.TileIsClearForSpawning(spawnLoc, randomVector, @object))
                    {
                        //for now, don't spawn in winter.
                        if (Game1.currentSeason != "winter")
                        {
                            //spawn the weed
                            spawnLoc.objects.Add(randomVector, new SObject(randomVector, GameLocation.getWeedForSeason(Game1.random, Game1.currentSeason), 1));
                            CreatedWeeds++;
                        }
                    }
                    numberOfAttempts++; // this might have been more useful INSIDE the while loop.
                }
            }
            return(CreatedWeeds);
        }
示例#3
0
 public static void Postfix(Tree __instance, GameTime time, Vector2 tileLocation, GameLocation location)
 {
     CheckForDialogue(__instance, time);
 }
 public override bool performToolAction(Tool t, int damage, Vector2 tileLocation, GameLocation location)
 {
     return(false);
 }
示例#5
0
文件: BaseQuest.cs 项目: mynew4/DAoC
 protected virtual void TeleportTo(GameObject target, GameObject caster, GameLocation location, uint delay)
 {
     TeleportTo(target, caster, location, delay, 0);
 }
示例#6
0
 /// <summary>
 /// Should be called whenever a player teleports to a new location
 /// </summary>
 /// <param name="player"></param>
 /// <param name="source"></param>
 /// <param name="destination"></param>
 public virtual void OnPlayerTeleport(GamePlayer player, GameLocation source, Teleport destination)
 {
     // override this in order to do something, like set immunity, when a player teleports
 }
示例#7
0
        private void HarvestAllItemsInBuilding(GameLocation location)
        {
            var buildingInfo = new BuildingContentsInfo(location, _supportedContainerTypes);

            Common.Utility.Log($"  {buildingInfo.Containers.Count()} containers found in building.");
            Common.Utility.Log($"  Of these containers, {buildingInfo.ReadyToHarvestContainers.Count()} are ready for harvest.");
            Common.Utility.Log($"  Of these containers, {buildingInfo.ReadyToLoadContainers.Count()} are empty and ready to be loaded.");

            var buildingHandler   = new BuildingContentsHandler(buildingInfo);
            int numItemsHarvested = 0;
            int numItemsLoaded    = 0;


            //Harvest all containers in building that are ready and place contents in player's inventory.
            try
            {
                numItemsHarvested = buildingHandler.HarvestContents(Game1.player);
            }
            catch (InventoryFullException ife)
            {
                numItemsHarvested = ife.NumItemsHarvestedBeforeFull;
                Game1.showRedMessage(Game1.content.LoadString("Strings\\StringsFromCSFiles:Crop.cs.588"));
            }
            catch (Exception ex)
            {
                Common.Utility.Log($"Exception while harvesting contents in BitwiseJonMods.OneClickShedReloader.HarvestAllItemsInBuilding: {ex.Message}", LogLevel.Error);
            }

            if (numItemsHarvested > 0)
            {
                var numContainersHarvested = buildingInfo.Containers.Count();
                Game1.playSound("coin");
                Game1.showGlobalMessage(string.Format("Harvested {0} {1} from {2} {3}!", numItemsHarvested, numItemsHarvested == 1 ? "item" : "items", numContainersHarvested, numContainersHarvested == 1 ? "container" : "containers"));
            }
            else
            {
                Game1.playSound("trashcan");
                Game1.showGlobalMessage("No items harvested.");
            }


            //If player is holding an object that can go into a container in the building, load as many as possible into any empty containers in building.
            try
            {
                numItemsLoaded = buildingHandler.LoadContents(Game1.player);
            }
            catch (Exception ex)
            {
                Common.Utility.Log($"Exception while loading contents in BitwiseJonMods.OneClickShedReloader.HarvestAllItemsInBuilding: {ex.Message}", LogLevel.Error);
            }

            if (numItemsLoaded > 0)
            {
                Game1.playSound("Ship");
                Game1.showGlobalMessage(string.Format("Loaded {0} {1}!", numItemsLoaded, numItemsLoaded == 1 ? "item" : "items"));
            }
            else
            {
                Game1.playSound("trashcan");
                Game1.showGlobalMessage("No items loaded.");
            }
        }
示例#8
0
        public static void ScriptLoaded(DOLEvent e, object sender, EventArgs args)
        {
            if (!ServerProperties.Properties.LOAD_QUESTS)
                return;
            if (log.IsInfoEnabled)
                log.Info("Quest \"" + questTitle + "\" initializing ...");
            /* First thing we do in here is to search for the NPCs inside
                * the world who comes from the Albion realm. If we find a the players,
                * this means we don't have to create a new one.
                *
                * NOTE: You can do anything you want in this method, you don't have
                * to search for NPC's ... you could create a custom item, place it
                * on the ground and if a player picks it up, he will get the quest!
                * Just examples, do anything you like and feel comfortable with :)
                */

            dalikor = GetDalikor();

            #region defineNPCs

            generalLocations[0] = new GameLocation(generalNames[0], 100, 100, 40124, 44594, 4712, 216);
            generalLocations[1] = new GameLocation(generalNames[1], 100, 100, 46821, 40884, 4972, 21);
            generalLocations[2] = new GameLocation(generalNames[2], 100, 100, 56104, 43865, 5460, 48);

            GameNPC[] npcs = null;
            for (int i = 0; i < general.Length; i++)
            {
                npcs = WorldMgr.GetNPCsByName(generalNames[i], eRealm.None);
                if (npcs.Length > 0)
                    general[i] = npcs[0] as GameNPC;
                else
                {
                    if (log.IsWarnEnabled)
                        log.Warn("Could not find " + generalNames[i] + ", creating ...");
                    general[i] = new GameNPC();

                    general[i].Model = 678;

                    general[i].GuildName = "Part of " + questTitle + " Quest";
                    general[i].Name = generalNames[i];
                    general[i].X = generalLocations[i].X;
                    general[i].Y = generalLocations[i].Y;
                    general[i].Z = generalLocations[i].Z;
                    general[i].Heading = generalLocations[i].Heading;

                    general[i].Realm = eRealm.None;
                    general[i].CurrentRegionID = generalLocations[i].RegionID;
                    general[i].Size = 49;
                    general[i].Level = 2;

                    StandardMobBrain brain = new StandardMobBrain();
                    brain.AggroLevel = 80;
                    brain.AggroRange = 1000;
                    general[i].SetOwnBrain(brain);

                    if (SAVE_INTO_DATABASE)
                        general[i].SaveIntoDatabase();

                    general[i].AddToWorld();
                }
            }

            #endregion defineNPCs

            #region defineItems

            /*
			 * TODO Model for Campfire doesn't work. Very Stange!
			 */
            /*
            // Add campfires to generals
            for (int i = 0; i < generalLocations.Length; i++)
            {
                GameStaticItem campfire = null;

                IEnumerable items =  WorldMgr.GetItemsCloseToSpot(generalLocations[i].RegionID,generalLocations[i].X, generalLocations[i].Y, generalLocations[i].Z, 400,true);
                foreach (GameObject obj in items)
                {
                    if (obj is GameStaticItem && obj.Name=="Camp Fire")
                    {
                        campfire= (GameStaticItem) obj;
                        break;
                    }
                }

                if (campfire==null)
                {
                    campfire = new GameStaticItem();
                    campfire.Name="Camp Fire";

                    campfire.Model = 2593;
                    campfire.Heading = generalLocations[i].Heading;
                    campfire.X = generalLocations[i].X;
                    campfire.Y = generalLocations[i].Y;
                    campfire.Z = generalLocations[i].Z;
                    campfire.CurrentRegionID = generalLocations[i].RegionID;

                    if (SAVE_INTO_DATABASE)
                        campfire.SaveIntoDatabase();

                    campfire.AddToWorld();

                    DOLConsole.WriteLine("Camp Fire added"+generalNames[i]);
                }
            }
*/

            askefruerWings = GameServer.Database.FindObjectByKey<ItemTemplate>("askefruer_wings");
            if (askefruerWings == null)
            {
                askefruerWings = new ItemTemplate();
                askefruerWings.Name = "Wings of Askefruer";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + askefruerWings.Name + " , creating it ...");

                askefruerWings.Weight = 2;
                askefruerWings.Model = 551;

                askefruerWings.Object_Type = (int)eObjectType.GenericItem;

                askefruerWings.Id_nb = "askefruer_wings";
                askefruerWings.IsPickable = true;
                askefruerWings.IsDropable = false;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    GameServer.Database.AddObject(askefruerWings);
            }

            dustyOldMap = GameServer.Database.FindObjectByKey<ItemTemplate>("dusty_old_map");
            if (dustyOldMap == null)
            {
                dustyOldMap = new ItemTemplate();
                dustyOldMap.Name = "Dusty Old Map";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + dustyOldMap.Name + " , creating it ...");

                dustyOldMap.Weight = 10;
                dustyOldMap.Model = 498;

                dustyOldMap.Object_Type = (int)eObjectType.GenericItem;

                dustyOldMap.Id_nb = "dusty_old_map";
                dustyOldMap.IsPickable = true;
                dustyOldMap.IsDropable = false;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    GameServer.Database.AddObject(dustyOldMap);
            }

            // item db check
            recruitsArms = GameServer.Database.FindObjectByKey<ItemTemplate>("recruits_studded_arms_mid");
            if (recruitsArms == null)
            {
                recruitsArms = new ItemTemplate();
                recruitsArms.Name = "Recruit's Studded Arms (Mid)";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + recruitsArms.Name + ", creating it ...");
                recruitsArms.Level = 7;

                recruitsArms.Weight = 36;
                recruitsArms.Model = 83; // studded Boots

                recruitsArms.DPS_AF = 10; // Armour
                recruitsArms.SPD_ABS = 19; // Absorption

                recruitsArms.Object_Type = (int)eObjectType.Studded;
                recruitsArms.Item_Type = (int)eEquipmentItems.ARMS;
                recruitsArms.Id_nb = "recruits_studded_arms_mid";
                recruitsArms.Price = Money.GetMoney(0, 0, 0, 4, 0);
                recruitsArms.IsPickable = true;
                recruitsArms.IsDropable = true;
                recruitsArms.Color = 36; // blue cloth

                recruitsArms.Bonus = 5; // default bonus

                recruitsArms.Bonus1 = 4;
                recruitsArms.Bonus1Type = (int)eStat.QUI;

                recruitsArms.Bonus2 = 1;
                recruitsArms.Bonus2Type = (int)eResist.Body;

                recruitsArms.Quality = 100;
                recruitsArms.Condition = 1000;
                recruitsArms.MaxCondition = 1000;
                recruitsArms.Durability = 1000;
                recruitsArms.MaxDurability = 1000;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    GameServer.Database.AddObject(recruitsArms);
            }

            recruitsSleeves = GameServer.Database.FindObjectByKey<ItemTemplate>("recruits_quilted_sleeves");
            if (recruitsSleeves == null)
            {
                recruitsSleeves = new ItemTemplate();
                recruitsSleeves.Name = "Recruit's Quilted Sleeves";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + recruitsSleeves.Name + ", creating it ...");
                recruitsSleeves.Level = 7;

                recruitsSleeves.Weight = 12;
                recruitsSleeves.Model = 153;

                recruitsSleeves.DPS_AF = 6; // Armour
                recruitsSleeves.SPD_ABS = 0; // Absorption

                recruitsSleeves.Object_Type = (int)eObjectType.Cloth;
                recruitsSleeves.Item_Type = (int)eEquipmentItems.ARMS;
                recruitsSleeves.Id_nb = "recruits_quilted_sleeves";
                recruitsSleeves.Price = Money.GetMoney(0, 0, 0, 4, 0);
                recruitsSleeves.IsPickable = true;
                recruitsSleeves.IsDropable = true;
                recruitsSleeves.Color = 27; // red cloth

                recruitsSleeves.Bonus = 5; // default bonus

                recruitsSleeves.Bonus1 = 4;
                recruitsSleeves.Bonus1Type = (int)eStat.DEX;

                recruitsSleeves.Bonus2 = 1;
                recruitsSleeves.Bonus2Type = (int)eResist.Body;

                recruitsSleeves.Quality = 100;
                recruitsSleeves.Condition = 1000;
                recruitsSleeves.MaxCondition = 1000;
                recruitsSleeves.Durability = 1000;
                recruitsSleeves.MaxDurability = 1000;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    GameServer.Database.AddObject(recruitsSleeves);
            }

            #endregion defineItems

            /* Now we add some hooks to the npc we found.
			* Actually, we want to know when a player interacts with him.
			* So, we hook the right-click (interact) and the whisper method
			* of npc and set the callback method to the "TalkToXXX"
			* method. This means, the "TalkToXXX" method is called whenever
			* a player right clicks on him or when he whispers to him.
			*/
            //We want to be notified whenever a player enters the world
            GameEventMgr.AddHandler(GamePlayerEvent.GameEntered, new DOLEventHandler(PlayerEnterWorld));

            GameEventMgr.AddHandler(dalikor, GameLivingEvent.Interact, new DOLEventHandler(TalkToDalikor));
            GameEventMgr.AddHandler(dalikor, GameLivingEvent.WhisperReceive, new DOLEventHandler(TalkToDalikor));

            GameEventMgr.AddHandler(GamePlayerEvent.AcceptQuest, new DOLEventHandler(SubscribeQuest));
            GameEventMgr.AddHandler(GamePlayerEvent.DeclineQuest, new DOLEventHandler(SubscribeQuest));

            /* Now we bring to dalikor the possibility to give this quest to players */
            dalikor.AddQuestToGive(typeof(Collection));

            if (log.IsInfoEnabled)
                log.Info("Quest \"" + questTitle + "\" initialized");
        }
示例#9
0
 public override void updateMovement(GameLocation location, GameTime time)
 {
 }
示例#10
0
 public FarmerCollection(GameLocation locationFilter = null)
 {
     _locationFilter = locationFilter;
 }
示例#11
0
 public static bool IsLavaTile(GameLocation location, int x, int y)
 {
     return(location.doesTileHaveProperty(x, y, "Water", "Back") != null);
 }
 /// <summary>Construct an instance.</summary>
 /// <param name="bin">The constructed shipping bin.</param>
 /// <param name="location">The location which contains the machine.</param>
 /// <param name="farm">The farm which has the shipping bin data.</param>
 public ShippingBinMachine(ShippingBin bin, GameLocation location, Farm farm)
     : base(location, BaseMachine.GetTileAreaFor(bin))
 {
     this.Farm = farm;
 }
示例#13
0
 /// <summary>Get a range handler which restricts access to a specific location.</summary>
 /// <param name="location">The specific location.</param>
 public static RangeHandler SpecificLocation(GameLocation location)
 {
     return(new RangeHandler(null, ChestRange.CurrentLocation, location)); // special case for migrating data
 }
示例#14
0
        /// <summary>
        /// Decides whether player can jump to the target point.
        /// All messages with reasons must be sent here.
        /// Can change destination too.
        /// </summary>
        /// <param name="targetPoint">The jump destination</param>
        /// <param name="player">The jumping player</param>
        /// <returns>True if allowed</returns>
        public bool IsAllowedToJump(ZonePoint targetPoint, GamePlayer player)
        {
            //Handles zoning INTO an instance.
            GameLocation loc = null;
            AdventureWingInstance previousInstance = null;

            // Do we have a group ?
            if(player.Group != null)
            {
                //Check if there is an instance dedicated to this group
                foreach(Region region in WorldMgr.GetAllRegions())
                {
                    if(region is AdventureWingInstance && ((AdventureWingInstance)region).Group != null && ((AdventureWingInstance)region).Group == player.Group)
                    {
                        // Our group has an instance !
                        previousInstance = (AdventureWingInstance)region;
                        break;
                    }
                    else if(region is AdventureWingInstance && ((AdventureWingInstance)region).Player != null && ((AdventureWingInstance)region).Player == player.Group.Leader)
                    {
                        // Our leader has an instance !
                        previousInstance = (AdventureWingInstance)region;
                        previousInstance.Group = player.Group;
                        break;
                    }
                }

            }
            else {
                // I am solo !
                //Check if there is an instance dedicated to me
                foreach(Region region in WorldMgr.GetAllRegions())
                {
                    if(region is AdventureWingInstance && ((AdventureWingInstance)region).Player != null && ((AdventureWingInstance)region).Player == player)
                    {
                        // I have an Instance !
                        previousInstance = (AdventureWingInstance)region;
                        previousInstance.Group = player.Group;
                        break;
                    }
                }
            }

            if(previousInstance != null)
            {
                // We should check if we can go in !
                if(previousInstance.Skin != targetPoint.TargetRegion)
                {
                    //we're trying to enter in an other instance and we still have one !
                    //check if previous one is empty
                    if(previousInstance.NumPlayers > 0)
                    {
                        //We can't jump !
                        player.Out.SendMessage("You have another instance (" + previousInstance.Description + ") running with people in it !", eChatType.CT_System, eChatLoc.CL_SystemWindow);
                        return false;
                    }
                    else
                    {
                        log.Warn("Player : "+ player.Name +" requested new Instance, destroying instance " + previousInstance.Description + ", ID: " + previousInstance.ID + ", type=" + previousInstance.GetType().ToString() + ".");
                        WorldMgr.RemoveInstance(previousInstance);
                        previousInstance = null;
                    }

                }

            }

               if(previousInstance == null)
               {
                // I have no instance to go to, create one !
                previousInstance = (AdventureWingInstance)WorldMgr.CreateInstance(targetPoint.TargetRegion, typeof(AdventureWingInstance));
                if(targetPoint.SourceRegion != 0 && targetPoint.SourceRegion == player.CurrentRegionID) {
                    //source loc seems legit...
                    previousInstance.SourceEntrance = new GameLocation("source", targetPoint.SourceRegion, targetPoint.SourceX, targetPoint.SourceY, targetPoint.SourceZ);
                }

                if(player.Group != null)
                {
                    previousInstance.Group = player.Group;
                    previousInstance.Player = player.Group.Leader;
                }
                else
                {
               			previousInstance.Group = null;
                    previousInstance.Player = player;
                }

                //get region data
                long mobs = 0;
                long merchants = 0;
                long items = 0;
                long bindpoints = 0;

                previousInstance.LoadFromDatabase(previousInstance.RegionData.Mobs, ref mobs, ref merchants, ref items, ref bindpoints);

                if (log.IsInfoEnabled)
                {
                    log.Info("Total Mobs: " + mobs);
                    log.Info("Total Merchants: " + merchants);
                    log.Info("Total Items: " + items);
                }

                //Attach Loot Generator
                LootMgr.RegisterLootGenerator(new LootGeneratorAurulite(), null, null, null, previousInstance.ID);

                // Player created new instance
                // Destroy all other instance that should be...
                List<Region> to_delete = new List<Region>();
                foreach(Region region in WorldMgr.GetAllRegions())
                {
                    if (region is AdventureWingInstance && (AdventureWingInstance)region != previousInstance)
                    {
                        AdventureWingInstance to_clean = (AdventureWingInstance)region;

               				// Won't clean up populated Instance
                        if(to_clean.NumPlayers == 0)
                        {

                            if(to_clean.Group != null && player.Group != null && to_clean.Group == player.Group)
                            {
                                // Got another instance for the same group... Destroy it !
                                to_delete.Add(to_clean);
                            }
                            else if(to_clean.Player != null && (to_clean.Player == player || (player.Group != null && player.Group.Leader == to_clean.Player)))
                            {
                                // Got another instance for the same player... Destroy it !
                                to_delete.Add(to_clean);
                            }
                            else if(to_clean.Group == null && to_clean.Player == null)
                            {
                                //nobody owns this instance anymore
                                to_delete.Add(to_clean);
                            }
                        }
                    }
                }

                //enumerate to_delete
                foreach(Region region in to_delete)
                {
                    log.Warn("Player : "+ player.Name +" has provoked an instance cleanup - " + region.Description + ", ID: " + region.ID + ", type=" + region.GetType().ToString() + ".");
                    WorldMgr.RemoveInstance((BaseInstance)region);
                }
               	}

            //get loc of instance
            if(previousInstance != null)
            {
                loc = new GameLocation(previousInstance.Description + " (instance)", previousInstance.ID, targetPoint.TargetX,  targetPoint.TargetY,  targetPoint.TargetZ,  targetPoint.TargetHeading);
            }

            if (loc != null)
            {

                // Move Player, changing target destination is failing !!
                player.MoveTo(loc);
                return false;
            }

            player.Out.SendMessage("Something went Wrong when creating Instance !", eChatType.CT_System, eChatLoc.CL_SystemWindow);
            return false;
        }
示例#15
0
        private void GetTileUnderCursor(object sender, UpdateTickedEventArgs e)
        {
            //Simulate previous SMAPI event GameEvents.FourthUpdateTick
            if (e.IsMultipleOf(4))
            {
                //See if we have a building under the cursor
                if (Game1.currentLocation is BuildableGameLocation buildableLocation)
                {
                    var building = buildableLocation.getBuildingAt(Game1.currentCursorTile);

                    if (building != null && _supportedBuildingTypes.Any(b => building.buildingType.Contains(b)))
                    {
                        //jon, 12/22/20: Greenhouse is now a building and can be moved. But the building is just a shell with no indoors so we must get
                        //  the actual Greenhouse game location here to use for finding objects inside.
                        if (building.buildingType == "Greenhouse")
                        {
                            if (Game1.MasterPlayer.hasOrWillReceiveMail("jojaPantry") || Game1.MasterPlayer.hasOrWillReceiveMail("ccPantry"))
                            {
                                _currentTileLocation = Game1.getLocationFromName("GreenHouse");
                            }
                        }
                        else
                        {
                            _currentTileLocation = building.indoors.Value;
                        }
                        return;
                    }
                }

                //See if we have the farmhouse or a cabin under the cursor that has a cellar
                var cellar = GetCellarForFarmHouseUnderCursor(Game1.currentCursorTile);
                if (cellar != null)
                {
                    //Common.Utility.Log($"{DateTime.Now.Ticks} House/Cabin under cursor has a cellar!");
                    _currentTileLocation = cellar;
                    return;
                }

                //See if we are in the greenhouse under and hovering near the door
                var greenhouse = GetGreenHouseUnderCursor(Game1.currentCursorTile);
                if (greenhouse != null)
                {
                    //Common.Utility.Log($"{DateTime.Now.Ticks} Greenhouse under cursor!");
                    _currentTileLocation = greenhouse;
                    return;
                }

                //See if we have the farm cave under the cursor
                var cave = GetFarmCaveUnderCursor(Game1.currentCursorTile);
                if (cave != null)
                {
                    //Common.Utility.Log($"{DateTime.Now.Ticks} Cave under cursor!");
                    _currentTileLocation = cave;
                    return;
                }


                //If we made it here, user is not hovering over supported building so set to null to hide tooltip
                _currentTileLocation = null;
            }
        }
示例#16
0
        public static void ScriptLoaded(DOLEvent e, object sender, EventArgs args)
        {
            if (!ServerProperties.Properties.LOAD_QUESTS)
                return;
            if (log.IsInfoEnabled)
                log.Info("Quest \"" + questTitle + "\" initializing ...");
            /* First thing we do in here is to search for the NPCs inside
             * the world who comes from the certain Realm. If we find a the players,
             * this means we don't have to create a new one.
             *
             * NOTE: You can do anything you want in this method, you don't have
             * to search for NPC's ... you could create a custom item, place it
             * on the ground and if a player picks it up, he will get the quest!
             * Just examples, do anything you like and feel comfortable with :)
             */

            #region DefineNPCs

            masterFrederick = GetMasterFrederick();

            GameNPC[] npcs = WorldMgr.GetNPCsByName("Master Visur", eRealm.Albion);
            if (npcs.Length == 0)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Master Visur, creating ...");
                masterVisur = new GameNPC();
                masterVisur.Model = 61;
                masterVisur.Name = "Master Visur";
                masterVisur.GuildName = "Part of " + questTitle + " Quest";
                masterVisur.Realm = eRealm.Albion;
                masterVisur.CurrentRegionID = 1;
                masterVisur.Size = 49;
                masterVisur.Level = 55;
                masterVisur.X = 585589;
                masterVisur.Y = 478396;
                masterVisur.Z = 3368;
                masterVisur.Heading = 56;
                masterVisur.MaxSpeedBase = 200;

                GameNpcInventoryTemplate template = new GameNpcInventoryTemplate();
                template.AddNPCEquipment(eInventorySlot.TorsoArmor, 798);
                template.AddNPCEquipment(eInventorySlot.RightHandWeapon, 19);
                masterVisur.Inventory = template.CloseTemplate();
                masterVisur.SwitchWeapon(GameLiving.eActiveWeaponSlot.Standard);

            //				masterVisur.AddNPCEquipment((byte) eEquipmentItems.TORSO, 798, 0, 0, 0);
            //				masterVisur.AddNPCEquipment((byte) eEquipmentItems.RIGHT_HAND, 19, 0, 0, 0);

                masterVisur.EquipmentTemplateID = "3400843";

                //You don't have to store the created mob in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    masterVisur.SaveIntoDatabase();
                masterVisur.AddToWorld();
            }
            else
                masterVisur = npcs[0];

            npcs = WorldMgr.GetNPCsByName("Scryer Alice", eRealm.Albion);
            if (npcs.Length == 0)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Alice, creating ...");
                alice = new GameNPC();
                alice.Model = 52;
                alice.Name = "Scryer Alice";
                alice.GuildName = "Part of " + questTitle + " Quest";
                alice.Realm = eRealm.Albion;
                alice.CurrentRegionID = 1;
                alice.Size = 51;
                alice.Level = 50;
                alice.X = 436598;
                alice.Y = 650425;
                alice.Z = 2448;

                GameNpcInventoryTemplate template = new GameNpcInventoryTemplate();
                template.AddNPCEquipment(eInventorySlot.TorsoArmor, 81);
                template.AddNPCEquipment(eInventorySlot.LegsArmor, 82);
                template.AddNPCEquipment(eInventorySlot.FeetArmor, 84);
                template.AddNPCEquipment(eInventorySlot.Cloak, 91);
                template.AddNPCEquipment(eInventorySlot.RightHandWeapon, 3);
                alice.Inventory = template.CloseTemplate();
                alice.SwitchWeapon(GameLiving.eActiveWeaponSlot.Standard);

            //				alice.AddNPCEquipment(Slot.TORSO, 81, 0, 0, 0);
            //				alice.AddNPCEquipment(Slot.LEGS, 82, 0, 0, 0);
            //				alice.AddNPCEquipment(Slot.FEET, 84, 0, 0, 0);
            //				alice.AddNPCEquipment(Slot.CLOAK, 91, 0, 0, 0);
            //				alice.AddNPCEquipment(Slot.RIGHTHAND, 3, 0, 0, 0);

                alice.Heading = 3766;
                alice.MaxSpeedBase = 200;
                alice.EquipmentTemplateID = "200276";
                alice.Flags = (GameNPC.eFlags) 18;

                StandardMobBrain brain = new StandardMobBrain();
                brain.AggroLevel = 0;
                brain.AggroRange = 0;
                alice.SetOwnBrain(brain);

                //You don't have to store the created mob in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    alice.SaveIntoDatabase();
                alice.AddToWorld();
            }
            else
                alice = npcs[0];

            Point2D point = alice.GetPointFromHeading( alice.Heading, 30 );
            locationAlice = new GameLocation(alice.CurrentZone.Description, alice.CurrentRegionID, point.X, point.Y, alice.Z);

            dragonflyTicket = CreateTicketTo("Castle Sauvage", "hs_src_castlesauvage");
            horseTicket = CreateTicketTo("Camelot Hills", "hs_src_camelothills");

            npcs = (GameNPC[]) WorldMgr.GetObjectsByName("Dragonfly Handler Colm", eRealm.Albion, typeof (GameStableMaster));
            if (npcs.Length == 0)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Dragonfly Handler Colm, creating ...");
                colm = new GameStableMaster();
                colm.Model = 78;
                colm.Name = "Dragonfly Handler Colm";
                colm.GuildName = "Stable Master";
                colm.Realm = eRealm.Albion;
                colm.CurrentRegionID = 1;
                colm.Size = 51;
                colm.Level = 50;

                GameNpcInventoryTemplate template = new GameNpcInventoryTemplate();
                template.AddNPCEquipment(eInventorySlot.TorsoArmor, 81, 10);
                template.AddNPCEquipment(eInventorySlot.LegsArmor, 82, 10);
                template.AddNPCEquipment(eInventorySlot.FeetArmor, 84, 10);
                template.AddNPCEquipment(eInventorySlot.Cloak, 57, 32);
                colm.Inventory = template.CloseTemplate();

            //				colm.AddNPCEquipment(Slot.TORSO, 81, 10, 0, 0);
            //				colm.AddNPCEquipment(Slot.LEGS, 82, 10, 0, 0);
            //				colm.AddNPCEquipment(Slot.FEET, 84, 10, 0, 0);
            //				colm.AddNPCEquipment(Slot.CLOAK, 57, 32, 0, 0);

                colm.X = 562775;
                colm.Y = 512453;
                colm.Z = 2438;
                colm.Heading = 158;
                colm.MaxSpeedBase = 200;

                StandardMobBrain brain = new StandardMobBrain();
                brain.AggroLevel = 0;
                brain.AggroRange = 0;
                colm.SetOwnBrain(brain);

                //You don't have to store the created mob in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    colm.SaveIntoDatabase();
                colm.AddToWorld();
            }
            else
            {
                colm = npcs[0] as GameStableMaster;
            }

            colm.TradeItems = new MerchantTradeItems(null);
            if (!colm.TradeItems.AddTradeItem(0, eMerchantWindowSlot.FirstEmptyInPage, dragonflyTicket))
                if (log.IsWarnEnabled)
                    log.Warn("dragonflyTicket not added");

            foreach (GameNPC npc in colm.GetNPCsInRadius(400))
            {
                if (npc.Name == "dragonfly hatchling")
                {
                    dragonfly = npc;
                    break;
                }
            }
            if (dragonfly == null)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Dragon Fly, creating ...");
                dragonfly = new GameNPC();
                dragonfly.Model = 1207;
                dragonfly.Name = "dragonfly hatchling";
                dragonfly.GuildName = "Part of " + questTitle + " Quest";
                dragonfly.Realm = eRealm.None;
                dragonfly.CurrentRegionID = 1;
                dragonfly.Size = 25;
                dragonfly.Level = 31;
                dragonfly.X = colm.X + 80;
                dragonfly.Y = colm.Y + 100;
                dragonfly.Z = colm.Z;

                StandardMobBrain brain = new StandardMobBrain();
                brain.AggroLevel = 0;
                brain.AggroRange = 0;
                dragonfly.SetOwnBrain(brain);

                dragonfly.Heading = 2434;
                dragonfly.MaxSpeedBase = 400;
                //dragonfly.EquipmentTemplateID = 200276;

                //You don't have to store the created mob in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database

                if (SAVE_INTO_DATABASE)
                    dragonfly.SaveIntoDatabase();
                dragonfly.AddToWorld();
            }

            npcs = (GameNPC[]) WorldMgr.GetObjectsByName("Uliam", eRealm.Albion, typeof (GameStableMaster));
            if (npcs.Length == 0)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Uliam, creating ...");
                uliam = new GameStableMaster();
                uliam.Model = 52;
                uliam.Name = "Uliam";
                uliam.GuildName = "Stable Master";
                uliam.Realm = eRealm.Albion;
                uliam.CurrentRegionID = 1;
                uliam.Size = 51;
                uliam.Level = 50;
                uliam.X = 585609;
                uliam.Y = 478980;
                uliam.Z = 2183;
                uliam.Heading = 93;
                uliam.MaxSpeedBase = 200;

                StandardMobBrain brain = new StandardMobBrain();
                brain.AggroLevel = 0;
                brain.AggroRange = 0;
                uliam.SetOwnBrain(brain);

                //ulliam.EquipmentTemplateID = 200276;

                //You don't have to store the created mob in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    uliam.SaveIntoDatabase();

                uliam.AddToWorld();
            }
            else
                uliam = npcs[0] as GameStableMaster;

            Point2D uliamloc = uliam.GetPointFromHeading( uliam.Heading, 30 );
            locationUliam = new GameLocation(uliam.CurrentZone.Description, uliam.CurrentRegionID, uliam.X, uliam.Y, uliam.Z);

            /*
            foreach (GameNPC npc in WorldMgr.GetNPCsCloseToObject(uliam, 400))
            {
                if (npc.Name == "horse")
                {
                    horse = npc;
                    break;
                }
            }

            if (horse == null)
            {
                if(Log.IsWarnEnabled)
                                    Log.Warn("Could not find Horse near Uliam, creating ...");
                horse = new GameNPC();
                horse.Model = 450; // //819;
                horse.Name = "horse";
                horse.GuildName = "Part of " + questTitle + " Quest";
                horse.Realm = (byte)eRealm.None;
                horse.CurrentRegionID = 1;
                horse.Size = 63;
                horse.Level = 55;
                horse.X = uliam.X + 80;
                horse.Y = uliam.Y + 130;
                horse.Z = uliam.Z;
                horse.Heading = 93;

                horse.AggroLevel = 0;
                horse.AggroRange = 0;
                //horse.EquipmentTemplateID = 200276;

                //You don't have to store the created mob in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    horse.SaveIntoDatabase();
                horse.AddToWorld();
            }
             */

            #endregion

            #region DefineItems

            // item db check
            noteFormColm = GameServer.Database.FindObjectByKey<ItemTemplate>("colms_note");
            if (noteFormColm == null)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Colm's Note, creating it ...");
                noteFormColm = new ItemTemplate();
                noteFormColm.Name = "Colm's Note";

                noteFormColm.Weight = 3;
                noteFormColm.Model = 498;

                noteFormColm.Object_Type = (int) eObjectType.GenericItem;

                noteFormColm.Id_nb = "colms_note";
                noteFormColm.IsPickable = true;
                noteFormColm.IsDropable = false;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database

                    GameServer.Database.AddObject(noteFormColm);
            }

            // item db check
            fairyPlans = GameServer.Database.FindObjectByKey<ItemTemplate>("ire_fairy_plans");
            if (fairyPlans == null)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Ire Fairy Plans, creating it ...");
                fairyPlans = new ItemTemplate();
                fairyPlans.Name = "Ire Fairy Plans";

                fairyPlans.Weight = 3;
                fairyPlans.Model = 498;

                fairyPlans.Object_Type = (int) eObjectType.GenericItem;

                fairyPlans.Id_nb = "ire_fairy_plans";
                fairyPlans.IsPickable = true;
                fairyPlans.IsDropable = false;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database

                    GameServer.Database.AddObject(fairyPlans);
            }

            translatedPlans = GameServer.Database.FindObjectByKey<ItemTemplate>("translated_ire_fairy_plans");
            if (translatedPlans == null)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Translated Ire Fairy Plans, creating it ...");
                translatedPlans = new ItemTemplate();
                translatedPlans.Name = "Translated Ire Fairy Plans";

                translatedPlans.Weight = 3;
                translatedPlans.Model = 498;

                translatedPlans.Object_Type = (int) eObjectType.GenericItem;

                translatedPlans.Id_nb = "translated_ire_fairy_plans";
                translatedPlans.IsPickable = true;
                translatedPlans.IsDropable = false;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database

                    GameServer.Database.AddObject(translatedPlans);
            }

            // item db check
            recruitsLegs = GameServer.Database.FindObjectByKey<ItemTemplate>("recruits_studded_legs");
            if (recruitsLegs == null)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Recruit's Studded Legs, creating it ...");
                recruitsLegs = new ItemTemplate();
                recruitsLegs.Name = "Recruit's Studded Legs";
                recruitsLegs.Level = 7;

                recruitsLegs.Weight = 42;
                recruitsLegs.Model = 82; // Studded Legs

                recruitsLegs.DPS_AF = 10; // Armour
                recruitsLegs.SPD_ABS = 19; // Absorption

                recruitsLegs.Object_Type = (int) eObjectType.Studded;
                recruitsLegs.Item_Type = (int) eEquipmentItems.LEGS;
                recruitsLegs.Id_nb = "recruits_studded_legs";
                recruitsLegs.Price = Money.GetMoney(0,0,0,10,0);
                recruitsLegs.IsPickable = true;
                recruitsLegs.IsDropable = true;
                recruitsLegs.Color = 9; // red leather

                recruitsLegs.Bonus = 5; // default bonus

                recruitsLegs.Bonus1 = 10;
                recruitsLegs.Bonus1Type = (int) eProperty.MaxHealth; // hit

                recruitsLegs.Bonus2 = 2;
                recruitsLegs.Bonus2Type = (int) eResist.Slash;

                recruitsLegs.Bonus3 = 1;
                recruitsLegs.Bonus3Type = (int) eResist.Cold;

                recruitsLegs.Quality = 100;
                recruitsLegs.Condition = 1000;
                recruitsLegs.MaxCondition = 1000;
                recruitsLegs.Durability = 1000;
                recruitsLegs.MaxDurability = 1000;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database

                    GameServer.Database.AddObject(recruitsLegs);
            }

            // item db check
            recruitsPants = GameServer.Database.FindObjectByKey<ItemTemplate>("recruits_quilted_pants");
            if (recruitsPants == null)
            {
                recruitsPants = new ItemTemplate();
                recruitsPants.Name = "Recruit's Quilted Pants";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + recruitsPants.Name + ", creating it ...");
                recruitsPants.Level = 7;

                recruitsPants.Weight = 14;
                recruitsPants.Model = 152; // cloth Legs

                recruitsPants.DPS_AF = 5; // Armour
                recruitsPants.SPD_ABS = 0; // Absorption

                recruitsPants.Object_Type = (int) eObjectType.Cloth;
                recruitsPants.Item_Type = (int) eEquipmentItems.LEGS;
                recruitsPants.Id_nb = "recruits_quilted_pants";
                recruitsPants.Price = Money.GetMoney(0,0,0,10,0);
                recruitsPants.IsPickable = true;
                recruitsPants.IsDropable = true;
                recruitsPants.Color = 17; // red leather

                recruitsPants.Bonus = 5; // default bonus

                recruitsPants.Bonus1 = 12;
                recruitsPants.Bonus1Type = (int) eProperty.MaxHealth; // hit

                recruitsPants.Bonus2 = 2;
                recruitsPants.Bonus2Type = (int) eResist.Slash;

                recruitsPants.Bonus3 = 1;
                recruitsPants.Bonus3Type = (int) eResist.Cold;

                recruitsPants.Quality = 100;
                recruitsPants.Condition = 1000;
                recruitsPants.MaxCondition = 1000;
                recruitsPants.Durability = 1000;
                recruitsPants.MaxDurability = 1000;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database

                    GameServer.Database.AddObject(recruitsPants);
            }

            #endregion

            /* Now we add some hooks to the npc we found.
             * Actually, we want to know when a player interacts with him.
             * So, we hook the right-click (interact) and the whisper method
             * of npc and set the callback method to the "TalkToXXX"
             * method. This means, the "TalkToXXX" method is called whenever
             * a player right clicks on him or when he whispers to him.
             */

            GameEventMgr.AddHandler(GamePlayerEvent.AcceptQuest, new DOLEventHandler(SubscribeQuest));
            GameEventMgr.AddHandler(GamePlayerEvent.DeclineQuest, new DOLEventHandler(SubscribeQuest));

            //We want to be notified whenever a player enters the world
            GameEventMgr.AddHandler(GamePlayerEvent.GameEntered, new DOLEventHandler(PlayerEnterWorld));

            GameEventMgr.AddHandler(masterFrederick, GameLivingEvent.Interact, new DOLEventHandler(TalkToMasterFrederick));
            GameEventMgr.AddHandler(masterFrederick, GameLivingEvent.WhisperReceive, new DOLEventHandler(TalkToMasterFrederick));

            GameEventMgr.AddHandler(masterVisur, GameObjectEvent.Interact, new DOLEventHandler(TalkToMasterVisur));

            GameEventMgr.AddHandler(colm, GameObjectEvent.Interact, new DOLEventHandler(TalkToColm));

            GameEventMgr.AddHandler(alice, GameObjectEvent.Interact, new DOLEventHandler(TalkToAlice));
            GameEventMgr.AddHandler(alice, GameLivingEvent.WhisperReceive, new DOLEventHandler(TalkToAlice));

            /* Now we bring to masterFrederick the possibility to give this quest to players */
            masterFrederick.AddQuestToGive(typeof (Frontiers));

            if (log.IsInfoEnabled)
                log.Info("Quest \"" + questTitle + "\" initialized");
        }
示例#17
0
        public static double GetPathDistance(GameLocation startLocation)
        {
            double RecursionMethod(GameLocation location, double dist)
            {
                if (dist > MaxSearchRange)
                {
                    return(DistancePenalty * dist);
                }
                // Check if this is a leveled location
                if (location is MineShaft)
                {
                    var shaft = location as MineShaft;
                    // Detect the DynamicDungeon, it uses SkullCave logic, but it starts with lvl 1, so we gotta fix that
                    if (Game1.currentLocation.Name.Equals("DynamicDungeon"))
                    {
                        return(GetPathDistance(Game1.getLocationFromName("WizardHouse")) + DistancePenalty * 2 + ((shaft.mineLevel + 120) * SkullDepthPenalty));
                    }
                    _Active.Remove(location.Name);
                    if (shaft.mineLevel > 120) // SkullCave
                    {
                        return(GetPathDistance(Game1.getLocationFromName("SkullCave")) + DistancePenalty + (shaft.mineLevel * SkullDepthPenalty));
                    }
                    else // Mines
                    {
                        return(GetPathDistance(Game1.getLocationFromName("Mine")) + DistancePenalty + (shaft.mineLevel * MineDepthPenalty));
                    }
                }
                // List if maps this map is connected to
                List <string> maps = new List <string>();

                void Whitelist(string mapName)
                {
                    if (!_Active.Contains(mapName))
                    {
                        maps.Add(mapName);
                        _Active.Add(mapName);
                    }
                }

                // We assume to begin with that we are insanely far away (No real situation should ever have -this- high a value, so it also makes it possible to detect a location that is not connected at all)
                double mdist = double.MaxValue;

                // AlchemyOffset, used to create path distance end points that can have a default penalty or have it as 0 for no default penalty
                if (location.map.Properties.ContainsKey(LeylineProperty))
                {
                    mdist = Convert.ToDouble((string)location.map.Properties[LeylineProperty]) - DistancePenalty;
                }
                else // The hard offset of a alchemyOffset point overrides any distance based cost
                {
                    // Check through all warps in the location
                    foreach (Warp warp in location.warps)
                    {
                        Whitelist(warp.TargetName);
                    }
                    // We loop through all Buildings tiles on the map to look for certain tile actions
                    for (int x = 0; x < location.map.Layers[0].LayerWidth; x++)
                    {
                        for (int y = 0; y < location.map.Layers[0].LayerHeight; y++)
                        {
                            // We check if it has a Action property, otherwise we can just ignore it
                            string prop = location.doesTileHaveProperty(x, y, "Action", "Buildings") ?? location.doesTileHaveProperty(x, y, "TouchAction", "Back");
                            if (prop == null)
                            {
                                continue;
                            }
                            // We check if the property is a certain type
                            switch (prop)
                            {
                            // Locations with special warps are handled here
                            case "WarpCommunityCenter":
                            case "WarpGreenhouse":
                                Whitelist(prop.Substring(4));
                                break;

                            case "EnterSewer":
                                Whitelist("Sewer");
                                break;

                            case "WizardHatch":
                                Whitelist("WizardHouseBasement");
                                break;

                            default:
                                // Locations that are normal or locked-door warps are handled here
                                var props = prop.Split(' ');
                                switch (props[0])
                                {
                                case "Warp":
                                case "LockedDoorWarp":
                                case "WarpWomensLocker":
                                case "WarpMensLocker":
                                    if (Game1.getLocationFromName(props[3]) != null)
                                    {
                                        Whitelist(props[3]);
                                    }
                                    break;

                                case "MagicWarp":
                                    if (Game1.getLocationFromName(props[1]) != null)
                                    {
                                        Whitelist(props[1]);
                                    }
                                    break;
                                }
                                break;
                            }
                        }
                    }
                    if (maps.Count == 0)
                    {
                        return(mdist);
                    }
                    foreach (string map in maps)
                    {
                        double vdist = RecursionMethod(Game1.getLocationFromName(map), dist + 1);
                        if (vdist < mdist)
                        {
                            mdist = vdist;
                        }
                    }
                }
                // We remove ourselves from the active list so future queries will work properly again
                // We add the result for this location to the cache only if its parent distance is 0 (This is the location being checked)
                if (dist == 0)
                {
                    _Active.Clear();
                    _Cache.Add(location.Name, mdist + DistancePenalty);
                }
                return(mdist + DistancePenalty);
            }

            // We only calculate path distance if we havent done so already for this location (Unless it is leveled, then we always recalculate)
            if (!_Cache.ContainsKey(startLocation.Name))
            {
                return(RecursionMethod(startLocation, 0));
            }
            // We return the offset (Distance of the parent) to our own, and return it
            return(_Cache[startLocation.Name]);
        }
示例#18
0
        /**
         * Convinient Method for teleporintg with assistant
         */

        protected void TeleportTo(GameLocation target)
        {
            TeleportTo(m_questPlayer, assistant, target, 5);
            TeleportTo(assistant, assistant, target, 25, 50);
        }
示例#19
0
        /// <summary>Get a unique map name for the given location.</summary>
        private string GetMapName(GameLocation location)
        {
            string uniqueName = location.uniqueName.Value;

            return(uniqueName ?? location.Name);
        }
示例#20
0
文件: Collection.cs 项目: mynew4/DAoC
        public static void ScriptLoaded(DOLEvent e, object sender, EventArgs args)
        {
            if (!ServerProperties.Properties.LOAD_QUESTS)
                return;
            if (log.IsInfoEnabled)
                log.Info("Quest \"" + questTitle + "\" initializing ...");
            /* First thing we do in here is to search for the NPCs inside
            * the world who comes from the certain Realm. If we find a the players,
            * this means we don't have to create a new one.
            *
            * NOTE: You can do anything you want in this method, you don't have
            * to search for NPC's ... you could create a custom item, place it
            * on the ground and if a player picks it up, he will get the quest!
            * Just examples, do anything you like and feel comfortable with :)
            */

            #region defineNPCS

            masterFrederick = GetMasterFrederick();

            generalLocations[0] = new GameLocation(generalNames[0], 1, 568589, 501801, 2134, 23);
            generalLocations[1] = new GameLocation(generalNames[1], 1, 572320, 499246, 2472, 14);
            generalLocations[2] = new GameLocation(generalNames[2], 1, 571900, 510559, 2210, 170);

            GameNPC[] npcs = null;
            for (int i = 0; i < general.Length; i++)
            {
                npcs = WorldMgr.GetNPCsByName(generalNames[i], eRealm.None);
                if (npcs.Length > 0)
                    general[i] = npcs[0] as GameNPC;
                else
                {
                    if (log.IsWarnEnabled)
                        log.Warn("Could not find " + generalNames[i] + ", creating her ...");
                    general[i] = new GameNPC();

                    general[i].Model = 603;

                    general[i].Name = generalNames[i];
                    general[i].X = generalLocations[i].X;
                    general[i].Y = generalLocations[i].Y;
                    general[i].Z = generalLocations[i].Z;
                    general[i].Heading = generalLocations[i].Heading;

                    general[i].GuildName = "Part of " + questTitle + " Quest";
                    general[i].Realm = eRealm.None;
                    general[i].CurrentRegionID = generalLocations[i].RegionID;

                    general[i].Size = 49;
                    general[i].Level = 2;
                    general[i].Race = 2007;
                    general[i].BodyType = 8;

                    StandardMobBrain brain = new StandardMobBrain();
                    brain.AggroLevel = 80;
                    brain.AggroRange = 1000;
                    general[i].SetOwnBrain(brain);

                    if (SAVE_INTO_DATABASE)
                        general[i].SaveIntoDatabase();
                    general[i].AddToWorld();
                }
            }

            #endregion

            #region defineItems

            fairyGeneralWings = GameServer.Database.FindObjectByKey<ItemTemplate>("fairy_general_wings");
            if (fairyGeneralWings == null)
            {
                fairyGeneralWings = new ItemTemplate();
                fairyGeneralWings.Name = "Wings of Fairy General";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + fairyGeneralWings.Name + " , creating it ...");

                fairyGeneralWings.Weight = 2;
                fairyGeneralWings.Model = 551;

                fairyGeneralWings.Object_Type = (int) eObjectType.GenericItem;

                fairyGeneralWings.Id_nb = "fairy_general_wings";
                fairyGeneralWings.IsPickable = true;
                fairyGeneralWings.IsDropable = false;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database

                    GameServer.Database.AddObject(fairyGeneralWings);
            }

            dustyOldMap = GameServer.Database.FindObjectByKey<ItemTemplate>("dusty_old_map");
            if (dustyOldMap == null)
            {
                dustyOldMap = new ItemTemplate();
                dustyOldMap.Name = "Dusty Old Map";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + dustyOldMap.Name + " , creating it ...");

                dustyOldMap.Weight = 10;
                dustyOldMap.Model = 498;

                dustyOldMap.Object_Type = (int) eObjectType.GenericItem;

                dustyOldMap.Id_nb = "dusty_old_map";
                dustyOldMap.IsPickable = true;
                dustyOldMap.IsDropable = false;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database

                    GameServer.Database.AddObject(dustyOldMap);
            }

            // item db check
            recruitsArms = GameServer.Database.FindObjectByKey<ItemTemplate>("recruits_studded_arms");
            if (recruitsArms == null)
            {
                recruitsArms = new ItemTemplate();
                recruitsArms.Name = "Recruit's Studded Arms";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + recruitsArms.Name + ", creating it ...");
                recruitsArms.Level = 7;

                recruitsArms.Weight = 36;
                recruitsArms.Model = 83; // studded Boots

                recruitsArms.DPS_AF = 10; // Armour
                recruitsArms.SPD_ABS = 19; // Absorption

                recruitsArms.Object_Type = (int) eObjectType.Studded;
                recruitsArms.Item_Type = (int) eEquipmentItems.ARMS;
                recruitsArms.Id_nb = "recruits_studded_arms";
                recruitsArms.Price = Money.GetMoney(0,0,0,4,0);
                recruitsArms.IsPickable = true;
                recruitsArms.IsDropable = true;
                recruitsArms.Color = 9; // red leather

                recruitsArms.Bonus = 5; // default bonus

                recruitsArms.Bonus1 = 4;
                recruitsArms.Bonus1Type = (int) eStat.QUI;

                recruitsArms.Bonus2 = 1;
                recruitsArms.Bonus2Type = (int) eResist.Body;

                recruitsArms.Quality = 100;
                recruitsArms.Condition = 1000;
                recruitsArms.MaxCondition = 1000;
                recruitsArms.Durability = 1000;
                recruitsArms.MaxDurability = 1000;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database

                    GameServer.Database.AddObject(recruitsArms);
            }

            recruitsSleeves = GameServer.Database.FindObjectByKey<ItemTemplate>("recruits_quilted_sleeves");
            if (recruitsSleeves == null)
            {
                recruitsSleeves = new ItemTemplate();
                recruitsSleeves.Name = "Recruit's Quilted Sleeves";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + recruitsSleeves.Name + ", creating it ...");
                recruitsSleeves.Level = 7;

                recruitsSleeves.Weight = 12;
                recruitsSleeves.Model = 153;

                recruitsSleeves.DPS_AF = 6; // Armour
                recruitsSleeves.SPD_ABS = 0; // Absorption

                recruitsSleeves.Object_Type = (int) eObjectType.Cloth;
                recruitsSleeves.Item_Type = (int) eEquipmentItems.ARMS;
                recruitsSleeves.Id_nb = "recruits_quilted_sleeves";
                recruitsSleeves.Price = Money.GetMoney(0,0,0,4,0);
                recruitsSleeves.IsPickable = true;
                recruitsSleeves.IsDropable = true;
                recruitsSleeves.Color = 27; // red cloth

                recruitsSleeves.Bonus = 5; // default bonus

                recruitsSleeves.Bonus1 = 4;
                recruitsSleeves.Bonus1Type = (int) eStat.DEX;

                recruitsSleeves.Bonus2 = 1;
                recruitsSleeves.Bonus2Type = (int) eResist.Body;

                recruitsSleeves.Quality = 100;
                recruitsSleeves.Condition = 1000;
                recruitsSleeves.MaxCondition = 1000;
                recruitsSleeves.Durability = 1000;
                recruitsSleeves.MaxDurability = 1000;

                //You don't have to store the created item in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database

                    GameServer.Database.AddObject(recruitsSleeves);
            }

            #endregion

            /* Now we add some hooks to the npc we found.
            * Actually, we want to know when a player interacts with him.
            * So, we hook the right-click (interact) and the whisper method
            * of npc and set the callback method to the "TalkToXXX"
            * method. This means, the "TalkToXXX" method is called whenever
            * a player right clicks on him or when he whispers to him.
            */

            GameEventMgr.AddHandler(GamePlayerEvent.AcceptQuest, new DOLEventHandler(SubscribeQuest));
            GameEventMgr.AddHandler(GamePlayerEvent.DeclineQuest, new DOLEventHandler(SubscribeQuest));

            //We want to be notified whenever a player enters the world
            GameEventMgr.AddHandler(GamePlayerEvent.GameEntered, new DOLEventHandler(PlayerEnterWorld));

            GameEventMgr.AddHandler(masterFrederick, GameLivingEvent.Interact, new DOLEventHandler(TalkToMasterFrederick));
            GameEventMgr.AddHandler(masterFrederick, GameLivingEvent.WhisperReceive, new DOLEventHandler(TalkToMasterFrederick));

            /* Now we bring to masterFrederick the possibility to give this quest to players */
            masterFrederick.AddQuestToGive(typeof (Collection));

            if (log.IsInfoEnabled)
                log.Info("Quest \"" + questTitle + "\" initialized");
        }
示例#21
0
 public override void performRemoveAction(Vector2 tileLocation, GameLocation environment)
 {
     removeOverlayTiles(environment);
     base.performRemoveAction(tileLocation, environment);
 }
示例#22
0
        /// <summary>Get whether a location is within range of the player.</summary>
        /// <param name="location">The location to check.</param>
        public bool IsInRange(GameLocation location)
        {
            string zone = this.GetZone(location, this.Range);

            return(zone != null && zone == this.CurrentZone);
        }
示例#23
0
        public override void DayUpdate(GameLocation location)
        {
            bool isLuremaster = Game1.getFarmer(owner) != null && Game1.getFarmer(owner).professions.Contains(11);
            bool isMariner    = Game1.getFarmer(owner) != null && Game1.getFarmer(owner).professions.Contains(10);

            if ((long)owner == 0L && Game1.player.professions.Contains(11))
            {
                isMariner = true;
            }
            if (!((bait.Value != null) | isLuremaster) || heldObject.Value != null)
            {
                return;
            }
            tileIndexToShow       = 714;
            readyForHarvest.Value = true;
            Random r = new Random((int)Game1.stats.DaysPlayed + (int)Game1.uniqueIDForThisGame / 2 + (int)tileLocation.X * 1000 + (int)tileLocation.Y);
            Dictionary <int, string> fishData = Game1.content.Load <Dictionary <int, string> >("Data\\Fish");
            List <int> marinerList            = new List <int>();
            double     chanceForJunk          = isMariner ? 0.0 : 0.2;

            if (!isMariner)
            {
                chanceForJunk += (double)location.getExtraTrashChanceForCrabPot((int)tileLocation.X, (int)tileLocation.Y);
            }
            if (r.NextDouble() > chanceForJunk)
            {
                foreach (KeyValuePair <int, string> v in fishData)
                {
                    if (v.Value.Contains("trap"))
                    {
                        bool     should_catch_ocean_fish = location is Beach || location.catchOceanCrabPotFishFromThisSpot((int)tileLocation.X, (int)tileLocation.Y);
                        string[] rawSplit = v.Value.Split('/');
                        if ((!rawSplit[4].Equals("ocean") || should_catch_ocean_fish) && (!rawSplit[4].Equals("freshwater") || !should_catch_ocean_fish))
                        {
                            if (isMariner)
                            {
                                marinerList.Add(v.Key);
                            }
                            else
                            {
                                double chanceForCatch = Convert.ToDouble(rawSplit[2]);
                                if (r.NextDouble() < chanceForCatch)
                                {
                                    heldObject.Value = new Object(v.Key, 1);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if (heldObject.Value == null)
            {
                if (isMariner && marinerList.Count > 0)
                {
                    heldObject.Value = new Object(marinerList[r.Next(marinerList.Count)], 1);
                }
                else
                {
                    heldObject.Value = new Object(r.Next(168, 173), 1);
                }
            }
        }
示例#24
0
        /*********
        ** Private methods
        *********/
        /// <summary>The method to call after <see cref="Farmer.moveRaft"/>.</summary>
        public static void After_MoveRaft(Farmer __instance, GameLocation currentLocation, GameTime time)
        {
            __instance.position.X += __instance.xVelocity;
            __instance.position.Y += __instance.yVelocity;
            Rectangle r = new Rectangle((int)(__instance.Position.X), (int)(__instance.Position.Y + 16), 64, 64);

            // 2 - down, 0 - up, 3 - left, 1 - right
            //Log.trace( "meow: " + ( __instance.movementDirections.Count > 0 ?__instance.movementDirections[0]:-1));
            if (__instance.movementDirections.Contains(2) || __instance.movementDirections.Contains(0))
            {
                Vector2 pos  = new Vector2(r.X + r.Width / 2, r.Y + r.Height);
                var     xPos = new xTile.Dimensions.Location((int)pos.X, (int)pos.Y);
                xTile.ObjectModel.PropertyValue propVal = null;
                currentLocation.map.GetLayer("Back").PickTile(xPos, Game1.viewport.Size)?.TileIndexProperties.TryGetValue("Water", out propVal);
                if (propVal == null)
                {
                    if (currentLocation.isTileLocationOpen(xPos))
                    {
                        Game1.player.isRafting = false;
                        Game1.player.Position  = pos;
                        //Game1.player.position.Y -= 64 + 16;
                        Game1.player.setTrajectory(0, 0);
                    }
                    return;
                }

                pos     = new Vector2(r.X + r.Width / 2, r.Y);
                xPos    = new xTile.Dimensions.Location((int)pos.X, (int)pos.Y);
                propVal = null;
                currentLocation.map.GetLayer("Back").PickTile(xPos, Game1.viewport.Size)?.TileIndexProperties.TryGetValue("Water", out propVal);
                if (propVal == null)
                {
                    if (currentLocation.isTileLocationOpen(xPos))
                    {
                        Game1.player.isRafting   = false;
                        Game1.player.Position    = pos;
                        Game1.player.position.Y -= 64 + 16;
                        Game1.player.setTrajectory(0, 0);
                    }
                    return;
                }
            }

            if (__instance.movementDirections.Contains(3))
            {
                Vector2 pos  = new Vector2(r.X, r.Y + r.Height / 2);
                var     xPos = new xTile.Dimensions.Location((int)pos.X, (int)pos.Y);
                xTile.ObjectModel.PropertyValue propVal = null;
                currentLocation.map.GetLayer("Back").PickTile(xPos, Game1.viewport.Size)?.TileIndexProperties.TryGetValue("Water", out propVal);
                if (propVal == null)
                {
                    if (currentLocation.isTileLocationOpen(xPos))
                    {
                        Game1.player.isRafting   = false;
                        Game1.player.Position    = pos;
                        Game1.player.position.Y -= 64 + 16;
                        Game1.player.setTrajectory(0, 0);
                    }
                    return;
                }

                pos     = new Vector2(r.X + r.Width, r.Y + r.Height / 2);
                xPos    = new xTile.Dimensions.Location((int)pos.X, (int)pos.Y);
                propVal = null;
                currentLocation.map.GetLayer("Back").PickTile(xPos, Game1.viewport.Size)?.TileIndexProperties.TryGetValue("Water", out propVal);
                if (propVal == null)
                {
                    if (currentLocation.isTileLocationOpen(xPos))
                    {
                        Game1.player.isRafting   = false;
                        Game1.player.Position    = pos;
                        Game1.player.position.Y -= 64 + 16;
                        Game1.player.setTrajectory(0, 0);
                    }
                    return;
                }
            }
        }
示例#25
0
        // Token: 0x060001E2 RID: 482 RVA: 0x0002B3D8 File Offset: 0x000295D8
        public bool update(GameTime time, GameLocation location, List <NPCController> allControllers)
        {
            this.puppet.speed = this.speed;
            bool reachedMeYet = false;

            foreach (NPCController i in allControllers)
            {
                if (i.puppet != null)
                {
                    if (i.puppet.Equals(this.puppet))
                    {
                        reachedMeYet = true;
                    }
                    if (i.puppet.facingDirection == this.puppet.facingDirection && !i.puppet.Equals(this.puppet) && i.puppet.GetBoundingBox().Intersects(this.puppet.nextPosition(this.puppet.facingDirection)))
                    {
                        if (reachedMeYet)
                        {
                            break;
                        }
                        return(false);
                    }
                }
            }
            this.puppet.MovePosition(time, Game1.viewport, location);
            if (this.pauseTime < 0 && !this.puppet.isMoving())
            {
                this.setMoving(false);
            }
            if (this.pauseTime < 0 && Math.Abs(Vector2.Distance(this.puppet.position, this.target)) <= (float)this.puppet.Speed)
            {
                this.pathIndex++;
                if (!this.setMoving(true))
                {
                    if (!this.loop)
                    {
                        if (this.behaviorAtEnd != null)
                        {
                            this.behaviorAtEnd();
                        }
                        return(true);
                    }
                    this.pathIndex = 0;
                    this.setMoving(true);
                }
            }
            else if (this.pauseTime >= 0)
            {
                this.pauseTime -= time.ElapsedGameTime.Milliseconds;
                if (this.pauseTime < 0)
                {
                    this.pathIndex++;
                    if (!this.setMoving(true))
                    {
                        if (!this.loop)
                        {
                            if (this.behaviorAtEnd != null)
                            {
                                this.behaviorAtEnd();
                            }
                            return(true);
                        }
                        this.pathIndex = 0;
                        this.setMoving(true);
                    }
                }
            }
            return(false);
        }
示例#26
0
        public static Vector2 SpawnRandomMonster(GameLocation location)
        {
            for (int index = 0; index < 15; ++index)
            {
                Vector2 randomTile = location.getRandomTile();
                if (Utility.isOnScreen(Utility.Vector2ToPoint(randomTile), 64, location))
                {
                    randomTile.X -= Game1.viewport.Width / 64;
                }
                if (location.isTileLocationTotallyClearAndPlaceable(randomTile))
                {
                    if (Game1.player.CombatLevel >= 10 && Game1.MasterPlayer.deepestMineLevel >= 145 && Game1.random.NextDouble() <= .001 && Game1.MasterPlayer.stats.getMonstersKilled("Pepper Rex") > 0)
                    {
                        DinoMonster squidKid = new DinoMonster(randomTile * Game1.tileSize)
                        {
                            focusedOnFarmers = true
                        };
                        location.characters.Add(squidKid);

                        return(randomTile);
                    }

                    else if (Game1.player.CombatLevel >= 10 && Game1.MasterPlayer.deepestMineLevel >= 145 && Game1.random.NextDouble() <= .05)
                    {
                        MetalHead squidKid = new MetalHead(randomTile * Game1.tileSize, 145)
                        {
                            focusedOnFarmers = true
                        };
                        location.characters.Add(squidKid);

                        return(randomTile);
                    }

                    else if (Game1.player.CombatLevel >= 10 && Game1.random.NextDouble() <= .25)
                    {
                        Skeleton skeleton = new Skeleton(randomTile * Game1.tileSize)
                        {
                            focusedOnFarmers = true
                        };
                        location.characters.Add(skeleton);

                        return(randomTile);
                    }

                    else if (Game1.player.CombatLevel >= 8 && Game1.random.NextDouble() <= 0.15)
                    {
                        ShadowBrute shadowBrute = new ShadowBrute(randomTile * Game1.tileSize)
                        {
                            focusedOnFarmers = true
                        };
                        location.characters.Add(shadowBrute);

                        return(randomTile);
                    }
                    else if (Game1.random.NextDouble() < 0.65 && location.isTileLocationTotallyClearAndPlaceable(randomTile))
                    {
                        RockGolem rockGolem = new RockGolem(randomTile * Game1.tileSize, Game1.player.CombatLevel)
                        {
                            focusedOnFarmers = true
                        };
                        rockGolem.Sprite.currentFrame = 16;
                        rockGolem.Sprite.loop         = false;
                        rockGolem.Sprite.UpdateSourceRect();
                        location.characters.Add(rockGolem);
                        return(randomTile);
                    }
                    else
                    {
                        int mineLevel;
                        if (Game1.player.CombatLevel > 1 && Game1.player.CombatLevel <= 4)
                        {
                            mineLevel = 41;
                        }
                        else if (Game1.player.CombatLevel > 4 && Game1.player.CombatLevel <= 8)
                        {
                            mineLevel = 100;
                        }
                        else if (Game1.player.CombatLevel > 8 && Game1.player.CombatLevel <= 10)
                        {
                            mineLevel = 140;
                        }
                        else
                        {
                            mineLevel = 200;
                        }

                        GreenSlime greenSlime = new GreenSlime(randomTile * Game1.tileSize, mineLevel)
                        {
                            focusedOnFarmers = true,
                        };
                        greenSlime.color.Value = Color.IndianRed;
                        location.characters.Add(greenSlime);

                        return(randomTile);
                    }
                }
            }

            return(Vector2.Zero);
        }
 /*********
 ** Public methods
 *********/
 /// <summary>Construct an instance.</summary>
 /// <param name="bush">The underlying bush.</param>
 /// <param name="location">The machine's in-game location.</param>
 public BushMachine(Bush bush, GameLocation location)
     : base(bush, location, GetTileAreaFor(bush))
 {
 }
示例#28
0
        private static void AdvanceCropOneStep(GameLocation loc, HoeDirt h, Vector2 position)
        {
            Crop currentCrop = h.crop;
            int  xPos        = (int)position.X;
            int  yPos        = (int)position.Y;

            if (currentCrop == null)
            {
                return;
            }

            //due to how this will be called, we do need to some checking
            if (!loc.IsGreenhouse && (currentCrop.dead.Value || !currentCrop.seasonsToGrowIn.Contains(Game1.currentSeason)))
            {
                currentCrop.dead.Value = true;
            }
            else
            {
                if (h.state.Value == HoeDirt.watered)
                {
                    //get the day of the current phase - if it's fully grown, we can just leave it here.
                    if (currentCrop.fullyGrown.Value)
                    {
                        currentCrop.dayOfCurrentPhase.Value -= 1;
                    }
                    else
                    {
                        //check to sere what the count of current days is

                        int phaseCount; //get the count of days in the current phase
                        if (currentCrop.phaseDays.Count > 0)
                        {
                            phaseCount = currentCrop.phaseDays[Math.Min(currentCrop.phaseDays.Count - 1, currentCrop.currentPhase.Value)];
                        }
                        else
                        {
                            phaseCount = 0;
                        }

                        currentCrop.dayOfCurrentPhase.Value = Math.Min(currentCrop.dayOfCurrentPhase.Value + 1, phaseCount);

                        //check phases
                        if (currentCrop.dayOfCurrentPhase.Value >= phaseCount && currentCrop.currentPhase.Value < currentCrop.phaseDays.Count - 1)
                        {
                            currentCrop.currentPhase.Value++;
                            currentCrop.dayOfCurrentPhase.Value = 0;
                        }

                        //skip negative day or 0 day crops.
                        while (currentCrop.currentPhase.Value < currentCrop.phaseDays.Count - 1 && currentCrop.phaseDays.Count > 0 && currentCrop.phaseDays[currentCrop.currentPhase.Value] <= 0)
                        {
                            currentCrop.currentPhase.Value++;
                        }

                        //handle wild crops
                        if (currentCrop.isWildSeedCrop() && currentCrop.phaseToShow.Value == -1 && currentCrop.currentPhase.Value > 0)
                        {
                            currentCrop.phaseToShow.Value = Game1.random.Next(1, 7);
                        }

                        //and now giant crops
                        double giantChance = new Random((int)Game1.uniqueIDForThisGame + (int)Game1.stats.daysPlayed + xPos * 2000 + yPos).NextDouble();

                        if (loc is Farm && currentCrop.currentPhase.Value == currentCrop.phaseDays.Count - 1 && IsValidGiantCrop(currentCrop.indexOfHarvest.Value) &&
                            giantChance <= 0.01)
                        {
                            for (int i = xPos - 1; i <= xPos + 1; i++)
                            {
                                for (int j = yPos - 1; j <= yPos + 1; j++)
                                {
                                    Vector2 tile = new Vector2(i, j);
                                    if (!loc.terrainFeatures.ContainsKey(tile) || !(loc.terrainFeatures[tile] is HoeDirt hDirt) ||
                                        hDirt?.crop?.indexOfHarvest == currentCrop.indexOfHarvest)
                                    {
                                        return; //no longer needs to process.
                                    }
                                }
                            }


                            //replace for giant crops.
                            for (int i = xPos - 1; i <= xPos + 1; i++)
                            {
                                for (int j = yPos - 1; j <= yPos + 1; j++)
                                {
                                    Vector2 tile = new Vector2(i, j);
                                    if (!(loc.terrainFeatures[tile] is null) && loc.terrainFeatures[tile] is HoeDirt hDirt)
                                    {
                                        hDirt.crop = null;
                                    }
                                }
                            }

                            if (loc is Farm f)
                            {
                                f.resourceClumps.Add(new GiantCrop(currentCrop.indexOfHarvest.Value, new Vector2(xPos - 1, yPos - 1)));
                            }
                        }
                    }
                }
                //process some edge cases for non watered crops.
                if (currentCrop.fullyGrown.Value && currentCrop.dayOfCurrentPhase.Value > 0 ||
                    currentCrop.currentPhase.Value < currentCrop.phaseDays.Count - 1 ||
                    !currentCrop.isWildSeedCrop())
                {
                    return; //stop processing
                }
                //replace wild crops**

                //remove any object here. o.O
                loc.objects.Remove(position);

                string season = Game1.currentSeason;
                switch (currentCrop.whichForageCrop.Value)
                {
                case 495:
                    season = "spring";
                    break;

                case 496:
                    season = "summer";
                    break;

                case 497:
                    season = "fall";
                    break;

                case 498:
                    season = "winter";
                    break;
                }
                loc.objects.Add(position, new SObject(position, currentCrop.getRandomWildCropForSeason(season), 1)
                {
                    IsSpawnedObject = true,
                    CanBeGrabbed    = true
                });

                //the normal iteration has a safe-call that isn't neded here
            }
        }
 /// <summary>Get whether the tool is currently enabled.</summary>
 /// <param name="player">The current player.</param>
 /// <param name="tool">The tool selected by the player (if any).</param>
 /// <param name="item">The item selected by the player (if any).</param>
 /// <param name="location">The current location.</param>
 public override bool IsEnabled(SFarmer player, Tool tool, Item item, GameLocation location)
 {
     return(this.Config.Enable && tool?.GetType().FullName == SeedBagAttachment.SeedBagTypeName);
 }
示例#30
0
 public EventArgsCurrentLocationChanged(GameLocation priorLocation, GameLocation newLocation)
 {
     NewLocation = newLocation;
     PriorLocation = priorLocation;
 }
        /// <summary>Apply the tool to the given tile.</summary>
        /// <param name="tile">The tile to modify.</param>
        /// <param name="tileObj">The object on the tile.</param>
        /// <param name="tileFeature">The feature on the tile.</param>
        /// <param name="player">The current player.</param>
        /// <param name="tool">The tool selected by the player (if any).</param>
        /// <param name="item">The item selected by the player (if any).</param>
        /// <param name="location">The current location.</param>
        public override bool Apply(Vector2 tile, SObject tileObj, TerrainFeature tileFeature, SFarmer player, Tool tool, Item item, GameLocation location)
        {
            // apply to plain dirt
            if (tileFeature is HoeDirt)
            {
                return(this.UseToolOnTile(tool, tile));
            }

            return(false);
        }
示例#32
0
        public override bool SayReceive(GameLiving source, string str)
        {
            if (!base.SayReceive(source, str))
                return false;

            string[] split = str.Split(' ');
            switch (split[0])
            {
                case "create":
                    ushort id = 286;

                    if (split.Length > 1)
                    {
                        try { id = ushort.Parse(split[1]); }
                        catch { }
                    }

                    m_instance = (Instance)WorldMgr.CreateInstance(id, typeof(Instance));
                    if (m_instance != null)
                        Say("Success, instance created.");
                    else
                        Say("Instance creation found errors.");

                    //Try and load a template from the db...
                    if (split.Length > 2)
                    {
                        string load = split[2];
                        Say("Trying to load instance '" + load + "' template from DB");
                        m_instance.LoadFromDatabase(load);
                    }

                    break;
                case "test":
                    if (m_instance == null)
                        Say("Instance is currently null.");
                    else
                    {
                        int x = 32361;
                        int y = 31744;
                        int z = 16003;
                        ushort heading = 1075;

                        if (m_instance.InstanceEntranceLocation != null)
                        {
                            x = m_instance.InstanceEntranceLocation.X;
                            y = m_instance.InstanceEntranceLocation.Y;
                            z = m_instance.InstanceEntranceLocation.Z;
                            heading = m_instance.InstanceEntranceLocation.Heading;
                        }

                        // save current position so player can use /instance exit
                        GameLocation saveLocation = new GameLocation(source.Name + "_exit", source.CurrentRegionID, source.X, source.Y, source.Z);
                        source.TempProperties.setProperty(saveLocation.Name, saveLocation);

                        Say("Instance ID " + m_instance.ID + ", Skin: " + m_instance.Skin + ", with " + m_instance.Zones.Count + " zones inside the region.");

                        if (!source.MoveTo(m_instance.ID, x, y, z, heading))
                        {
                            Say("Source could not be moved to instance entrance; MoveTo returned false.  Now trying to move to current location inside the instance.");

                            if (!source.MoveTo(m_instance.ID, source.X, source.Y, source.Z, source.Heading))
                            {
                                Say("Sorry, that failed as well.");
                            }
                        }
                    }
                    break;
            }
            return true;
        }
示例#33
0
        private void Display_RenderedWorld(object sender, RenderedWorldEventArgs e)
        {
            if (!Config.EnableMod || !isShredding)
            {
                return;
            }

            if (isIntro && introLength < timeShredded)
            {
                isIntro           = false;
                Game1.currentSong = Game1.soundBank.GetCue(currentSong);
            }

            keysPressed = new bool[] { Config.FretKey1.JustPressed(), Config.FretKey2.JustPressed(), Config.FretKey3.JustPressed(), Config.FretKey4.JustPressed() };
            for (int j = 0; j < 4; j++)
            {
                if (keysPressed[j])
                {
                    timePressed[j] = timeShredded;
                }
            }

            int width = (int)(currentData.noteScale * 16);

            float[] buttonSwells = new float[] { 1, 1, 1, 1 };
            for (int j = 0; j < 4; j++)
            {
                if (timePressed[j] == 0)
                {
                    continue;
                }
                if (timeShredded - timePressed[j] < Config.ButtonSwell / 2)
                {
                    buttonSwells[j] = 1 + (timeShredded - timePressed[j]) / width;
                }
                else if (timeShredded - timePressed[j] < Config.ButtonSwell)
                {
                    buttonSwells[j] = 1 + (Config.ButtonSwell - (timeShredded - timePressed[j])) / width;
                }
            }


            int barX = Game1.viewport.Width / 2 - barTexture.Width / 2;

            e.SpriteBatch.Draw(barTexture, new Vector2(barX, targetStart), null, Color.White);
            e.SpriteBatch.Draw(barTexture, new Vector2(barX, targetStart + width), null, Color.White);

            KeybindList[] keys = new KeybindList[] { Config.FretKey1, Config.FretKey2, Config.FretKey3, Config.FretKey4 };
            for (int j = 0; j < 4; j++)
            {
                Game1.drawDialogueBox(barX + width * j + width / 2 - 128, targetStart + width + width / 2 - 128, 256, 256, false, true, null, false, true, -1, -1, -1);
                e.SpriteBatch.DrawString(Game1.dialogueFont, keys[j].ToString(), new Vector2(barX + width * j + width / 2 - 16 * buttonSwells[j], targetStart + width + width / 2 - 16 * buttonSwells[j]), buttonSwells[j] > 1 ? Color.Green : Color.White, 0, Vector2.Zero, 2 * buttonSwells[j], SpriteEffects.None, 1);
            }

            bool stillShredding = false;
            bool nextNote       = false;

            for (int i = 0; i < currentData.beatDataList.Count; i++)
            {
                float notePos = timeShredded - currentData.noteScale * 16 * (i + 1);

                foreach (var note in currentData.beatDataList[i])
                {
                    var height = currentData.noteScale * 16 * note.length;
                    var yPos   = timeShredded - currentData.noteScale * 16 * (i + note.length);
                    if (yPos > Game1.viewport.Height)
                    {
                        continue;
                    }
                    stillShredding = true;
                    if (yPos <= -height || note.fret < 0)
                    {
                        continue;
                    }
                    var       xPos            = Game1.viewport.Width / 2 - currentData.noteScale * 16 * 4 / 2 + currentData.noteScale * 16 * note.fret;
                    Rectangle?sourceRectangle = new Rectangle?(GameLocation.getSourceRectForObject(note.index >= 0 ? note.index : currentData.defaultIconIndexes[note.fret]));
                    if (note.length > 1)
                    {
                        e.SpriteBatch.Draw(Game1.objectSpriteSheet, new Rectangle((int)xPos, (int)yPos, (int)width, (int)height), sourceRectangle, Color.White * 0.5f);
                    }
                    e.SpriteBatch.Draw(Game1.objectSpriteSheet, new Rectangle((int)xPos, (int)(yPos + height - width), (int)width, (int)width), sourceRectangle, Color.White);
                }
                if (!nextNote && notePos < targetStart + width / 2)
                {
                    nextNote = true;
                    for (int j = 0; j < keysPressed.Length; j++)
                    {
                        if (keysPressed[j])
                        {
                            var  noteScore = 0;
                            bool found     = false;
                            foreach (var note in currentData.beatDataList[i])
                            {
                                if (note.fret == j)
                                {
                                    noteScore += GetNoteScore(notePos);
                                    found      = true;
                                }
                            }
                            if (!found)
                            {
                                noteScore = currentData.missScore;
                            }
                            shredScore += noteScore;
                            Game1.player.currentLocation.debris.Add(new Debris(Math.Abs(noteScore), new Vector2((Game1.player.getStandingX() + Game1.random.Next(-100, 100)), Game1.player.getStandingY() + Game1.random.Next(100)), noteScore == currentData.perfectScore ? Color.Green : (noteScore > 0 ? Color.Yellow : Color.Red), 1f, Game1.player));
                        }
                    }
                }
            }
            e.SpriteBatch.DrawString(Game1.dialogueFont, $"Score: {shredScore}", new Vector2(Game1.viewport.Width / 2 + width * 2 + 64, targetStart + width / 2), Color.White, 0, Vector2.Zero, 2, SpriteEffects.None, 1f);


            timeShredded += currentData.speed;
            if (!stillShredding)
            {
                if (!highScores.TryGetValue(currentSong, out int highScore) || shredScore * 100 > highScore)
                {
                    highScores[currentSong] = shredScore;
                    Game1.addHUDMessage(new HUDMessage($"You got a new high score of {shredScore} for {Utility.getSongTitleFromCueName(currentSong)}!"));
                }
                Game1.player.canMove = true;
                isShredding          = false;
                currentData          = null;
                currentSong          = null;
                timeShredded         = 0;
            }
        }
示例#34
0
        public static void ScriptLoaded(DOLEvent e, object sender, EventArgs args)
        {
            if (!ServerProperties.Properties.LOAD_QUESTS)
                return;
            if (log.IsInfoEnabled)
                log.Info("Quest \"" + questTitle + "\" initializing ...");
            /* First thing we do in here is to search for the NPCs inside
                * the world who comes from the Albion realm. If we find a the players,
                * this means we don't have to create a new one.
                *
                * NOTE: You can do anything you want in this method, you don't have
                * to search for NPC's ... you could create a custom item, place it
                * on the ground and if a player picks it up, he will get the quest!
                * Just examples, do anything you like and feel comfortable with :)
                */

            #region DefineNPCs

            dalikor = GetDalikor();

            GameNPC[] npcs = WorldMgr.GetNPCsByName("Stor Gothi Annark", eRealm.Midgard);
            if (npcs.Length == 0)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Stor Gothi Annark, creating ...");
                annark = new GameNPC();
                annark.Model = 215;
                annark.Name = "Stor Gothi Annark";
                annark.GuildName = "Part of " + questTitle + " Quest";
                annark.Realm = eRealm.Midgard;
                annark.CurrentRegionID = 100;
                annark.Size = 51;
                annark.Level = 66;
                annark.X = 765357;
                annark.Y = 668790;
                annark.Z = 5759;
                annark.Heading = 7711;

                //annark.AddNPCEquipment((byte)eEquipmentItems.TORSO, 798, 0, 0, 0);
                //annark.AddNPCEquipment((byte)eEquipmentItems.RIGHT_HAND, 19, 0, 0, 0);

                annark.EquipmentTemplateID = "5100090";

                //You don't have to store the created mob in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    annark.SaveIntoDatabase();
                annark.AddToWorld();
            }
            else
                annark = npcs[0];

            npcs = WorldMgr.GetNPCsByName(LanguageMgr.GetTranslation(ServerProperties.Properties.SERV_LANGUAGE, "Mid.Frontiers.NPCScryerIdora"), eRealm.Midgard);
            if (npcs.Length == 0)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Scryer Idora, creating ...");
                idora = new GameNPC();
                idora.Model = 227;
                idora.Name = LanguageMgr.GetTranslation(ServerProperties.Properties.SERV_LANGUAGE, "Mid.Frontiers.NPCScryerIdora");
                idora.GuildName = "Part of " + questTitle + " Quest";
                idora.Realm = eRealm.Midgard;
                idora.CurrentRegionID = 234;
                idora.Size = 52;
                idora.Level = 50;
                idora.X = 558081;
                idora.Y = 573988;
                idora.Z = 8640;

                GameNpcInventoryTemplate template = new GameNpcInventoryTemplate();
                template.AddNPCEquipment(eInventorySlot.TorsoArmor, 81);
                template.AddNPCEquipment(eInventorySlot.LegsArmor, 82);
                template.AddNPCEquipment(eInventorySlot.FeetArmor, 84);
                template.AddNPCEquipment(eInventorySlot.Cloak, 91);
                template.AddNPCEquipment(eInventorySlot.RightHandWeapon, 3);
                idora.Inventory = template.CloseTemplate();
                idora.SwitchWeapon(GameLiving.eActiveWeaponSlot.Standard);

            //				idora.AddNPCEquipment(Slot.TORSO, 81, 0, 0, 0);
            //				idora.AddNPCEquipment(Slot.LEGS, 82, 0, 0, 0);
            //				idora.AddNPCEquipment(Slot.FEET, 84, 0, 0, 0);
            //				idora.AddNPCEquipment(Slot.CLOAK, 91, 0, 0, 0);
            //				idora.AddNPCEquipment(Slot.RIGHTHAND, 3, 0, 0, 0);

                idora.Heading = 1558;
                idora.MaxSpeedBase = 200;
                idora.EquipmentTemplateID = "200292";

                StandardMobBrain brain = new StandardMobBrain();
                brain.AggroLevel = 0;
                brain.AggroRange = 500;
                idora.SetOwnBrain(brain);

                //You don't have to store the created mob in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    idora.SaveIntoDatabase();
                idora.AddToWorld();
            }
            else
                idora = npcs[0];

            Point2D point = idora.GetPointFromHeading( idora.Heading, 30 );
            locationIdora = new GameLocation(idora.CurrentZone.Description, idora.CurrentRegionID, point.X, point.Y, idora.Z);

            ticketToSvasudFaste = CreateTicketTo("Svasud Faste", "hs_mularn_svasudfaste");
            ticketToMularn = CreateTicketTo("Mularn", "hs_svasudfaste_mularn");

            npcs = (GameNPC[])WorldMgr.GetObjectsByName(LanguageMgr.GetTranslation(ServerProperties.Properties.SERV_LANGUAGE, "Mid.Frontiers.NPCGriffinHandlerNjiedi"), eRealm.Midgard, typeof(GameStableMaster));
            if (npcs.Length == 0)
            {
                njiedi = new GameStableMaster();
                njiedi.Model = 158;
                njiedi.Name = LanguageMgr.GetTranslation(ServerProperties.Properties.SERV_LANGUAGE, "Mid.Frontiers.NPCGriffinHandlerNjiedi");

                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + njiedi.Name + ", creating ...");
                njiedi.GuildName = "Stable Master";
                njiedi.Realm = eRealm.Midgard;
                njiedi.CurrentRegionID = 100;
                njiedi.Size = 51;
                njiedi.Level = 50;

                GameNpcInventoryTemplate template = new GameNpcInventoryTemplate();
                template.AddNPCEquipment(eInventorySlot.TorsoArmor, 81, 10);
                template.AddNPCEquipment(eInventorySlot.LegsArmor, 82, 10);
                template.AddNPCEquipment(eInventorySlot.FeetArmor, 84, 10);
                template.AddNPCEquipment(eInventorySlot.Cloak, 57, 32);
                njiedi.Inventory = template.CloseTemplate();

            //				njiedi.AddNPCEquipment(Slot.TORSO, 81, 10, 0, 0);
            //				njiedi.AddNPCEquipment(Slot.LEGS, 82, 10, 0, 0);
            //				njiedi.AddNPCEquipment(Slot.FEET, 84, 10, 0, 0);
            //				njiedi.AddNPCEquipment(Slot.CLOAK, 57, 32, 0, 0);

                njiedi.X = GameLocation.ConvertLocalXToGlobalX(55561, 100);
                njiedi.Y = GameLocation.ConvertLocalYToGlobalY(58225, 100);
                njiedi.Z = 5005;
                njiedi.Heading = 126;

                StandardMobBrain brain = new StandardMobBrain();
                brain.AggroLevel = 0;
                brain.AggroRange = 0;
                njiedi.SetOwnBrain(brain);

                //You don't have to store the created mob in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                    njiedi.SaveIntoDatabase();
                njiedi.AddToWorld();
            }
            else
            {
                njiedi = npcs[0] as GameStableMaster;
            }

            njiedi.TradeItems = new MerchantTradeItems(null);
            if (!njiedi.TradeItems.AddTradeItem(1, eMerchantWindowSlot.FirstEmptyInPage, ticketToSvasudFaste))
                if (log.IsWarnEnabled)
                    log.Warn("ticketToSvasudFaste not added");

            foreach (GameNPC npc in njiedi.GetNPCsInRadius(400))
            {
                if (npc.Name == LanguageMgr.GetTranslation(ServerProperties.Properties.SERV_LANGUAGE, "Mid.Frontiers.NPCGryphon"))
                {
                    griffin = npc;
                    break;
                }
            }
            if (griffin == null)
            {
                griffin = new GameNPC();
                griffin.Model = 1236; // //819;
                griffin.Name = "tamed gryphon";

                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + griffin.Name + ", creating ...");
                griffin.GuildName = "Part of " + questTitle + " Quest";
                griffin.Realm = eRealm.Midgard;
                griffin.CurrentRegionID = njiedi.CurrentRegionID;
                griffin.Size = 50;
                griffin.Level = 50;
                griffin.X = njiedi.X + 80;
                griffin.Y = njiedi.Y + 100;
                griffin.Z = njiedi.Z;

                StandardMobBrain brain = new StandardMobBrain();
                brain.AggroLevel = 0;
                brain.AggroRange = 0;
                griffin.SetOwnBrain(brain);

                griffin.Heading = 93;
                griffin.MaxSpeedBase = 400;
                //dragonfly.EquipmentTemplateID = 200276;

                //You don't have to store the created mob in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database

                if (SAVE_INTO_DATABASE)
                {
                    griffin.SaveIntoDatabase();
                }
                griffin.AddToWorld();
            }

            npcs = (GameNPC[]) WorldMgr.GetObjectsByName("Vorgar", eRealm.Midgard, typeof (GameStableMaster));
            if (npcs.Length == 0)
            {
                vorgar = new GameStableMaster();
                vorgar.Model = 52;
                vorgar.Name = "Vorgar";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + vorgar.Name + ", creating ...");
                vorgar.GuildName = "Stable Master";
                vorgar.Realm = eRealm.Midgard;
                vorgar.CurrentRegionID = 100;
                vorgar.Size = 51;
                vorgar.Level = 50;
                vorgar.X = GameLocation.ConvertLocalXToGlobalX(10660, 100);
                vorgar.Y = GameLocation.ConvertLocalYToGlobalY(3437, 100);
                vorgar.Z = 5717;
                vorgar.Heading = 327;
                vorgar.MaxSpeedBase = 200;

                StandardMobBrain brain = new StandardMobBrain();
                brain.AggroLevel = 0;
                brain.AggroRange = 0;
                vorgar.SetOwnBrain(brain);

                //ulliam.EquipmentTemplateID = 200276;

                //You don't have to store the created mob in the db if you don't want,
                //it will be recreated each time it is not found, just comment the following
                //line if you rather not modify your database
                if (SAVE_INTO_DATABASE)
                {
                    vorgar.SaveIntoDatabase();
                }

                vorgar.AddToWorld();
            }
            else
                vorgar = npcs[0] as GameStableMaster;

            Point2D vorgarloc = vorgar.GetPointFromHeading( vorgar.Heading, 30 );
            locationVorgar = new GameLocation(vorgar.CurrentZone.Description, vorgar.CurrentRegionID, vorgarloc.X, vorgarloc.Y, vorgar.Z);

            #endregion

            #region DefineItems

            // item db check
            noteForNjiedi = GameServer.Database.FindObjectByKey<ItemTemplate>("njiedi_note");
            if (noteForNjiedi == null)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Could not find Njiedi's Note, creating it ...");
                noteForNjiedi = new ItemTemplate();
                noteForNjiedi.Name = "Njiedi's Note";

                noteForNjiedi.Weight = 3;
                noteForNjiedi.Model = 498;

                noteForNjiedi.Object_Type = (int) eObjectType.GenericItem;

                noteForNjiedi.Id_nb = "njiedi_note";
                noteForNjiedi.IsPickable = true;
                noteForNjiedi.IsDropable = false;

                GameServer.Database.AddObject(noteForNjiedi);
            }

            // item db check
            askefruerPlans = GameServer.Database.FindObjectByKey<ItemTemplate>("askefruer_plans");
            if (askefruerPlans == null)
            {
                askefruerPlans = new ItemTemplate();
                askefruerPlans.Name = "Askefruer Plans";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + askefruerPlans.Name + ", creating it ...");

                askefruerPlans.Weight = 3;
                askefruerPlans.Model = 498;

                askefruerPlans.Object_Type = (int) eObjectType.GenericItem;

                askefruerPlans.Id_nb = "askefruer_plans";
                askefruerPlans.IsPickable = true;
                askefruerPlans.IsDropable = false;

                GameServer.Database.AddObject(askefruerPlans);
            }

            translatedPlans = GameServer.Database.FindObjectByKey<ItemTemplate>("translated_askefruer_plans");
            if (translatedPlans == null)
            {
                translatedPlans = new ItemTemplate();
                translatedPlans.Name = "Translated Askefruer Plans";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + translatedPlans.Name + ", creating it ...");

                translatedPlans.Weight = 3;
                translatedPlans.Model = 498;

                translatedPlans.Object_Type = (int) eObjectType.GenericItem;

                translatedPlans.Id_nb = "translated_askefruer_plans";
                translatedPlans.IsPickable = true;
                translatedPlans.IsDropable = false;

                GameServer.Database.AddObject(translatedPlans);
            }

            // item db check
            recruitsLegs = GameServer.Database.FindObjectByKey<ItemTemplate>("recruits_studded_legs_mid");
            if (recruitsLegs == null)
            {
                recruitsLegs = new ItemTemplate();
                recruitsLegs.Name = "Recruit's Studded Legs (Mid)";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + recruitsLegs.Name + ", creating it ...");
                recruitsLegs.Level = 7;

                recruitsLegs.Weight = 42;
                recruitsLegs.Model = 82; // Studded Legs

                recruitsLegs.DPS_AF = 10; // Armour
                recruitsLegs.SPD_ABS = 19; // Absorption

                recruitsLegs.Object_Type = (int) eObjectType.Studded;
                recruitsLegs.Item_Type = (int) eEquipmentItems.LEGS;
                recruitsLegs.Id_nb = "recruits_studded_legs_mid";
                recruitsLegs.Price = Money.GetMoney(0,0,0,10,0);
                recruitsLegs.IsPickable = true;
                recruitsLegs.IsDropable = true;
                recruitsLegs.Color = 14; // blue leather

                recruitsLegs.Bonus = 5; // default bonus

                recruitsLegs.Bonus1 = 12;
                recruitsLegs.Bonus1Type = (int) eProperty.MaxHealth; // hit

                recruitsLegs.Bonus2 = 2;
                recruitsLegs.Bonus2Type = (int) eResist.Slash;

                recruitsLegs.Bonus3 = 1;
                recruitsLegs.Bonus3Type = (int) eResist.Cold;

                recruitsLegs.Quality = 100;
                recruitsLegs.Condition = 1000;
                recruitsLegs.MaxCondition = 1000;
                recruitsLegs.Durability = 1000;
                recruitsLegs.MaxDurability = 1000;

                GameServer.Database.AddObject(recruitsLegs);
            }

            // item db check
            recruitsPants = GameServer.Database.FindObjectByKey<ItemTemplate>("recruits_quilted_pants");
            if (recruitsPants == null)
            {
                recruitsPants = new ItemTemplate();
                recruitsPants.Name = "Recruit's Quilted Pants";
                if (log.IsWarnEnabled)
                    log.Warn("Could not find " + recruitsPants.Name + ", creating it ...");
                recruitsPants.Level = 7;

                recruitsPants.Weight = 14;
                recruitsPants.Model = 152; // cloth Legs

                recruitsPants.DPS_AF = 5; // Armour
                recruitsPants.SPD_ABS = 0; // Absorption

                recruitsPants.Object_Type = (int) eObjectType.Cloth;
                recruitsPants.Item_Type = (int) eEquipmentItems.LEGS;
                recruitsPants.Id_nb = "recruits_quilted_pants";
                recruitsPants.Price = Money.GetMoney(0,0,0,10,0);
                recruitsPants.IsPickable = true;
                recruitsPants.IsDropable = true;
                recruitsPants.Color = 36;

                recruitsPants.Bonus = 5; // default bonus

                recruitsPants.Bonus1 = 12;
                recruitsPants.Bonus1Type = (int) eProperty.MaxHealth; // hit

                recruitsPants.Bonus2 = 2;
                recruitsPants.Bonus2Type = (int) eResist.Slash;

                recruitsPants.Bonus3 = 1;
                recruitsPants.Bonus3Type = (int) eResist.Cold;

                recruitsPants.Quality = 100;
                recruitsPants.Condition = 1000;
                recruitsPants.MaxCondition = 1000;
                recruitsPants.Durability = 1000;
                recruitsPants.MaxDurability = 1000;

                GameServer.Database.AddObject(recruitsPants);
            }

            #endregion

            /* Now we add some hooks to the npc we found.
            * Actually, we want to know when a player interacts with him.
            * So, we hook the right-click (interact) and the whisper method
            * of npc and set the callback method to the "TalkToXXX"
            * method. This means, the "TalkToXXX" method is called whenever
            * a player right clicks on him or when he whispers to him.
            */
            //We want to be notified whenever a player enters the world
            GameEventMgr.AddHandler(GamePlayerEvent.AcceptQuest, new DOLEventHandler(SubscribeQuest));
            GameEventMgr.AddHandler(GamePlayerEvent.DeclineQuest, new DOLEventHandler(SubscribeQuest));

            GameEventMgr.AddHandler(GamePlayerEvent.GameEntered, new DOLEventHandler(PlayerEnterWorld));

            GameEventMgr.AddHandler(dalikor, GameLivingEvent.Interact, new DOLEventHandler(TalkToDalikor));
            GameEventMgr.AddHandler(dalikor, GameLivingEvent.WhisperReceive, new DOLEventHandler(TalkToDalikor));

            GameEventMgr.AddHandler(annark, GameObjectEvent.Interact, new DOLEventHandler(TalkToAnnark));

            GameEventMgr.AddHandler(njiedi, GameObjectEvent.Interact, new DOLEventHandler(TalkToNjiedi));

            GameEventMgr.AddHandler(idora, GameObjectEvent.Interact, new DOLEventHandler(TalkToIdora));
            GameEventMgr.AddHandler(idora, GameLivingEvent.WhisperReceive, new DOLEventHandler(TalkToIdora));

            GameEventMgr.AddHandler(vorgar, GameObjectEvent.Interact, new DOLEventHandler(TalkToVorgar));
            GameEventMgr.AddHandler(vorgar, GameLivingEvent.WhisperReceive, new DOLEventHandler(TalkToVorgar));

            /* Now we bring to dalikor the possibility to give this quest to players */
            dalikor.AddQuestToGive(typeof (Frontiers));

            if (log.IsInfoEnabled)
                if (log.IsInfoEnabled)
                    log.Info("Quest \"" + questTitle + "\" initialized");
        }
示例#35
0
        public static void addSpecificTemporarySprite(ref string key, ref GameLocation location)
        {
            if (key == "animalCompetition")
            {
                String outdoorsTextureName = null;
                switch (SDate.Now().Season)
                {
                case "spring":
                    outdoorsTextureName = spring_outdoorsTileSheetName;
                    break;

                case "summer":
                    outdoorsTextureName = summer_outdoorsTileSheetName;
                    break;

                case "fall":
                    outdoorsTextureName = fall_outdoorsTileSheetName;
                    break;

                case "winter":
                    outdoorsTextureName = winter_outdoorsTileSheetName;
                    break;
                }

                location.TemporarySprites.Add(new TemporaryAnimatedSprite(DataLoader.LooseSpritesName,
                                                                          new Rectangle(84, 0, 98, 79), 9999f, 1, 999,
                                                                          new Vector2(26f, 59f) * (float)Game1.tileSize, false, false,
                                                                          (float)(59 * Game1.tileSize) / 10000f, 0.0f, Color.White,
                                                                          (float)Game1.pixelZoom, 0.0f, 0.0f, 0.0f, false));

                //Outdoors
                Rectangle singleFeed = new Rectangle(304, 144, 16, 32);
                Rectangle doubleFeed = new Rectangle(320, 128, 32, 32);
                Rectangle water      = new Rectangle(288, 112, 32, 32);
                Rectangle create     = new Rectangle(288, 144, 16, 32);
                //LooseSprites
                Rectangle TopLeft      = new Rectangle(0, 44, 16, 16);
                Rectangle TopCenter    = new Rectangle(16, 44, 16, 16);
                Rectangle TopRight     = new Rectangle(32, 44, 16, 16);
                Rectangle CenterLeft   = new Rectangle(0, 60, 16, 16);
                Rectangle CenterCenter = new Rectangle(16, 60, 16, 16);
                Rectangle CenterRight  = new Rectangle(32, 60, 16, 16);
                Rectangle BottonLeft   = new Rectangle(0, 76, 16, 16);
                Rectangle BottonCenter = new Rectangle(16, 76, 16, 16);
                Rectangle BottonRight  = new Rectangle(32, 76, 16, 16);

                Rectangle LeftUp    = new Rectangle(48, 44, 16, 16);
                Rectangle RightUp   = new Rectangle(64, 44, 16, 16);
                Rectangle LeftDown  = new Rectangle(48, 60, 16, 16);
                Rectangle RightDown = new Rectangle(64, 60, 16, 16);

                addTemporarySprite(location, outdoorsTextureName, doubleFeed, 24, 62);
                addTemporarySprite(location, outdoorsTextureName, water, 32, 62);
                addTemporarySprite(location, outdoorsTextureName, singleFeed, 34, 62);
                addTemporarySprite(location, outdoorsTextureName, create, 23, 62);

                addTemporarySprite(location, DataLoader.LooseSpritesName, TopLeft, 26, 64);
                addTemporarySprite(location, DataLoader.LooseSpritesName, TopCenter, 27, 64);
                addTemporarySprite(location, DataLoader.LooseSpritesName, TopCenter, 28, 64);
                addTemporarySprite(location, DataLoader.LooseSpritesName, TopCenter, 29, 64);
                addTemporarySprite(location, DataLoader.LooseSpritesName, TopCenter, 30, 64);
                addTemporarySprite(location, DataLoader.LooseSpritesName, TopRight, 31, 64);

                addTemporarySprite(location, DataLoader.LooseSpritesName, TopLeft, 25, 65);
                addTemporarySprite(location, DataLoader.LooseSpritesName, LeftUp, 26, 65);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 27, 65);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 28, 65);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 29, 65);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 30, 65);
                addTemporarySprite(location, DataLoader.LooseSpritesName, RightUp, 31, 65);
                addTemporarySprite(location, DataLoader.LooseSpritesName, TopRight, 32, 65);

                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterLeft, 25, 66);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 26, 66);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 27, 66);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 28, 66);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 29, 66);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 30, 66);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 31, 66);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterRight, 32, 66);

                addTemporarySprite(location, DataLoader.LooseSpritesName, BottonLeft, 25, 67);
                addTemporarySprite(location, DataLoader.LooseSpritesName, LeftDown, 26, 67);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 27, 67);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 28, 67);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 29, 67);
                addTemporarySprite(location, DataLoader.LooseSpritesName, CenterCenter, 30, 67);
                addTemporarySprite(location, DataLoader.LooseSpritesName, RightDown, 31, 67);
                addTemporarySprite(location, DataLoader.LooseSpritesName, BottonRight, 32, 67);

                addTemporarySprite(location, DataLoader.LooseSpritesName, BottonLeft, 26, 68);
                addTemporarySprite(location, DataLoader.LooseSpritesName, BottonCenter, 27, 68);
                addTemporarySprite(location, DataLoader.LooseSpritesName, BottonCenter, 28, 68);
                addTemporarySprite(location, DataLoader.LooseSpritesName, BottonCenter, 29, 68);
                addTemporarySprite(location, DataLoader.LooseSpritesName, BottonCenter, 30, 68);
                addTemporarySprite(location, DataLoader.LooseSpritesName, BottonRight, 31, 68);
            }
        }
示例#36
0
文件: gmappeal.cs 项目: mynew4/DAoC
        public void OnCommand(GameClient client, string[] args)
        {
            if (ServerProperties.Properties.DISABLE_APPEALSYSTEM)
            {
                AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.SystemDisabled"));
                return;
            }

            if (args.Length < 2)
            {
                DisplaySyntax(client);
                return;
            }

            switch (args[1])
            {

                #region gmappeal assist
                case "assist":
                    {
                        if (args.Length < 3)
                        {
                            DisplaySyntax(client);
                            return;
                        }
                        int result = 0;
                        string targetName = args[2];
                        GameClient targetClient = WorldMgr.GuessClientByPlayerNameAndRealm(targetName, 0, false, out result);
                        switch (result)
                        {
                            case 2: // name not unique
                                AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.NameNotUnique"));
                                return;
                            case 3: // exact match
                            case 4: // guessed name
                                break;
                        }

                        if (targetClient == null)
                        {

                            // nothing found
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.PlayerNotFound", targetName));
                            return;
                        }

                        DBAppeal appeal = AppealMgr.GetAppealByPlayerName(targetClient.Player.Name);
                        if (appeal != null)
                        {
                            if (appeal.Status != "Being Helped")
                            {
                                AppealMgr.ChangeStatus(client.Player.Name, targetClient.Player, appeal, "Being Helped");
                                string message = LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.RandMessage" + Util.Random(4), targetClient.Player.Name);
                                client.Player.TempProperties.setProperty("AppealAssist", targetClient.Player);
                                client.Player.SendPrivateMessage(targetClient.Player, message);
                                targetClient.Out.SendPlaySound(eSoundType.Craft, 0x04);
                                return;
                            }
                            else
                            {
                                AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.BeingHelped"));
                                break;
                            }
                        }
                        AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.DoesntHaveAppeal"));
                        break;
                    }
                #endregion gmappeal assist
                #region gmappeal view

                case "view":
                    {
                        if (args.Length < 3)
                        {
                            DisplaySyntax(client);
                            return;
                        }
                        int result = 0;
                        string targetName = args[2];
                        GameClient targetClient = WorldMgr.GuessClientByPlayerNameAndRealm(targetName, 0, false, out result);
                        switch (result)
                        {

                            case 2: // name not unique
                                AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.NameNotUnique"));
                                return;
                            case 3: // exact match
                            case 4: // guessed name
                                break;
                        }
                        if (targetClient == null)
                        {

                            // nothing found
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.PlayerNotFound", targetName));
                            return;
                        }
                        DBAppeal appeal = AppealMgr.GetAppealByPlayerName(targetClient.Player.Name);
                        if (appeal != null)
                        {
                            //Let's view it.
                            List<string> msg = new List<string>();
                            msg.Add("[Appeal]: " + appeal.Name + ", [Status]: " + appeal.Status + ", [Priority]: " + appeal.SeverityToName + " [Issue]: " + appeal.Text + ", [Time]: " + appeal.Timestamp + ".\n");
                            msg.Add("To assist them with the appeal use /gmappeal assist <player name>.\n");
                            msg.Add("To jump yourself to the player use /gmappeal jumpto.\n");
                            msg.Add("For a full list of possible commands, use /gmappeal (with no arguments)");
                            client.Out.SendCustomTextWindow("Viewing " + appeal.Name + "'s Appeal", msg);
                            return;
                        }
                        AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.DoesntHaveAppeal"));
                        break;
                    }
                #endregion gmappeal view
                #region gmappeal release
                case "release":
                    {
                        if (args.Length < 3)
                        {
                            DisplaySyntax(client);
                            return;
                        }
                        int result = 0;
                        string targetName = args[2];
                        GameClient targetClient = WorldMgr.GuessClientByPlayerNameAndRealm(targetName, 0, false, out result);
                        switch (result)
                        {
                            case 2: // name not unique
                                AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.NameNotUnique"));
                                return;
                            case 3: // exact match
                            case 4: // guessed name
                                break;
                        }

                        if (targetClient == null)
                        {

                            // nothing found
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.PlayerNotFound", targetName));
                            return;
                        }

                        DBAppeal appeal = AppealMgr.GetAppealByPlayerName(targetClient.Player.Name);
                        if (appeal != null)
                        {
                            if (appeal.Status == "Being Helped")
                            {
                                AppealMgr.ChangeStatus(client.Player.Name, targetClient.Player, appeal, "Open");
                                client.Player.TempProperties.removeProperty("AppealAssist");
                                return;
                            }
                            else
                            {
                                AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.NotBeingHelped"));
                                return;
                            }
                        }
                        AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.DoesntHaveAppeal"));
                        return;
                    }
                #endregion gmappeal release
                #region gmappeal list
                case "list":
                case "listall":
                    {

                        int low = 0;
                        int med = 0;
                        int high = 0;
                        int crit = 0;
                        string caption;
                        IList<DBAppeal> appeallist;
                        List<string> msg = new List<string>();

                        if (args[1] == "listall")
                        {
                            caption = "Offline and Online Player Appeals";
                            appeallist = AppealMgr.GetAllAppealsOffline();
                        }
                        else
                        {
                            caption = "Online Player Appeals";
                            appeallist = AppealMgr.GetAllAppeals();
                        }

                        if (appeallist.Count < 1 || appeallist == null)
                        {
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.NoAppealsinQueue"));
                            return;
                        }

                        foreach (DBAppeal a in appeallist)
                        {
                            switch (a.Severity)
                            {
                                case (int)AppealMgr.eSeverity.Low:
                                    low++;
                                    break;
                                case (int)AppealMgr.eSeverity.Medium:
                                    med++;
                                    break;
                                case (int)AppealMgr.eSeverity.High:
                                    high++;
                                    break;
                                case (int)AppealMgr.eSeverity.Critical:
                                    crit++;
                                    break;
                            }
                        }
                        int total = appeallist.Count;
                        msg.Add(LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.CurrentStaffAvailable", AppealMgr.StaffList.Count, total) + "\n");
                        msg.Add("Appeals ordered by severity: ");
                        msg.Add("Critical:" + crit + ", High:" + high + " Med:" + med + ", Low:" + low + ".\n");
                        if (crit > 0)
                        {
                            msg.Add("Critical priority appeals:\n");
                            foreach (DBAppeal a in appeallist)
                            {
                                if (a.Severity == (int)AppealMgr.eSeverity.Critical)
                                {
                                    msg.Add("[Name]: " + a.Name + ", [Status]: " + a.Status + ", [Priority]: " + a.SeverityToName + " [Issue]: " + a.Text + ", [Time]: " + a.Timestamp + ".\n");
                                }
                            }
                        }
                        if (high > 0)
                        {
                            msg.Add("High priority appeals:\n");
                            foreach (DBAppeal a in appeallist)
                            {
                                if (a.Severity == (int)AppealMgr.eSeverity.High)
                                {
                                    msg.Add("[Name]: " + a.Name + ", [Status]: " + a.Status + ", [Priority]: " + a.SeverityToName + ", [Issue]: " + a.Text + ", [Time]: " + a.Timestamp + ".\n");
                                }
                            }
                        }
                        if (med > 0)
                        {
                            msg.Add("Medium priority Appeals:\n");
                            foreach (DBAppeal a in appeallist)
                            {
                                if (a.Severity == (int)AppealMgr.eSeverity.Medium)
                                {
                                    msg.Add("[Name]: " + a.Name + ", [Status]: " + a.Status + ", [Priority]: " + a.SeverityToName + ", [Issue]: " + a.Text + ", [Time]: " + a.Timestamp + ".\n");
                                }
                            }
                        }
                        if (low > 0)
                        {
                            msg.Add("Low priority appeals:\n");
                            foreach (DBAppeal a in appeallist)
                            {
                                if (a.Severity == (int)AppealMgr.eSeverity.Low)
                                {
                                    msg.Add("[Name]: " + a.Name + ", [Status]: " + a.Status + ", [Priority]: " + a.SeverityToName + ", [Issue]: " + a.Text + ", [Time]: " + a.Timestamp + ".\n");
                                }
                            }
                        }
                        client.Out.SendCustomTextWindow(caption, msg);
                    }

                    break;
                #endregion gmappeal list
                #region gmappeal close
                case "close":
                    {
                        if (args.Length < 3)
                        {
                            DisplaySyntax(client);
                            return;
                        }
                        int result = 0;
                        string targetName = args[2];
                        GameClient targetClient = WorldMgr.GuessClientByPlayerNameAndRealm(targetName, 0, false, out result);
                        switch (result)
                        {
                            case 2: // name not unique
                                AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.NameNotUnique"));
                                return;
                            case 3: // exact match
                            case 4: // guessed name
                                break;
                        }

                        if (targetClient == null)
                        {

                            // nothing found
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.PlayerNotFound", targetName));
                            return;
                        }

                        DBAppeal appeal = AppealMgr.GetAppealByPlayerName(targetClient.Player.Name);
                        if (appeal == null)
                        {
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.DoesntHaveAppeal"));
                            return;
                        }
                        AppealMgr.CloseAppeal(client.Player.Name, targetClient.Player, appeal);
                        client.Player.TempProperties.removeProperty("AppealAssist");
                        return;
                    }

                #endregion gmappeal close
                #region gmappeal closeoffline
                case "closeoffline":
                    {
                        if (args.Length < 3)
                        {
                            DisplaySyntax(client);
                            return;
                        }
                        string targetName = args[2];
                        DBAppeal appeal = AppealMgr.GetAppealByPlayerName(targetName);
                        if (appeal == null)
                        {
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.CantFindAppeal"));
                            return;
                        }
                        AppealMgr.CloseAppeal(client.Player.Name, appeal);

                        //just incase the player is actually online let's check so we can handle it properly
                        string targetNameTwo = args[2];
                        int resultTwo = 0;
                        GameClient targetClient = WorldMgr.GuessClientByPlayerNameAndRealm(targetNameTwo, 0, false, out resultTwo);
                        switch (resultTwo)
                        {
                            case 2: // name not unique
                                AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.NameNotUnique"));
                                return;
                            case 3: // exact match
                            case 4: // guessed name
                                break;
                        }
                        if (targetClient == null)
                        {

                            // player isn't online so we're fine.
                            return;
                        }
                        else
                        {
                            //cleaning up the player since he really was online.
                            AppealMgr.MessageToClient(targetClient, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.StaffClosedYourAppeal", client.Player.Name));
                            targetClient.Out.SendPlaySound(eSoundType.Craft, 0x02);
                            targetClient.Player.TempProperties.setProperty("HasPendingAppeal", false);
                        }
                        return;
                    }

                #endregion gmappeal closeoffline
                #region gmappeal jumpto
                case "jumpto":
                    {
                        try
                        {
                            GamePlayer p = client.Player.TempProperties.getProperty<GamePlayer>("AppealAssist");
                            if (p.ObjectState == GameObject.eObjectState.Active)
                            {
                                GameLocation oldlocation = new GameLocation("old", client.Player.CurrentRegionID, client.Player.X, client.Player.Y, client.Player.Z);
                                client.Player.TempProperties.setProperty("AppealJumpOld", oldlocation);
                                client.Player.MoveTo(p.CurrentRegionID, p.X, p.Y, p.Z, p.Heading);
                            }
                            break;
                        }
                        catch
                        {
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.MustBeAssisting"));
                            break;
                        }
                    }
                case "jumpback":
                    {
                        GameLocation jumpback = client.Player.TempProperties.getProperty<GameLocation>("AppealJumpOld");

                        if (jumpback != null)
                        {
                            client.Player.MoveTo(jumpback);
                            //client.Player.TempProperties.removeProperty("AppealJumpOld");
                            break;
                        }
                        else
                        {
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.NoLocationToJump"));
                        }
                        break;
                    }

                #endregion gmappeal jumpto
                #region gmappeal mute
                case "mute":
                    {
                        bool mute = client.Player.TempProperties.getProperty<bool>("AppealMute");
                        if (mute == false)
                        {
                            client.Player.TempProperties.setProperty("AppealMute", true);
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.NoLongerReceiveMsg"));
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.UseCmdTurnBackOn"));
                            AppealMgr.StaffList.Remove(client.Player);
                        }
                        else
                        {
                            client.Player.TempProperties.setProperty("AppealMute", false);
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.NowReceiveMsg"));
                            AppealMgr.MessageToClient(client, LanguageMgr.GetTranslation(client.Account.Language, "Scripts.Players.Appeal.UseCmdTurnBackOff"));
                            AppealMgr.StaffList.Add(client.Player);
                        }

                        break;
                    }
                #endregion gmappeal mute
                #region gmappeal commands
                case "commands":
                case "cmds":
                case "help":
                    //List all the commands in a pop up window
                    List<string> helpmsg = new List<string>();
                    helpmsg.Add("Commands for server staff to assist players with their Appeals.");
                    helpmsg.Add("/gmappeal view <player name> - Views the appeal of a specific player.");
                    helpmsg.Add("/gmappeal list - Lists all the current Appeals from online players only, in a window.");
                    helpmsg.Add("/gmappeal listall - Will list Appeals of both offline and online players, in a window.");
                    helpmsg.Add("/gmappeal assist <player name> - Take ownership of the player's appeal and lets other staff know you are helping this player.");
                    helpmsg.Add("/gmappeal jumpto - Will jump you to the player you are currently assisting (must use /gmappeal assist first).");
                    helpmsg.Add("/gmappeal jumpback - Will jump you back to where you were after you've helped the player (must use /gmappeal jumpto first).");
                    helpmsg.Add("/gmappeal close <player name> - Closes the appeal and removes it from the queue.");
                    helpmsg.Add("/gmappeal closeoffline <player name> - Closes an appeal of a player who is not online.");
                    helpmsg.Add("/gmappeal release <player name> - Releases ownership of the player's appeal so someone else can help them.");
                    helpmsg.Add("/gmappeal mute - Toggles receiving appeal notices, for yourself, for this session.");
                    client.Out.SendCustomTextWindow("/gmappeal commands list", helpmsg);
                    break;
                #endregion gmappeal commands
                default:
                    {
                        DisplaySyntax(client);
                        return;
                    }
            }
            return;
        }
示例#37
0
 public override bool performToolAction(Tool t, GameLocation location)
 {
     return(base.performToolAction(t, location));
 }
示例#38
0
文件: BaseQuest.cs 项目: mynew4/DAoC
 protected virtual void TeleportTo(GameObject target, GameObject caster, GameLocation location)
 {
     TeleportTo(target, caster, location, 0, 0);
 }
示例#39
0
 public override bool performUseAction(GameLocation location)
 {
     return(base.performUseAction(location));
 }
示例#40
0
文件: BaseQuest.cs 项目: mynew4/DAoC
        protected virtual void TeleportTo(GameObject target, GameObject caster, GameLocation location, uint delay, int fuzzyLocation)
        {
            delay *= 100; // 1/10sec to milliseconds
            if (delay <= 0)
                delay = 1;
            m_animSpellObjectQueue.Enqueue(caster);
            m_animSpellTeleportTimerQueue.Enqueue(new RegionTimer(caster, new RegionTimerCallback(MakeAnimSpellSequence), (int)delay));

            m_animEmoteObjectQueue.Enqueue(target);
            m_animEmoteTeleportTimerQueue.Enqueue(new RegionTimer(target, new RegionTimerCallback(MakeAnimEmoteSequence), (int)delay + 2000));

            m_portObjectQueue.Enqueue(target);

            location.X += Util.Random(0 - fuzzyLocation, fuzzyLocation);
            location.Y += Util.Random(0 - fuzzyLocation, fuzzyLocation);

            m_portDestinationQueue.Enqueue(location);
            m_portTeleportTimerQueue.Enqueue(new RegionTimer(target, new RegionTimerCallback(MakePortSequence), (int)delay + 3000));

            if (location.Name != null)
            {
                m_questPlayer.Out.SendMessage(LanguageMgr.GetTranslation(m_questPlayer.Client, "BaseQuest.TeleportTo.Text1", target.Name, location.Name), eChatType.CT_System, eChatLoc.CL_SystemWindow);
            }
        }
示例#41
0
        /// <summary>The prefix for the <see cref="Object.drawPlacementBounds(SpriteBatch, GameLocation)"/> method.</summary>
        /// <param name="spriteBatch">The <see cref="SpriteBatch"/> to draw the placement bounds to.</param>
        /// <param name="location">The current game location.</param>
        /// <returns><see langword="false"/>, meaning the original method will not get ran.</returns>
        /// <remarks>This reimplements the original method so the object doesn't get drawn over the placement bounds when the object being placed is a custom tree's seed.<br/>The reason the object gets drawn over the placement bounds is because the custom tree seeds aren't categorised as seeds (as custom trees can use anything for their seed).</remarks>
        internal static bool DrawPlacementBoundsPrefix(SpriteBatch spriteBatch, GameLocation location, Object __instance)
        {
            // ensure object is placeable and not a wallpaper
            if (!__instance.isPlaceable() || __instance is Wallpaper)
            {
                return(false);
            }

            // get screen space coordinates of the placement tile (when using a mouse)
            var xScreen = (int)Game1.GetPlacementGrabTile().X * 64;
            var yScreen = (int)Game1.GetPlacementGrabTile().Y * 64;

            // get screen space cooridnates if the user is not using a mouse
            Game1.isCheckingNonMousePlacement = !Game1.IsPerformingMousePlacement();
            if (Game1.isCheckingNonMousePlacement)
            {
                var nearbyValidPlacementPosition = Utility.GetNearbyValidPlacementPosition(Game1.player, location, __instance, xScreen, yScreen);
                xScreen = (int)nearbyValidPlacementPosition.X;
                yScreen = (int)nearbyValidPlacementPosition.Y;
            }
            if (Utility.isThereAnObjectHereWhichAcceptsThisItem(location, __instance, xScreen, yScreen))
            {
                return(false);
            }
            Game1.isCheckingNonMousePlacement = false;

            // check if the object is placeable (either in the environment of a nearby object)
            var canPlaceHere = Utility.playerCanPlaceItemHere(location, __instance, xScreen, yScreen, Game1.player) ||
                               (Utility.isThereAnObjectHereWhichAcceptsThisItem(location, __instance, xScreen, yScreen) && Utility.withinRadiusOfPlayer(xScreen, yScreen, 1, Game1.player));

            // get the number of placement bounds to draw (if furniture is being drawn)
            var width  = 1;
            var height = 1;

            if (__instance is Furniture furniture)
            {
                width  = furniture.getTilesWide();
                height = furniture.getTilesHigh();
            }

            // draw placement boxs (the red / green box)
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    spriteBatch.Draw(
                        texture: Game1.mouseCursors,
                        position: new Vector2((xScreen / 64 + x) * 64 - Game1.viewport.X, (yScreen / 64 + y) * 64 - Game1.viewport.Y),
                        sourceRectangle: new Rectangle(canPlaceHere ? 194 : 210, 388, 16, 16),
                        color: Color.White,
                        rotation: 0f,
                        origin: Vector2.Zero,
                        scale: 4f,
                        effects: SpriteEffects.None,
                        layerDepth: 0.01f
                        );
                }
            }

            // draw the object over the placement bounds
            {
                // ensure object is either a big craftable or piece of furniture
                if (!__instance.bigCraftable && !(__instance is Furniture))
                {
                    return(false);
                }

                // ensure object isn't a seed or fertilizer (by category)
                if (__instance.category == Object.SeedsCategory || __instance.category == Object.fertilizerCategory)
                {
                    return(false);
                }

                // ensure object isn't a custom tree seed
                if (ModEntry.Instance.CustomTrees.Any(customTree => customTree.SeedId == __instance.ParentSheetIndex))
                {
                    return(false);
                }

                __instance.draw(spriteBatch, xScreen / 64, yScreen / 64, .5f);
                return(false);
            }
        }
示例#42
0
 private static void Events_CurrentLocationChanged(GameLocation newLocation)
 {
     //SGame.CurrentLocation = null;
     //System.Threading.Thread.Sleep(10);
     #if DEBUG
     Console.WriteLine(newLocation.name);
     SGame.CurrentLocation = SGame.LoadOrCreateSGameLocationFromName(newLocation.name);
     #endif
     //Game1.currentLocation = SGame.CurrentLocation;
     //Log.LogComment(((SGameLocation) newLocation).name);
     //Log.LogComment("LOC CHANGED: " + SGame.currentLocation.name);
 }
示例#43
0
        /// <summary>The prefix for the <see cref="Object.placementAction(GameLocation, int, int, Farmer)"/> method.</summary>
        /// <param name="location">The current game location.</param>
        /// <param name="x">The X position of the cursor (screen space).</param>
        /// <param name="y">The Y position of the cursor (screen space).</param>
        /// <param name="__instance">The <see cref="Object"/> instance being patched.</param>
        /// <param name="__result">The return value of the method being patched (in this case whether a tree was successfully planted).</param>
        /// <returns><see langword="true"/> if the original method should get ran; otherwise, <see langword="false"/> (this depends on if the tree is custom).</returns>
        /// <remarks>This is used to allow custom tree seeds to be planted.</remarks>
        internal static bool PlacementActionPrefix(GameLocation location, int x, int y, Object __instance, ref bool __result)
        {
            var placementTile = new Vector2(x / 64, y / 64); // 64 = 16 (tile size) * 4 (tile scale)

            // ensure object trying to be placed isn't a big craftable or furniture (the original method should handle those)
            if (__instance.bigCraftable || __instance is Furniture)
            {
                //// handle placement logic for if object being paces is a tapper
                if (__instance.ParentSheetIndex != 105 && __instance.ParentSheetIndex != 264)
                {
                    return(true);
                }

                // ensure a tree exists at the placement location
                if (!location.terrainFeatures.ContainsKey(placementTile) || !(location.terrainFeatures[placementTile] is Tree tree))
                {
                    return(false);
                }

                // ensure tree is valid to receive a tapper
                if (tree.growthStage < 5 || tree.stump || location.Objects.ContainsKey(placementTile))
                {
                    return(false);
                }

                var isTreeCustom = ModEntry.Instance.Api.GetTreeById(tree.treeType, out var customTree);
                if (isTreeCustom && customTree.TappedProduct.ProductId == -1) // ensure there is a valid tapped product if the tree is custom
                {
                    return(false);
                }

                // place tapper
                var tapper = (Object)__instance.getOne();
                tapper.heldObject.Value   = null;
                tapper.tileLocation.Value = placementTile;
                location.Objects.Add(placementTile, tapper);
                tree.tapped.Value = true;
                tree.UpdateTapperProduct(tapper);
                location.playSound("axe");

                __result = true;
                return(false);
            }

            // try to get a tree whose seed is the object trying to be planted
            if (!ModEntry.Instance.CustomTrees.Any(tree => tree.SeedId == __instance.ParentSheetIndex)) // object being placed either isn't a tree or is a base game tree
            {
                return(true);
            }
            var customTreeFromSeed = ModEntry.Instance.CustomTrees.FirstOrDefault(tree => tree.SeedId == __instance.ParentSheetIndex);

            // ensure tree can be planted (checks tile data for NoSpawn spots etc)
            var canPlaceWildTreeSeed = typeof(Object).GetMethod("canPlaceWildTreeSeed", BindingFlags.NonPublic | BindingFlags.Instance);

            if (!(bool)canPlaceWildTreeSeed.Invoke(__instance, new object[] { location, placementTile }))
            {
                Game1.showRedMessage(Game1.content.LoadString("Strings\\StringsFromCSFiles:Object.cs.13021")); // "Invalid Position"
                __result = false;
                return(false);
            }

            // plant tree
            var newTree = new Tree(customTreeFromSeed.Id);

            newTree.modData[$"{ModEntry.Instance.ModManifest.UniqueID}/daysTillBarkHarvest"]       = "0";
            newTree.modData[$"{ModEntry.Instance.ModManifest.UniqueID}/daysTillNextShakeProducts"] = JsonConvert.SerializeObject(new int[customTreeFromSeed.ShakingProducts.Count]);

            location.terrainFeatures.Remove(placementTile);
            location.terrainFeatures.Add(placementTile, newTree);
            location.playSound("dirtyHit");
            __result = true;
            return(false);
        }
示例#44
0
        public void OnCommand(GameClient client, string[] args)
        {
			if (client.Player == null)
				return;

			GamePlayer player = client.Player;

			string key = GetInstanceKey(player);

			if (args.Length < 2)
            {
				if (key != "")
					SendMessage(client, "Current instance key is " + key);
					
				DisplaySyntax(client);
                return;
            }

            if (key == "" && args[1] != "key")
            {
                SendMessage(client, "You must first assign an instance to work with using /instance key <ID>.");
                return;
            }

            switch (args[1].ToLower())
            {
                #region SetInstanceID
                case "key":
					string newKey = string.Join(" ", args, 2, args.Length - 2);
                    client.Player.TempProperties.setProperty(INSTANCE_KEY, newKey);
					SendMessage(client, "Instance key set to " + newKey);
					break;
                #endregion
                #region Create Entry
                case "entry":
                    {
						try
						{
							if (args.Length < 3)
							{
								DisplaySyntax(client);
								return;
							}

							//Create the database entry...
							DBInstanceXElement element = new DBInstanceXElement();
							element.Heading = client.Player.Heading;
							element.X = client.Player.X;
							element.Y = client.Player.Y;
							element.Z = client.Player.Z;
							element.InstanceID = key;
							element.ClassType = args[2];

							int npctemplate = 0;

							try { npctemplate = int.Parse(args[3]); }
							catch { }

							element.NPCTemplate = npctemplate.ToString();

							if (npctemplate > 0)
							{
								// reload all templates to grab any new ones
								NpcTemplateMgr.Reload();
							}


							//Save the element to database!
							GameServer.Database.AddObject(element);
							GameServer.Database.SaveObject(element);

							//Dinberg: place a marker at this spot!
							string theType = args[2];

							SendMessage(client, "Created an element here! Use your memory for now, I sure as hell dont have anything else to show you where it is ^^");

							//Only create ones that have namespaces (signified by '.')
							if (theType.Contains("."))
							{
								SendMessage(client, "theType suspected to be a ClassType - attempting to invoke a marker of this class.");
								GameObject obj = null;

								//Now we have the classtype to create, create it thus!
								ArrayList asms = new ArrayList();
								asms.Add(typeof(GameServer).Assembly);
								asms.AddRange(ScriptMgr.Scripts);

								//This is required to ensure we check scripts for the space aswell, such as quests!
								foreach (Assembly asm in asms)
								{
									obj = (GameObject)(asm.CreateInstance(theType, false));
									if (obj != null)
										break;
								}

								if (args.Length == 4)
								{
									int templateID = 0;
									try { templateID = int.Parse(args[3]); }
									catch { }
									//If its an npc, load from the npc template about now.
									//By default, we ignore npctemplate if its set to 0.
									if ((GameNPC)obj != null && templateID != 0)
									{
										INpcTemplate npcTemplate = NpcTemplateMgr.GetTemplate(templateID);
										//we only want to load the template if one actually exists, or there could be trouble!
										if (npcTemplate != null)
										{
											((GameNPC)obj).LoadTemplate(npcTemplate);
										}
									}
								}

								//Add to world...
								obj.Name = element.ObjectId.Substring(0, 18);
								obj.GuildName = element.ObjectId.Substring(18);

								obj.X = element.X;
								obj.Y = element.Y;
								obj.Z = element.Z;
								obj.Heading = element.Heading;

								obj.CurrentRegion = client.Player.CurrentRegion;

								// now make sure model is visible
								if (obj is GameNPC && obj.Model == 0)
									obj.Model = 408; // red ball
								else if (obj is GameStaticItem && obj.Model == 0)
									obj.Model = 100; // bag

								if (!obj.AddToWorld())
									client.Out.SendMessage("Error: Object not added to world correctly!", eChatType.CT_Important, eChatLoc.CL_SystemWindow);
								else
									client.Out.SendMessage("Object added!", eChatType.CT_Say, eChatLoc.CL_SystemWindow);
							}
						}
						catch (Exception ex)
						{
							client.Out.SendMessage("An Exception has occurred when trying to add object, review server error logs! Exception: " + ex.Message, eChatType.CT_Important, eChatLoc.CL_SystemWindow);
							log.Error("Instance Entry Error", ex);
						}
                    }
                    break;
				#endregion
				#region remove
				case "remove":
                    {
                        GameObject obj = client.Player.TargetObject;
                        if (obj == null)
                            return;
                        string ObjectId = obj.Name + obj.GuildName;
                        DataObject o = GameServer.Database.FindObjectByKey<DBInstanceXElement>(ObjectId);

                        if (o == null)
                        {
                            client.Out.SendMessage("Could not find the entry in the database! <key=" + ObjectId + ">", eChatType.CT_Say, eChatLoc.CL_SystemWindow);
                            return;
                        }

                        GameServer.Database.DeleteObject(o);
                        client.Out.SendMessage("Object removed!", eChatType.CT_Say, eChatLoc.CL_SystemWindow);

                        //Remove object...
                        obj.RemoveFromWorld();
                        obj.Delete();
                        obj.DeleteFromDatabase();
                    }
                    break;
				#endregion
				#region create
				case "create":
					{
						if (player.CurrentRegion.IsInstance)
						{
							SendMessage(client, "You are already in an instance, use /instance exit to get out.");
							return;
						}

						try
						{
							if (args.Length < 3)
							{
								throw new Exception("You need to provide a skin id.  A skin is the ID of the region you want this instance to look like.");
							}

							Instance newInstance = player.TempProperties.getProperty<object>(key, null) as Instance;

							if (newInstance != null)
							{
								throw new Exception("You already have an instance '" + key + "' created, please close it before creating another.");
							}

							ushort skinID = Convert.ToUInt16(args[2]);

							newInstance = (Instance)WorldMgr.CreateInstance(skinID, typeof(Instance));

							if (newInstance == null)
							{
								SendMessage(client, "Instance creation failed.");
							}
							else
							{
								SendMessage(client, "Instance created, now loading elements for instance '" + key + "' from the DB.");
								newInstance.LoadFromDatabase(key);
								player.TempProperties.setProperty(key, newInstance);
							}
						}
						catch (Exception ex)
						{
							SendMessage(client, ex.Message);
							return;
						}
					}
					break;
				#endregion
				#region close
				case "close":
					{
						Instance newInstance = player.TempProperties.getProperty<object>(key, null) as Instance;

						if (newInstance == null)
						{
							SendMessage(client, "Can't find an instance to delete.");
						}
						else
						{
							player.TempProperties.removeProperty(key);
							newInstance.DestroyWhenEmpty = true;
							if (newInstance.NumPlayers == 0)
							{
								SendMessage(client, "Instance closed.");
							}
							else
							{
								SendMessage(client, "Instance will close once all players leave.");
							}
						}
					}
					break;
				#endregion
				#region test
				case "test":
					{
						if (player.CurrentRegion.IsInstance)
						{
							SendMessage(client, "You are already in an instance, use /instance exit to get out.");
							return;
						}

						Instance newInstance = player.TempProperties.getProperty<object>(key, null) as Instance;

						if (newInstance == null)
						{
							SendMessage(client, "Can't find an instance to test, you will need to create one first.");
						}
						else
						{
							// start with some generic coordinates that seem to work well in many instance zones
							int x = 32361;
							int y = 31744;
							int z = 16003;
							ushort heading = 1075;

							// If you're having trouble zoning into an instance then try adding an entrance element so it can be used here
							if (newInstance.InstanceEntranceLocation != null)
							{
								x = newInstance.InstanceEntranceLocation.X;
								y = newInstance.InstanceEntranceLocation.Y;
								z = newInstance.InstanceEntranceLocation.Z;
								heading = newInstance.InstanceEntranceLocation.Heading;
							}

							// save current position for use with /instance exit
							GameLocation saveLocation = new GameLocation(player.Name + "_exit", player.CurrentRegionID, player.X, player.Y, player.Z);
							player.TempProperties.setProperty(saveLocation.Name, saveLocation);

							bool success = true;

							if (!player.MoveTo(newInstance.ID, x, y, z, heading))
							{
								SendMessage(client, "MoveTo to entrance failed, now trying to move to current location inside the instance.");

								if (!player.MoveTo(newInstance.ID, player.X, player.Y, player.Z, player.Heading))
								{
									SendMessage(client, "That failed as well.  Either add an entrance to this instance or move in the world to a corresponding instance location.");
									success = false;
								}
							}

							if (success)
							{
								SendMessage(client, "Welcome to Instance ID " + newInstance.ID + ", Skin: " + newInstance.Skin + ", with " + newInstance.Zones.Count + " zones and " + newInstance.Objects.Length + " objects inside the region!");
								SendMessage(client, "Use '/instance exit' to leave if you get stuck.");
							}
						}
					}
					break;
				#endregion
				#region exit
				case "exit":
					{
						if (!player.CurrentRegion.IsInstance)
						{
							SendMessage(client, "You need to be in an instance to use this command.");
							return;
						}

						GameLocation saveLocation = player.TempProperties.getProperty<object>(player.Name + "_exit", null) as GameLocation;

						if (saveLocation == null)
						{
							ushort sourceRegion = (player.CurrentRegion as BaseInstance).Skin;

							if (!player.MoveTo(sourceRegion, player.X, player.Y, player.Z, player.Heading))
								player.MoveToBind();
						}
						else
						{
							player.MoveTo(saveLocation.RegionID, saveLocation.X, saveLocation.Y, saveLocation.Z, saveLocation.Heading);
						}
					}
					break;
				#endregion
			}

            return;
        }
示例#45
0
        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="worldAreas">The predefined world areas for <see cref="ChestRange.CurrentWorldArea"/>.</param>
        /// <param name="range">The range within which chests should be accessible.</param>
        /// <param name="currentLocation">The player's current location.</param>
        public RangeHandler(IDictionary <string, HashSet <string> > worldAreas, ChestRange range, GameLocation currentLocation)
        {
            this.Range = range;

            this.WorldAreaZones = new(() => this.GetWorldAreaZones(worldAreas));
            this.CurrentZone    = this.GetZone(currentLocation, range);
        }