From 179cb505571b278ea3e14454c811c54cb4e06e2a Mon Sep 17 00:00:00 2001 From: Kamron Batman <3953314+kamronbatman@users.noreply.github.com> Date: Mon, 11 Nov 2019 03:40:16 -0800 Subject: [PATCH] Updates Packets & Randomizer (#43) * Fixes a bug with the main loop. Removes unnecessary optimizations for RDRand. * WIP - Rewriting packets. * Cleanup and updates README * Converts more packets * Fixes header * Converts Effects packets. * Forgot the send command * Adds the start of containers packets. * Adds message packets with caching * Extends the send methods * Starts to add Acquire methods * Converted the packets * Cleanup * Cleanup * Adds more packets * Adds more packets * Fixes clearing arrays from pool. Adds Mobile Incoming * Converts more packets. * Moves more packets * Moves more packets * Test compression * Merges * Migrating to an idiomatic syntax that also supports compression, and proxying. * Optimize the stack alloc. Changes attributes * Converted container packets * Visual Studio doesn't auto save files. I am still getting used to subpar IDEs. * Adds static packet caching. Will profile later. Converts more packets * Fixes packets and changes how compression is configured * WIP - Adds basics for Gumps. Not finished though. * Fix file * Fixes formatting * Changed SpanWriter to be more idiomatic. * Fixes Span vs RawSpan and missing stackallocs * Converts over some more gumps * WIP - Deletes 32bit support. * Drops RDRand32 support. * Fixes gump compilation * Converting gump components * Removes old huffman compression function * Revert signature for backwards compatibility * WIP - Converting more gump components * Creates ArraySet for the strings. Updates AppendTo to reference that. * Converts the maining gump components * Cleans up gump components * Cleans up directives * Cleans up ArraySet and moves it. Adds null-coalescing-assignment * Cleanup, Target Packets, and C# 8 changes. * Removed OPL Packet * World packets * Fixing packet uses * Cleans up code. Fixes packet uses in various places. * More cleanup for packets * Code cleanup * Converts more packet uses and cleans up more code * More code cleanup * Finishes fixing the packets in Item * Updates secure trade packets * Updates core and gets it to compile. * Moved packets to scripts. Fixed account handler use of packets * Code cleanup * Updates chat packets * Code cleanuo * Adds party packets, but need to implement them. * Party packets WIP * Finishes party packets * Rearrange movement namespaces and classes * Finishes plant packets * Code Formatting * Fixes moving effects * Code cleanup, eliminates equipinfo * Adds more packets. Fixes bugs with various packets. * Finishes mahjon packets * Fixes mahjong packet * Code cleanup * Finishes mahjong packets * Adds Map packets * Add multifacet maps and charts * Cleans up some packets with UTF8 * Optimizes packets * Cleans up more packets. Moves the MessageHelper * Removes assistant support. Removes extended protocol. Incorporates MapUO packets as normal packets. * Updates protocol extensions packet receiver * Fixes a few bugs. Fixes a few more packets. * Code cleanup and fixing more packets * Fixes packet effects * Cleaned up more code * Buff Icon cleanup * Removed unused constructors * Code Cleanup. Adds BoatHS Packets * Moves house files. Updates house foundation packets. * Deployment cleanup * Fixes: * Code cleanup * More code cleanup * More code cleanup * Cleaned up BaseHouse * Enforces styling * Converts foreach to linq where possible. * Dont need that * Goals/Readme updates * Removes 32bit support at the highest level. Turns on HRT by default. * Code cleanup. Fixes extended features packet. * Fixes various bugs * Code cleanup * Code cleanup * Code cleanup. Fixes gump X/Y assignment. * Code cleanup using |= operator * More code cleanup * Cleanup * Fixes spacing issues. Thanks Visual Studio. You suck. * Compiler error * Fixes NPE from RunUO 2.7 * Renames ScriptCompiler to AssemblyHandler. Fixes packets. Updates README * Fixes more packets. Stupid trailing nulls. * Fixes various bugs. * Fixes for gumps * Fixes more gump stuff. Going to split it out later since it is getting insane * Recoded the gump writing * WIP * *Added output path of scripts project to dev branch *Activated debugging in code --- GOALS.md | 4 +- ModernUO.sln | 20 +- Projects/Scripts/Accounting/Account.cs | 1 + .../Accounting/AccountAttackLimiter.cs | 3 +- Projects/Scripts/Accounting/AccountHandler.cs | 61 +- Projects/Scripts/Accounting/Accounts.cs | 2 +- Projects/Scripts/Accounting/Firewall.cs | 4 +- Projects/Scripts/Commands/Add.cs | 2 +- Projects/Scripts/Commands/Batch.cs | 3 +- .../Scripts/Commands/BoundingBoxPicker.cs | 4 +- Projects/Scripts/Commands/ConvertPlayers.cs | 2 +- Projects/Scripts/Commands/Decorate.cs | 4 +- Projects/Scripts/Commands/DecorateMag.cs | 2 +- Projects/Scripts/Commands/Docs.cs | 52 +- Projects/Scripts/Commands/GenTeleporter.cs | 76 +- .../Commands/Generic/Commands/Commands.cs | 63 +- .../Commands/Generic/Commands/DesignInsert.cs | 6 +- .../Compilers/ConditionalCompiler.cs | 41 +- .../Generic/Extensions/DistinctExtension.cs | 3 +- .../Generic/Extensions/SortExtension.cs | 4 +- .../Implementors/BaseCommandImplementor.cs | 11 +- .../ContainedCommandImplementor.cs | 5 +- .../Implementors/GlobalCommandImplementor.cs | 11 +- .../Generic/Implementors/ObjectConditional.cs | 3 +- .../Implementors/RegionCommandImplementor.cs | 14 +- .../Implementors/SerialCommandImplementor.cs | 8 +- Projects/Scripts/Commands/Handlers.cs | 73 +- Projects/Scripts/Commands/HelpInfo.cs | 2 +- Projects/Scripts/Commands/Logging.cs | 2 +- Projects/Scripts/Commands/Properties.cs | 8 +- Projects/Scripts/Commands/ShardTime.cs | 4 +- Projects/Scripts/Commands/SignParser.cs | 17 +- Projects/Scripts/Commands/Skills.cs | 4 +- Projects/Scripts/Commands/SkillsMenu.cs | 4 +- Projects/Scripts/Commands/Statics.cs | 10 +- Projects/Scripts/Commands/VisibilityList.cs | 88 +- Projects/Scripts/Commands/Wipe.cs | 6 +- .../Context Menus/AddToSpellbookEntry.cs | 6 +- .../Engines/BulkOrders/Books/BOBGump.cs | 1 - .../Engines/BulkOrders/Books/BulkOrderBook.cs | 1 - .../Scripts/Engines/BulkOrders/LargeBOD.cs | 1 + .../Engines/BulkOrders/LargeTailorBOD.cs | 3 +- .../Scripts/Engines/BulkOrders/Rewards.cs | 52 +- .../CannedEvil/ChampionSkullBrazier.cs | 26 +- .../Engines/CannedEvil/ChampionSpawn.cs | 20 +- Projects/Scripts/Engines/Chat/Channel.cs | 14 +- Projects/Scripts/Engines/Chat/Chat.cs | 31 +- .../Engines/Chat/ChatActionHandlers.cs | 6 +- Projects/Scripts/Engines/Chat/ChatUser.cs | 28 +- Projects/Scripts/Engines/Chat/Chatold.cs | 4 +- Projects/Scripts/Engines/Chat/Packets.cs | 34 +- Projects/Scripts/Engines/ConPVP/Arena.cs | 13 +- .../Scripts/Engines/ConPVP/DuelContext.cs | 28 +- .../Engines/ConPVP/Games/BombingRun.cs | 53 +- Projects/Scripts/Engines/ConPVP/Games/CTF.cs | 40 +- .../Scripts/Engines/ConPVP/Games/DoubleDom.cs | 10 +- .../Engines/ConPVP/Games/KingOfTheHill.cs | 19 +- .../Engines/ConPVP/Games/TourneyMatch.cs | 2 +- .../Engines/ConPVP/Gumps/RulesetGump.cs | 4 +- .../Scripts/Engines/ConPVP/Participant.cs | 2 +- Projects/Scripts/Engines/ConPVP/Tournament.cs | 55 +- .../Scripts/Engines/Craft/Core/CraftItem.cs | 9 +- .../Scripts/Engines/Craft/Core/Recipes.cs | 10 +- Projects/Scripts/Engines/Craft/Core/Repair.cs | 4 +- Projects/Scripts/Engines/Craft/DefAlchemy.cs | 2 +- .../Scripts/Engines/Craft/DefBlacksmithy.cs | 2 +- .../Scripts/Engines/Craft/DefBowFletching.cs | 2 +- .../Scripts/Engines/Craft/DefCarpentry.cs | 2 +- .../Scripts/Engines/Craft/DefCartography.cs | 2 +- Projects/Scripts/Engines/Craft/DefCooking.cs | 2 +- .../Scripts/Engines/Craft/DefGlassblowing.cs | 2 +- .../Scripts/Engines/Craft/DefInscription.cs | 2 +- Projects/Scripts/Engines/Craft/DefMasonry.cs | 2 +- .../Scripts/Engines/Craft/DefTailoring.cs | 2 +- .../Scripts/Engines/Craft/DefTinkering.cs | 2 +- .../Doom/LeverPuzzle/LeverPuzzleController.cs | 22 +- .../Doom/LeverPuzzle/LeverPuzzleItems.cs | 2 +- .../Doom/LeverPuzzle/LeverPuzzleRegions.cs | 6 +- Projects/Scripts/Engines/Ethics/Core/Ethic.cs | 4 +- .../Engines/Ethics/Evil/Powers/Blight.cs | 8 +- .../Engines/Ethics/Evil/Powers/UnholySense.cs | 4 +- .../Engines/Ethics/Hero/Powers/Bless.cs | 8 +- .../Engines/Ethics/Hero/Powers/HolySense.cs | 4 +- .../Scripts/Engines/Factions/Core/Faction.cs | 86 +- .../Engines/Factions/Core/PlayerState.cs | 4 +- .../Power Faction Items/PowerFactionItem.cs | 7 +- .../Power Faction Items/UrnOfAscension.cs | 6 +- .../Factions/Items/Traps/BaseFactionTrap.cs | 35 +- .../Items/Traps/FactionExplosionTrap.cs | 2 +- .../Factions/Items/Traps/FactionSawTrap.cs | 6 +- .../Factions/Mobiles/Guards/GuardAI.cs | 6 +- Projects/Scripts/Engines/Harvest/Fishing.cs | 4 +- .../Scripts/Engines/Harvest/Lumberjacking.cs | 2 +- Projects/Scripts/Engines/Harvest/Mining.cs | 2 +- Projects/Scripts/Engines/Help/HelpGump.cs | 93 +- Projects/Scripts/Engines/Help/PagePrompt.cs | 10 +- .../Scripts/Engines/Help/PagePromptGump.cs | 6 +- Projects/Scripts/Engines/Help/PageQueue.cs | 2 - .../Scripts/Engines/Help/PageQueueGump.cs | 86 +- .../Scripts/Engines/Help/SpeechLogGump.cs | 2 - Projects/Scripts/Engines/Help/StuckMenu.cs | 6 +- .../Scripts/Engines/Khaldun/PuzzleChest.cs | 46 +- .../Engines/MLQuests/Gumps/RaceChangeGump.cs | 85 +- Projects/Scripts/Engines/MLQuests/MLQuest.cs | 15 +- .../Engines/MLQuests/MLQuestContext.cs | 24 +- .../Scripts/Engines/MLQuests/MLQuestEntry.cs | 41 +- .../Engines/MLQuests/MLQuestPersistence.cs | 5 +- .../Scripts/Engines/MLQuests/MLQuestSystem.cs | 21 +- .../Engines/MLQuests/Mobiles/BoonCollector.cs | 16 +- .../Engines/MLQuests/Mobiles/SirHelper.cs | 46 +- .../MLQuests/Objectives/EscortObjective.cs | 14 +- .../MLQuests/Objectives/KillObjective.cs | 26 +- .../Scripts/Engines/MLQuests/QuestArea.cs | 10 +- .../Scripts/Engines/MyRunUO/LayerComparer.cs | 81 + Projects/Scripts/Engines/Party/Packets.cs | 196 +- Projects/Scripts/Engines/Party/Party.cs | 199 +- .../Engines/Pathing/FastAStarAlgorithm.cs | 42 +- .../Scripts/Engines/Pathing/FastMovement.cs | 4 +- Projects/Scripts/Engines/Pathing/Movement.cs | 6 +- .../Scripts/Engines/Pathing/MovementPath.cs | 4 +- .../Scripts/Engines/Pathing/PathAlgorithm.cs | 4 +- .../Scripts/Engines/Pathing/PathFollower.cs | 3 +- .../Engines/Pathing/SlowAStarAlgorithm.cs | 37 +- .../Engines/Plants/EmptyTheBowlGump.cs | 2 +- .../Scripts/Engines/Plants/MainPlantGump.cs | 20 +- .../Plants/Network/DisplayHelpTopic.cs | 15 - Projects/Scripts/Engines/Plants/PlantItem.cs | 3 +- .../Scripts/Engines/Plants/PlantResources.cs | 13 +- .../Scripts/Engines/Plants/PlantSystem.cs | 1 + Projects/Scripts/Engines/Plants/PlantType.cs | 24 +- .../Scripts/Engines/Plants/PollinateTarget.cs | 22 +- .../Engines/Plants/ReproductionGump.cs | 15 +- .../Engines/Plants/SetToDecorativeGump.cs | 2 +- .../Quests/Collector/Items/Obsidian.cs | 17 +- .../Engines/Quests/Collector/Objectives.cs | 2 +- .../Quests/Core/Items/EnchantedSextant.cs | 13 +- .../Engines/Quests/Core/QuestSerializer.cs | 14 - .../Engines/Quests/Core/QuestSystem.cs | 4 +- .../Quests/Dark Tides/Items/KronusScroll.cs | 9 +- .../Quests/Dark Tides/Items/MaabusCoffin.cs | 6 +- .../Engines/Quests/Dark Tides/Objectives.cs | 2 +- .../Quests/Uzeraan Turmoil/Conversations.cs | 50 +- .../Items/SchmendrickApprenticeCorpse.cs | 30 +- .../Uzeraan Turmoil/Mobiles/MilitiaFighter.cs | 9 +- .../Quests/Uzeraan Turmoil/Objectives.cs | 76 +- .../Uzeraan Turmoil/UzeraanTurmoilQuest.cs | 5 +- .../Quests/Witch Apprentice/Ingredient.cs | 10 +- .../Items/HagApprenticeCorpse.cs | 4 +- .../Quests/Witch Apprentice/Objectives.cs | 55 +- Projects/Scripts/Engines/Spawner/Spawner.cs | 130 +- .../Scripts/Engines/Spawner/SpawnerGump.cs | 12 +- .../Character Statue Maker/CharacterStatue.cs | 46 +- .../Gumps/CharacterStatueGump.cs | 11 +- .../Character Statue Maker/Packets.cs | 33 +- .../VeteranRewards/RewardOptionGump.cs | 13 +- Projects/Scripts/Engines/Virtues/Honor.cs | 4 +- .../Scripts/Engines/Virtues/VirtueGump.cs | 18 +- .../Scripts/Engines/Virtues/VirtueInfoGump.cs | 4 +- .../Engines/Virtues/VirtueStatusGump.cs | 2 +- Projects/Scripts/Gumps/AdminGump.cs | 79 +- Projects/Scripts/Gumps/BaseConfirmGump.cs | 6 +- Projects/Scripts/Gumps/CategorizedAddGump.cs | 7 +- Projects/Scripts/Gumps/ClientGump.cs | 4 +- Projects/Scripts/Gumps/CommentsGump.cs | 7 +- Projects/Scripts/Gumps/ConfirmHouseResize.cs | 4 +- Projects/Scripts/Gumps/Go/GoGump.cs | 4 +- .../Scripts/Gumps/Guilds/DeclareFealtyGump.cs | 4 +- .../Gumps/Guilds/GrantGuildTitleGump.cs | 2 +- .../Scripts/Gumps/Guilds/GuildAbbrvPrompt.cs | 1 - .../Gumps/Guilds/GuildAcceptWarGump.cs | 2 +- .../Gumps/Guilds/GuildAdminCandidatesGump.cs | 2 +- .../Gumps/Guilds/GuildCandidatesGump.cs | 2 +- .../Gumps/Guilds/GuildChangeTypeGump.cs | 2 +- .../Scripts/Gumps/Guilds/GuildCharterGump.cs | 2 +- .../Gumps/Guilds/GuildCharterPrompt.cs | 1 - .../Gumps/Guilds/GuildDeclarePeaceGump.cs | 2 +- .../Gumps/Guilds/GuildDeclareWarGump.cs | 2 +- .../Gumps/Guilds/GuildDeclareWarPrompt.cs | 1 - .../Scripts/Gumps/Guilds/GuildDismissGump.cs | 2 +- .../Scripts/Gumps/Guilds/GuildNamePrompt.cs | 1 - .../Gumps/Guilds/GuildRejectWarGump.cs | 2 +- .../Guilds/GuildRescindDeclarationGump.cs | 2 +- .../Scripts/Gumps/Guilds/GuildRosterGump.cs | 2 +- .../Scripts/Gumps/Guilds/GuildTitlePrompt.cs | 1 - .../Scripts/Gumps/Guilds/GuildWarAdminGump.cs | 2 +- Projects/Scripts/Gumps/Guilds/GuildWarGump.cs | 2 +- .../Gumps/Guilds/GuildWebsitePrompt.cs | 1 - .../Scripts/Gumps/Guilds/GuildmasterGump.cs | 2 +- .../Guilds/New Guild System/BaseGuildGump.cs | 29 +- .../Guilds/New Guild System/OtherGuildInfo.cs | 67 - Projects/Scripts/Gumps/HouseDemolishGump.cs | 18 +- Projects/Scripts/Gumps/HouseGump.cs | 8 +- Projects/Scripts/Gumps/HouseGumpAOS.cs | 160 +- Projects/Scripts/Gumps/HouseTransferGump.cs | 2 +- Projects/Scripts/Gumps/PetResurrectGump.cs | 4 +- Projects/Scripts/Gumps/PlayerVendorGumps.cs | 19 +- Projects/Scripts/Gumps/PolymorphGump.cs | 2 +- Projects/Scripts/Gumps/Props/PropsGump.cs | 8 +- Projects/Scripts/Gumps/Props/SetBodyGump.cs | 30 +- Projects/Scripts/Gumps/Props/SetGump.cs | 1 - Projects/Scripts/Gumps/Props/SetObjectGump.cs | 1 - Projects/Scripts/Gumps/RunebookGump.cs | 5 +- Projects/Scripts/Gumps/SetSecureLevelGump.cs | 6 +- Projects/Scripts/Gumps/SkillsGump.cs | 1 - Projects/Scripts/Gumps/VendorRentalGumps.cs | 1 - .../Halloween/2006/Engines/TrickOrTreat.cs | 5 +- Projects/Scripts/Items/Addons/BallotBox.cs | 1 - .../Addons/ElvenSpinningwheelEastAddon.cs | 23 +- .../Addons/ElvenSpinningwheelSouthAddon.cs | 24 +- .../Items/Addons/FlourMillEastAddon.cs | 7 +- .../Items/Addons/FlourMillSouthAddon.cs | 7 +- Projects/Scripts/Items/Addons/JackOLantern.cs | 22 +- .../Items/Addons/SpinningwheelEastAddon.cs | 24 +- .../Items/Addons/SpinningwheelSouthAddon.cs | 24 +- Projects/Scripts/Items/Aquarium/Aquarium.cs | 9 +- Projects/Scripts/Items/Armor/BaseArmor.cs | 64 +- .../Items/Armor/Glasses/ElvenGlasses.cs | 10 +- Projects/Scripts/Items/Body Parts/Head.cs | 5 +- Projects/Scripts/Items/Books/BaseBook.cs | 124 +- Projects/Scripts/Items/Books/BrownBook.cs | 6 +- Projects/Scripts/Items/Books/Packets.cs | 80 + Projects/Scripts/Items/Books/RedBook.cs | 6 +- Projects/Scripts/Items/Books/TanBook.cs | 6 +- .../Scripts/Items/Clothing/BaseClothing.cs | 32 +- Projects/Scripts/Items/Clothing/Hats.cs | 1 - .../Scripts/Items/Containers/Container.cs | 51 +- .../Items/Containers/FillableContainers.cs | 16 +- .../Items/Containers/LockableContainer.cs | 4 +- .../Scripts/Items/Containers/SalvageBag.cs | 15 +- .../Items/Containers/TrappableContainer.cs | 10 +- .../Items/Containers/TreasureMapChest.cs | 69 +- .../Scripts/Items/Deeds/HairRestylingDeed.cs | 8 +- .../Scripts/Items/Deeds/HolidayTreeDeed.cs | 10 +- .../Items/Equipment/EquipmentInfoAttribute.cs | 15 + Projects/Scripts/Items/Equipment/Packets.cs | 56 + Projects/Scripts/Items/Food/CookableFood.cs | 39 +- Projects/Scripts/Items/Food/Cooking.cs | 28 +- Projects/Scripts/Items/Games/BaseBoard.cs | 10 +- Projects/Scripts/Items/Games/Dices.cs | 8 +- .../Items/Games/Mahjong/MahjongGame.cs | 4 +- .../Games/Mahjong/MahjongPacketHandlers.cs | 11 +- .../Items/Games/Mahjong/MahjongPlayers.cs | 98 +- .../Scripts/Items/Games/Mahjong/Packets.cs | 232 +- Projects/Scripts/Items/Guilds/GuildDeed.cs | 1 - Projects/Scripts/Items/Guilds/Guildstone.cs | 21 +- .../Scripts/Items/Maps/IndecipherableMap.cs | 10 +- Projects/Scripts/Items/Maps/MapItem.cs | 105 +- Projects/Scripts/Items/Maps/Packets.cs | 81 + Projects/Scripts/Items/Maps/PresetMap.cs | 4 +- Projects/Scripts/Items/Maps/TreasureMap.cs | 92 +- Projects/Scripts/Items/Misc/BankCheck.cs | 1 - Projects/Scripts/Items/Misc/Blocker.cs | 172 +- Projects/Scripts/Items/Misc/BulletinBoards.cs | 227 +- .../Items/Misc/CommunicationCrystals.cs | 10 +- Projects/Scripts/Items/Misc/Corpses/Corpse.cs | 84 +- .../Scripts/Items/Misc/Corpses/Packets.cs | 236 +- .../Scripts/Items/Misc/EffectController.cs | 4 +- Projects/Scripts/Items/Misc/EffectItem.cs | 2 +- Projects/Scripts/Items/Misc/Firebomb.cs | 3 +- Projects/Scripts/Items/Misc/Gold.cs | 1 - .../Scripts/Items/Misc/InteriorDecorator.cs | 6 +- Projects/Scripts/Items/Misc/Key.cs | 19 +- Projects/Scripts/Items/Misc/KeyRing.cs | 16 +- Projects/Scripts/Items/Misc/LOSBlocker.cs | 173 +- .../Items/Misc/PlayerBulletinBoards.cs | 1 - Projects/Scripts/Items/Misc/PowerGenerator.cs | 15 +- Projects/Scripts/Items/Misc/PublicMoongate.cs | 8 +- Projects/Scripts/Items/Misc/Teleporter.cs | 31 +- Projects/Scripts/Items/Misc/TrashBarrel.cs | 2 +- Projects/Scripts/Items/Misc/UnholyBone.cs | 2 +- Projects/Scripts/Items/Quivers/BaseQuiver.cs | 2 +- .../Items/Resources/Tailor/BoltOfCloth.cs | 6 +- .../Scripts/Items/Resources/Tailor/Cloth.cs | 5 +- .../Items/Resources/Tailor/Leathers.cs | 14 +- .../Items/Resources/Tailor/UncutCloth.cs | 5 +- .../Items/Skill Items/Camping/Campfire.cs | 2 +- .../Items/Skill Items/Fishing/Misc/SOS.cs | 18 +- .../Fishing/Misc/SpecialFishingNet.cs | 3 +- .../Harvest Tools/BaseHarvestTool.cs | 4 +- .../Skill Items/Magical/Misc/Moongate.cs | 4 +- .../Skill Items/Magical/Misc/RecallRune.cs | 1 - .../Explosion Potions/BaseExplosionPotion.cs | 5 +- .../Skill Items/Magical/Potions/NightSight.cs | 6 +- .../Items/Skill Items/Magical/Runebook.cs | 14 +- .../Items/Skill Items/Magical/Spellbook.cs | 51 +- .../Scripts/Items/Skill Items/Misc/Bandage.cs | 2 +- .../Items/Skill Items/Misc/FireHorn.cs | 9 +- .../Musical Instruments/BaseInstrument.cs | 9 +- .../Skill Items/Ninjitsu/LeatherNinjaBelt.cs | 25 +- .../Skill Items/Tailor Items/Misc/Dyes.cs | 1 - .../Skill Items/Thief/DisguisePersistance.cs | 7 +- .../Items/Skill Items/Tinkering/Spyglass.cs | 12 +- .../Dawn's Music Box/DawnsMusicBox.cs | 14 +- .../SacrificialAltar.cs | 2 +- .../Special/House Raffle/HouseRaffleStone.cs | 27 +- .../Items/Special/Solen Items/BagOfSending.cs | 30 +- .../Special/Solen Items/BallOfSummoning.cs | 18 +- .../Special/Solen Items/BraceletOfBinding.cs | 1 - Projects/Scripts/Items/Special/SoulStone.cs | 25 +- .../Special/Special Scrolls/PowerScroll.cs | 30 +- .../Special Scrolls/ScrollofAlacrity.cs | 15 +- .../Special Scrolls/ScrollofTranscendence.cs | 15 +- .../Special/Special Scrolls/SpecialScroll.cs | 2 +- .../Special/Special Scrolls/StatScroll.cs | 34 +- .../Veteran Rewards/AnkhOfSacrifice.cs | 9 +- .../Items/Special/Veteran Rewards/Brazier.cs | 3 +- .../Items/Special/Veteran Rewards/Cannon.cs | 88 +- .../Veteran Rewards/WeaponEngravingTool.cs | 6 +- .../Scripts/Items/Talismans/TalismanSlayer.cs | 13 +- .../Items/Talismans/TalismanSummons.cs | 19 +- Projects/Scripts/Items/Traps/GasTrap.cs | 4 +- .../Scripts/Items/Traps/GiantSpikeTrap.cs | 2 +- Projects/Scripts/Items/Traps/SawTrap.cs | 4 +- Projects/Scripts/Items/Traps/SpikeTrap.cs | 14 +- Projects/Scripts/Items/Traps/StoneFaceTrap.cs | 26 +- Projects/Scripts/Items/Wands/BaseWand.cs | 13 +- .../Items/Weapons/Abilities/WeaponAbility.cs | 90 +- Projects/Scripts/Items/Weapons/BaseWeapon.cs | 140 +- .../Items/Weapons/Maces/FireworksWand.cs | 2 +- .../Items/Weapons/Ranged/BaseRanged.cs | 2 +- .../Items/Weapons/Staves/ShepherdsCrook.cs | 7 +- Projects/Scripts/Misc/AOS.cs | 5 +- Projects/Scripts/Misc/AccountPrompt.cs | 7 +- Projects/Scripts/Misc/Animations.cs | 4 +- Projects/Scripts/Misc/AttackMessage.cs | 4 +- Projects/Scripts/Misc/AutoSave.cs | 4 +- Projects/Scripts/Misc/Broadcasts.cs | 2 +- Projects/Scripts/Misc/BuffIcons.cs | 198 +- Projects/Scripts/Misc/CharacterCreation.cs | 127 +- Projects/Scripts/Misc/Cleanup.cs | 6 +- Projects/Scripts/Misc/CurrentExpansion.cs | 4 +- Projects/Scripts/Misc/DoorGenerator.cs | 2 +- Projects/Scripts/Misc/Email.cs | 16 +- Projects/Scripts/Misc/Fastwalk.cs | 4 +- Projects/Scripts/Misc/Geometry.cs | 19 +- .../Gifts/Winter2004/PileOfGlacialSnow.cs | 6 +- Projects/Scripts/Misc/Guild.cs | 134 +- Projects/Scripts/Misc/Keywords.cs | 4 +- Projects/Scripts/Misc/LanguageStatistics.cs | 13 +- Projects/Scripts/Misc/LightCycle.cs | 12 +- Projects/Scripts/Misc/LoginStats.cs | 4 +- Projects/Scripts/Misc/MapDefinitions.cs | 11 +- Projects/Scripts/Misc/MapUO.cs | 158 +- .../Solen Items => Misc}/MessageHelper.cs | 8 +- Projects/Scripts/Misc/NameList.cs | 1 + Projects/Scripts/Misc/NameVerification.cs | 27 +- Projects/Scripts/Misc/Notoriety.cs | 28 +- Projects/Scripts/Misc/Paperdoll.cs | 11 +- Projects/Scripts/Misc/ProfanityProtection.cs | 5 +- Projects/Scripts/Misc/Profile.cs | 16 +- Projects/Scripts/Misc/ProtocolExtensions.cs | 44 +- Projects/Scripts/Misc/RaceDefinitions.cs | 81 +- Projects/Scripts/Misc/ServerList.cs | 87 +- Projects/Scripts/Misc/ShardPoller.cs | 5 +- Projects/Scripts/Misc/SkillCheck.cs | 2 +- Projects/Scripts/Misc/Titles.cs | 3 +- .../Scripts/Misc/TreasureMapProtection.cs | 4 +- Projects/Scripts/Misc/VendorGenerator.cs | 20 +- Projects/Scripts/Misc/Weather.cs | 1 + Projects/Scripts/Misc/WeightOverloading.cs | 21 +- Projects/Scripts/Mobiles/AI/AnimalAI.cs | 2 +- Projects/Scripts/Mobiles/AI/BaseAI.cs | 79 +- Projects/Scripts/Mobiles/AI/HealerAI.cs | 20 +- Projects/Scripts/Mobiles/AI/MageAI.cs | 15 +- .../Mobiles/Animals/Mounts/Ethereals.cs | 9 +- .../Scripts/Mobiles/Animals/Mounts/Kirin.cs | 2 +- Projects/Scripts/Mobiles/BaseCreature.cs | 252 +- .../Scripts/Mobiles/Familiars/HordeMinion.cs | 6 +- .../Scripts/Mobiles/Guards/ArcherGuard.cs | 2 +- Projects/Scripts/Mobiles/Guards/BaseGuard.cs | 8 +- .../Scripts/Mobiles/Guards/WarriorGuard.cs | 2 +- .../Monsters/Humanoid/Magic/SavageShaman.cs | 8 +- .../Humanoid/Melee/KhaldunRevenant.cs | 11 +- .../Humanoid/Melee/KhaldunSummoner.cs | 2 +- .../Monsters/Humanoid/Melee/KhaldunZealot.cs | 2 +- .../Mobiles/Monsters/ML/Special/Ilhenir.cs | 4 +- .../Monsters/Misc/Melee/PlagueBeastLord.cs | 3 +- .../Monsters/Misc/Melee/PlagueSpawn.cs | 3 +- .../Mobiles/Monsters/SE/DeathWatchBeetle.cs | 2 +- .../Scripts/Mobiles/Monsters/SE/FanDancer.cs | 9 +- Projects/Scripts/Mobiles/PlayerMobile.cs | 365 +- .../Scripts/Mobiles/Special/ChaosGuard.cs | 1 - Projects/Scripts/Mobiles/Special/Harrower.cs | 14 +- Projects/Scripts/Mobiles/Special/Mephitis.cs | 9 +- .../Scripts/Mobiles/Special/OrderGuard.cs | 1 - Projects/Scripts/Mobiles/Special/Semidar.cs | 3 +- Projects/Scripts/Mobiles/Townfolk/Banker.cs | 11 - .../Scripts/Mobiles/Townfolk/BrideGroom.cs | 7 +- .../Mobiles/Townfolk/EscortableMage.cs | 2 +- Projects/Scripts/Mobiles/Townfolk/Merchant.cs | 2 +- .../Scripts/Mobiles/Townfolk/Messenger.cs | 2 +- Projects/Scripts/Mobiles/Townfolk/Noble.cs | 2 +- Projects/Scripts/Mobiles/Townfolk/Peasant.cs | 2 +- .../Mobiles/Townfolk/SeekerOfAdventure.cs | 9 +- .../Scripts/Mobiles/Townfolk/TownCrier.cs | 9 +- .../Scripts/Mobiles/Vendors/BaseVendor.cs | 126 +- .../Mobiles/Vendors/NPC/AnimalTrainer.cs | 44 +- .../NPC/Guildmasters/BaseGuildmaster.cs | 31 +- .../Mobiles/Vendors/PlayerBarkeeper.cs | 3 +- .../Scripts/Mobiles/Vendors/PlayerVendor.cs | 27 +- .../Scripts/Mobiles/Vendors/RentedVendor.cs | 4 +- .../Mobiles/Vendors/VendorInventory.cs | 5 +- Projects/Scripts/Multis/Boats/BaseBoat.cs | 168 +- .../Multis/Boats/ConfirmDryDockGump.cs | 2 +- Projects/Scripts/Multis/Boats/Packets.cs | 127 + .../Scripts/Multis/Boats/RenameBoatPrompt.cs | 2 - Projects/Scripts/Multis/Boats/Strandedness.cs | 4 +- Projects/Scripts/Multis/DynamicDecay.cs | 2 +- .../Scripts/Multis/{ => Houses}/BaseHouse.cs | 447 +- Projects/Scripts/Multis/{ => Houses}/Deeds.cs | 15 +- .../Multis/{ => Houses}/HouseFoundation.cs | 232 +- .../Multis/{ => Houses}/HousePlacement.cs | 28 +- .../Multis/{ => Houses}/HousePlacementTool.cs | 32 +- .../Scripts/Multis/{ => Houses}/HouseSign.cs | 0 .../Multis/{ => Houses}/HouseTeleporter.cs | 0 .../Scripts/Multis/{ => Houses}/Houses.cs | 2 +- .../Multis/{ => Houses}/MovingCrate.cs | 23 +- Projects/Scripts/Multis/Houses/Packets.cs | 366 ++ .../Multis/{ => Houses}/PreviewHouse.cs | 0 Projects/Scripts/Network/Packets.cs | 24 + Projects/Scripts/Regions/GuardedRegion.cs | 15 +- .../Scripts/Regions/Spawning/SpawnEntry.cs | 4 +- .../Regions/Spawning/SpawnPersistence.cs | 5 +- Projects/Scripts/Scripts.csproj | 1 + Projects/Scripts/Skills/Anatomy.cs | 2 +- Projects/Scripts/Skills/AnimalTaming.cs | 6 +- Projects/Scripts/Skills/Discordance.cs | 5 +- Projects/Scripts/Skills/EvalInt.cs | 3 +- Projects/Scripts/Skills/Hiding.cs | 6 +- Projects/Scripts/Skills/ItemIdentification.cs | 8 +- Projects/Scripts/Skills/SpiritSpeak.cs | 2 +- Projects/Scripts/Skills/Tracking.cs | 4 +- .../SpecialSystems/Engines/TestCenter.cs | 18 +- .../SpecialSystems/Items/Stones/GMStone.cs | 56 - Projects/Scripts/Spells/Base/SpecialMove.cs | 16 +- Projects/Scripts/Spells/Base/SpellHelper.cs | 62 +- .../Scripts/Spells/Bushido/SamuraiSpell.cs | 4 +- .../Scripts/Spells/Chivalry/DispelEvil.cs | 2 +- .../Scripts/Spells/Chivalry/NobleSacrifice.cs | 12 +- .../Scripts/Spells/Chivalry/SacredJourney.cs | 20 - .../Scripts/Spells/Eighth/AirElemental.cs | 2 +- .../Scripts/Spells/Eighth/EarthElemental.cs | 2 +- .../Scripts/Spells/Eighth/FireElemental.cs | 2 +- .../Scripts/Spells/Eighth/SummonDaemon.cs | 2 +- .../Scripts/Spells/Eighth/WaterElemental.cs | 2 +- Projects/Scripts/Spells/Fifth/PoisonField.cs | 11 +- .../Scripts/Spells/Fifth/SummonCreature.cs | 2 +- Projects/Scripts/Spells/First/Clumsy.cs | 2 +- Projects/Scripts/Spells/First/Feeblemind.cs | 2 +- Projects/Scripts/Spells/First/NightSight.cs | 2 +- .../Scripts/Spells/First/ReactiveArmor.cs | 2 +- Projects/Scripts/Spells/First/Weaken.cs | 2 +- Projects/Scripts/Spells/Fourth/ArchCure.cs | 18 +- Projects/Scripts/Spells/Fourth/Curse.cs | 2 +- Projects/Scripts/Spells/Fourth/FireField.cs | 13 +- Projects/Scripts/Spells/Fourth/Lightning.cs | 2 +- .../Spells/Mysticism/HailStormSpell.cs | 8 +- .../Spells/Mysticism/NetherCycloneSpell.cs | 8 +- .../Spells/Mysticism/StoneFormSpell.cs | 3 +- .../Spells/Necromancy/BloodOathSpell.cs | 4 +- .../Scripts/Spells/Necromancy/Exorcism.cs | 5 +- .../Scripts/Spells/Necromancy/PainSpike.cs | 2 +- .../Scripts/Spells/Necromancy/Strangle.cs | 4 +- .../Scripts/Spells/Ninjitsu/AnimalForm.cs | 8 +- Projects/Scripts/Spells/Second/Agility.cs | 2 +- Projects/Scripts/Spells/Second/Cunning.cs | 2 +- Projects/Scripts/Spells/Second/Protection.cs | 2 +- Projects/Scripts/Spells/Second/Strength.cs | 2 +- .../Scripts/Spells/Seventh/ChainLightning.cs | 11 +- .../Scripts/Spells/Seventh/EnergyField.cs | 13 +- Projects/Scripts/Spells/Seventh/GateTravel.cs | 21 +- .../Scripts/Spells/Seventh/MeteorSwarm.cs | 7 +- Projects/Scripts/Spells/Seventh/Polymorph.cs | 1 - Projects/Scripts/Spells/Sixth/Mark.cs | 4 +- .../Scripts/Spells/Sixth/ParalyzeField.cs | 11 +- .../Spells/Spellweaving/AttuneWeapon.cs | 2 +- .../Spells/Spellweaving/EssenceOfWind.cs | 3 +- .../Scripts/Spells/Spellweaving/GiftOfLife.cs | 2 +- .../Spells/Spellweaving/GiftOfRenewal.cs | 2 +- .../Scripts/Spells/Spellweaving/ReaperForm.cs | 6 +- .../Spells/Spellweaving/Thunderstorm.cs | 2 +- .../Spells/Targeting/RecallSpellTarget.cs | 11 +- Projects/Scripts/Spells/Third/Bless.cs | 2 +- Projects/Scripts/Spells/Third/WallOfStone.cs | 11 +- Projects/Server/Diagnostics/BaseProfile.cs | 4 +- Projects/Server/Effects.cs | 301 +- Projects/Server/ExpansionInfo.cs | 3 +- Projects/Server/Geometry.cs | 6 +- Projects/Server/Guild.cs | 34 +- Projects/Server/Gumps/Gump.cs | 260 +- Projects/Server/Gumps/GumpAlphaRegion.cs | 61 +- Projects/Server/Gumps/GumpBackground.cs | 69 +- Projects/Server/Gumps/GumpButton.cs | 105 +- Projects/Server/Gumps/GumpCheck.cs | 89 +- Projects/Server/Gumps/GumpEntry.cs | 37 +- Projects/Server/Gumps/GumpGroup.cs | 25 +- Projects/Server/Gumps/GumpHtml.cs | 96 +- Projects/Server/Gumps/GumpHtmlLocalized.cs | 220 +- Projects/Server/Gumps/GumpImage.cs | 76 +- Projects/Server/Gumps/GumpImageTileButton.cs | 176 +- Projects/Server/Gumps/GumpImageTiled.cs | 73 +- Projects/Server/Gumps/GumpItem.cs | 73 +- Projects/Server/Gumps/GumpItemProperty.cs | 26 +- Projects/Server/Gumps/GumpLabel.cs | 63 +- Projects/Server/Gumps/GumpLabelCropped.cs | 88 +- Projects/Server/Gumps/GumpPage.cs | 26 +- Projects/Server/Gumps/GumpRadio.cs | 92 +- Projects/Server/Gumps/GumpTextEntry.cs | 104 +- Projects/Server/Gumps/GumpTextEntryLimited.cs | 110 +- Projects/Server/Gumps/GumpTooltip.cs | 26 +- Projects/Server/HuePicker.cs | 10 +- Projects/Server/IAccount.cs | 2 +- Projects/Server/Insensitive.cs | 14 +- Projects/Server/Interfaces.cs | 7 +- Projects/Server/Item.cs | 364 +- Projects/Server/Items/Container.cs | 63 +- Projects/Server/Items/Containers.cs | 9 +- Projects/Server/Items/SecureTradeContainer.cs | 1 - Projects/Server/Items/VirtualCheck.cs | 9 +- Projects/Server/Items/VirtualHair.cs | 20 +- Projects/Server/Layer.cs | 20 + Projects/Server/LightType.cs | 20 + Projects/Server/Main.cs | 144 +- Projects/Server/Map.cs | 147 +- Projects/Server/Menus/IMenu.cs | 4 +- Projects/Server/Menus/ItemListMenu.cs | 17 +- Projects/Server/Menus/QuestionMenu.cs | 17 +- Projects/Server/Mobile.cs | 2031 +++----- Projects/Server/Movement.cs | 2 +- Projects/Server/Network/Listener.cs | 13 +- Projects/Server/Network/NetState.cs | 134 +- Projects/Server/Network/Packet.cs | 267 -- Projects/Server/Network/PacketHandlers.cs | 536 +-- Projects/Server/Network/PacketReader.cs | 306 +- Projects/Server/Network/PacketWriter.cs | 346 -- Projects/Server/Network/Packets.cs | 4170 ----------------- Projects/Server/Network/Packets/Accounts.cs | 325 ++ Projects/Server/Network/Packets/Arrow.cs | 69 + Projects/Server/Network/Packets/Attributes.cs | 168 + Projects/Server/Network/Packets/Containers.cs | 217 + Projects/Server/Network/Packets/Damage.cs | 61 + Projects/Server/Network/Packets/Effects.cs | 283 ++ Projects/Server/Network/Packets/Gumps.cs | 94 + Projects/Server/Network/Packets/Items.cs | 330 ++ Projects/Server/Network/Packets/Map.cs | 72 + Projects/Server/Network/Packets/Menus.cs | 235 + Projects/Server/Network/Packets/Messages.cs | 161 + Projects/Server/Network/Packets/Mobiles.cs | 959 ++++ Projects/Server/Network/Packets/Player.cs | 550 +++ Projects/Server/Network/Packets/Profile.cs | 29 + Projects/Server/Network/Packets/Targeting.cs | 81 + Projects/Server/Network/Packets/Trade.cs | 139 + Projects/Server/Network/Packets/Vendors.cs | 207 + .../Server/Network/Packets/VirtualHair.cs | 78 + Projects/Server/Network/SendQueue.cs | 44 - Projects/Server/Network/ServerInfo.cs | 24 + Projects/Server/Network/SocketExtensions.cs | 4 +- .../Server/Network/StaticPacketHandlers.cs | 135 - Projects/Server/Notoriety.cs | 24 +- Projects/Server/ObjectPropertyList.cs | 138 +- .../Server/Persistence/BinaryMemoryWriter.cs | 2 +- .../Server/Persistence/DualSaveStrategy.cs | 2 +- .../Server/Persistence/DynamicSaveStrategy.cs | 3 +- Projects/Server/Persistence/FileOperations.cs | 14 +- Projects/Server/Persistence/FileQueue.cs | 15 +- .../Persistence/ParallelSaveStrategy.cs | 3 +- Projects/Server/Persistence/Persistence.cs | 2 +- .../Server/Persistence/QueuedMemoryWriter.cs | 2 +- Projects/Server/Persistence/SaveStrategy.cs | 2 +- .../Persistence/SequentialFileWriter.cs | 2 +- .../Persistence/StandardSaveStrategy.cs | 7 +- Projects/Server/Prompt.cs | 8 +- Projects/Server/QuestArrow.cs | 10 +- Projects/Server/Region.cs | 41 +- Projects/Server/Sector.cs | 3 +- Projects/Server/SecureTrade.cs | 93 +- Projects/Server/Serial.cs | 4 +- Projects/Server/Serialization.cs | 16 +- Projects/Server/Server.csproj | 4 + Projects/Server/Skills.cs | 6 +- Projects/Server/Targeting/MultiTarget.cs | 11 +- Projects/Server/Targeting/Target.cs | 6 +- Projects/Server/TileData.cs | 7 +- Projects/Server/TileMatrix.cs | 24 +- Projects/Server/Timer.cs | 38 +- Projects/Server/Utility.cs | 89 +- Projects/Server/VirtueInfo.cs | 5 +- Projects/Server/World.cs | 45 +- 588 files changed, 10843 insertions(+), 16177 deletions(-) create mode 100644 Projects/Scripts/Engines/MyRunUO/LayerComparer.cs delete mode 100644 Projects/Scripts/Engines/Plants/Network/DisplayHelpTopic.cs create mode 100644 Projects/Scripts/Items/Books/Packets.cs create mode 100644 Projects/Scripts/Items/Equipment/EquipmentInfoAttribute.cs create mode 100644 Projects/Scripts/Items/Equipment/Packets.cs create mode 100644 Projects/Scripts/Items/Maps/Packets.cs rename Projects/Scripts/{Items/Special/Solen Items => Misc}/MessageHelper.cs (58%) create mode 100644 Projects/Scripts/Multis/Boats/Packets.cs rename Projects/Scripts/Multis/{ => Houses}/BaseHouse.cs (88%) rename Projects/Scripts/Multis/{ => Houses}/Deeds.cs (94%) rename Projects/Scripts/Multis/{ => Houses}/HouseFoundation.cs (90%) rename Projects/Scripts/Multis/{ => Houses}/HousePlacement.cs (90%) rename Projects/Scripts/Multis/{ => Houses}/HousePlacementTool.cs (96%) rename Projects/Scripts/Multis/{ => Houses}/HouseSign.cs (100%) rename Projects/Scripts/Multis/{ => Houses}/HouseTeleporter.cs (100%) rename Projects/Scripts/Multis/{ => Houses}/Houses.cs (96%) rename Projects/Scripts/Multis/{ => Houses}/MovingCrate.cs (88%) create mode 100644 Projects/Scripts/Multis/Houses/Packets.cs rename Projects/Scripts/Multis/{ => Houses}/PreviewHouse.cs (100%) create mode 100644 Projects/Scripts/Network/Packets.cs delete mode 100644 Projects/Scripts/SpecialSystems/Items/Stones/GMStone.cs delete mode 100644 Projects/Server/Network/Packet.cs delete mode 100644 Projects/Server/Network/PacketWriter.cs delete mode 100644 Projects/Server/Network/Packets.cs create mode 100644 Projects/Server/Network/Packets/Accounts.cs create mode 100644 Projects/Server/Network/Packets/Arrow.cs create mode 100644 Projects/Server/Network/Packets/Attributes.cs create mode 100644 Projects/Server/Network/Packets/Containers.cs create mode 100644 Projects/Server/Network/Packets/Damage.cs create mode 100644 Projects/Server/Network/Packets/Effects.cs create mode 100644 Projects/Server/Network/Packets/Gumps.cs create mode 100644 Projects/Server/Network/Packets/Items.cs create mode 100644 Projects/Server/Network/Packets/Map.cs create mode 100644 Projects/Server/Network/Packets/Menus.cs create mode 100644 Projects/Server/Network/Packets/Messages.cs create mode 100644 Projects/Server/Network/Packets/Mobiles.cs create mode 100644 Projects/Server/Network/Packets/Player.cs create mode 100644 Projects/Server/Network/Packets/Profile.cs create mode 100644 Projects/Server/Network/Packets/Targeting.cs create mode 100644 Projects/Server/Network/Packets/Trade.cs create mode 100644 Projects/Server/Network/Packets/Vendors.cs create mode 100644 Projects/Server/Network/Packets/VirtualHair.cs delete mode 100644 Projects/Server/Network/SendQueue.cs create mode 100644 Projects/Server/Network/ServerInfo.cs delete mode 100644 Projects/Server/Network/StaticPacketHandlers.cs diff --git a/GOALS.md b/GOALS.md index c70e89d09..1e4b2d13f 100644 --- a/GOALS.md +++ b/GOALS.md @@ -7,8 +7,8 @@ - [X] Support configuration via a `modernuo.json` file ### Networking -- [ ] Replace Packet classes with functions -- [ ] Improve asynchronous socket handling using Pipes +- [X] Replace Packet classes with functions +- [X] Improve asynchronous socket handling using Pipes - [ ] Improve socket handling (2-5x) and event loop using libuv ### Administration diff --git a/ModernUO.sln b/ModernUO.sln index deab80f56..cdd102acb 100644 --- a/ModernUO.sln +++ b/ModernUO.sln @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.29102.190 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server", "Projects\Server\Server.csproj", "{5E93BB35-3661-4822-9A8A-859726BAD87F}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server", "Projects\Server\Server.csproj", "{9514A3D3-5C0F-4EE0-B168-67C3F50DC225}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Scripts", "Projects\Scripts\Scripts.csproj", "{83CF2484-BCCB-4B7C-9C5F-7AB43AEA5E8F}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Scripts", "Projects\Scripts\Scripts.csproj", "{BF29C43A-A539-448D-93DB-D7CBE13BACFE}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -13,14 +13,14 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5E93BB35-3661-4822-9A8A-859726BAD87F}.Debug|Any CPU.ActiveCfg = Release|Any CPU - {5E93BB35-3661-4822-9A8A-859726BAD87F}.Debug|Any CPU.Build.0 = Release|Any CPU - {5E93BB35-3661-4822-9A8A-859726BAD87F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5E93BB35-3661-4822-9A8A-859726BAD87F}.Release|Any CPU.Build.0 = Release|Any CPU - {83CF2484-BCCB-4B7C-9C5F-7AB43AEA5E8F}.Debug|Any CPU.ActiveCfg = Release|Any CPU - {83CF2484-BCCB-4B7C-9C5F-7AB43AEA5E8F}.Debug|Any CPU.Build.0 = Release|Any CPU - {83CF2484-BCCB-4B7C-9C5F-7AB43AEA5E8F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {83CF2484-BCCB-4B7C-9C5F-7AB43AEA5E8F}.Release|Any CPU.Build.0 = Release|Any CPU + {9514A3D3-5C0F-4EE0-B168-67C3F50DC225}.Debug|Any CPU.ActiveCfg = Release|Any CPU + {9514A3D3-5C0F-4EE0-B168-67C3F50DC225}.Debug|Any CPU.Build.0 = Release|Any CPU + {9514A3D3-5C0F-4EE0-B168-67C3F50DC225}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9514A3D3-5C0F-4EE0-B168-67C3F50DC225}.Release|Any CPU.Build.0 = Release|Any CPU + {BF29C43A-A539-448D-93DB-D7CBE13BACFE}.Debug|Any CPU.ActiveCfg = Release|Any CPU + {BF29C43A-A539-448D-93DB-D7CBE13BACFE}.Debug|Any CPU.Build.0 = Release|Any CPU + {BF29C43A-A539-448D-93DB-D7CBE13BACFE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BF29C43A-A539-448D-93DB-D7CBE13BACFE}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Projects/Scripts/Accounting/Account.cs b/Projects/Scripts/Accounting/Account.cs index 8ff0ab711..ced955f02 100644 --- a/Projects/Scripts/Accounting/Account.cs +++ b/Projects/Scripts/Accounting/Account.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; diff --git a/Projects/Scripts/Accounting/AccountAttackLimiter.cs b/Projects/Scripts/Accounting/AccountAttackLimiter.cs index f302c22f3..a5b797bca 100644 --- a/Projects/Scripts/Accounting/AccountAttackLimiter.cs +++ b/Projects/Scripts/Accounting/AccountAttackLimiter.cs @@ -61,8 +61,7 @@ namespace Server.Accounting InvalidAccountAccessLog accessLog = FindAccessLog(ns); - if (accessLog == null) - m_List.Add(accessLog = new InvalidAccountAccessLog(ns.Address)); + m_List.Add(accessLog ??= new InvalidAccountAccessLog(ns.Address)); accessLog.Counts += 1; accessLog.RefreshAccessTime(); diff --git a/Projects/Scripts/Accounting/AccountHandler.cs b/Projects/Scripts/Accounting/AccountHandler.cs index 31c131b6a..459b173bd 100644 --- a/Projects/Scripts/Accounting/AccountHandler.cs +++ b/Projects/Scripts/Accounting/AccountHandler.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Net; using Server.Accounting; using Server.Engines.Help; @@ -176,8 +177,8 @@ namespace Server.Misc from.SendLocalizedMessage(501234, "", 0x35); /* The next available Counselor/Game Master will respond as soon as possible. - * Please check your Journal for messages every few minutes. - */ + * Please check your Journal for messages every few minutes. + */ PageQueue.Enqueue(new PageEntry(from, $"[Automated: Change Password]Desired password: {pass}Current IP address: {ipAddress}Account IP address: {accessList[0]}", @@ -199,38 +200,27 @@ namespace Server.Misc if (!(state.Account is Account acct)) { state.Dispose(); + return; } - else if (index < 0 || index >= acct.Length) - { - state.Send(new DeleteResult(DeleteResultType.BadRequest)); - state.Send(new CharacterListUpdate(acct)); - } + + DeleteResultType deleteType; + + if (index < 0 || index >= acct.Length) + deleteType = DeleteResultType.BadRequest; else { Mobile m = acct[index]; if (m == null) - { - state.Send(new DeleteResult(DeleteResultType.CharNotExist)); - state.Send(new CharacterListUpdate(acct)); - } + deleteType = DeleteResultType.CharNotExist; else if (m.NetState != null) - { - state.Send(new DeleteResult(DeleteResultType.CharBeingPlayed)); - state.Send(new CharacterListUpdate(acct)); - } + deleteType = DeleteResultType.CharBeingPlayed; else if (RestrictDeletion && DateTime.UtcNow < m.CreationTime + DeleteDelay) - { - state.Send(new DeleteResult(DeleteResultType.CharTooYoung)); - state.Send(new CharacterListUpdate(acct)); - } + deleteType = DeleteResultType.CharTooYoung; else if (m.AccessLevel == AccessLevel.Player && Region.Find(m.LogoutLocation, m.LogoutMap).IsPartOf() ) //Don't need to check current location, if netstate is null, they're logged out - { - state.Send(new DeleteResult(DeleteResultType.BadRequest)); - state.Send(new CharacterListUpdate(acct)); - } + deleteType = DeleteResultType.BadRequest; else { Console.WriteLine("Client: {0}: Deleting character {1} (0x{2:X})", state, index, m.Serial.Value); @@ -238,27 +228,18 @@ namespace Server.Misc acct.Comments.Add(new AccountComment("System", $"Character #{index + 1} {m} deleted by {state}")); m.Delete(); - state.Send(new CharacterListUpdate(acct)); + Packets.SendCharacterListUpdate(state, acct); + return; } } + + Packets.SendDeleteResult(state, deleteType); + Packets.SendCharacterListUpdate(state, acct); } - public static bool CanCreate(IPAddress ip) - { - if (!IPTable.ContainsKey(ip)) - return true; + public static bool CanCreate(IPAddress ip) => !IPTable.ContainsKey(ip) || IPTable[ip] < MaxAccountsPerIP; - return IPTable[ip] < MaxAccountsPerIP; - } - - private static bool IsForbiddenChar(char c) - { - for (int i = 0; i < m_ForbiddenChars.Length; ++i) - if (c == m_ForbiddenChars[i]) - return true; - - return false; - } + private static bool IsForbiddenChar(char c) => m_ForbiddenChars.Any(t => c == t); private static Account CreateAccount(NetState state, string un, string pw) { @@ -377,9 +358,7 @@ namespace Server.Misc string pw = e.Password; if (!(Accounts.GetAccount(un) is Account acct)) - { e.Accepted = false; - } else if (!acct.HasAccess(e.State)) { Console.WriteLine("Login: {0}: Access denied for '{1}'", e.State, un); diff --git a/Projects/Scripts/Accounting/Accounts.cs b/Projects/Scripts/Accounting/Accounts.cs index 8bf7e5446..d5d01b165 100644 --- a/Projects/Scripts/Accounting/Accounts.cs +++ b/Projects/Scripts/Accounting/Accounts.cs @@ -90,4 +90,4 @@ namespace Server.Accounting xml.Close(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Accounting/Firewall.cs b/Projects/Scripts/Accounting/Firewall.cs index 4946ff9c6..d7de42822 100644 --- a/Projects/Scripts/Accounting/Firewall.cs +++ b/Projects/Scripts/Accounting/Firewall.cs @@ -191,9 +191,7 @@ namespace Server return otherAddress.Equals(m_Address); } else if (obj is IPFirewallEntry entry) - { return m_Address.Equals(entry.m_Address); - } return false; } @@ -246,7 +244,7 @@ namespace Server public WildcardIPFirewallEntry(string entry) => m_Entry = entry; - public bool IsBlocked(IPAddress address) + bool IFirewallEntry.IsBlocked(IPAddress address) { if (!m_Valid) return false; //Why process if it's invalid? it'll return false anyway after processing it. diff --git a/Projects/Scripts/Commands/Add.cs b/Projects/Scripts/Commands/Add.cs index 60e144037..9948d1c39 100644 --- a/Projects/Scripts/Commands/Add.cs +++ b/Projects/Scripts/Commands/Add.cs @@ -7,7 +7,7 @@ using CPA = Server.CommandPropertyAttribute; namespace Server.Commands { - public class Add + public static class Add { private static Type m_EntityType = typeof(IEntity); diff --git a/Projects/Scripts/Commands/Batch.cs b/Projects/Scripts/Commands/Batch.cs index 89e703c5e..9abef7a59 100644 --- a/Projects/Scripts/Commands/Batch.cs +++ b/Projects/Scripts/Commands/Batch.cs @@ -120,8 +120,7 @@ namespace Server.Commands command.ExecuteList(eventArgs[i], usedList); - if (list.Count > 20) - CommandLogging.Enabled = true; + CommandLogging.Enabled |= list.Count > 20; command.Flush(e.Mobile, list.Count > 20); } diff --git a/Projects/Scripts/Commands/BoundingBoxPicker.cs b/Projects/Scripts/Commands/BoundingBoxPicker.cs index d95156919..29b0913bd 100644 --- a/Projects/Scripts/Commands/BoundingBoxPicker.cs +++ b/Projects/Scripts/Commands/BoundingBoxPicker.cs @@ -1,6 +1,6 @@ using Server.Targeting; -namespace Server +namespace Server.Commands { public delegate void BoundingBoxCallback(Map map, Point3D start, Point3D end); @@ -60,4 +60,4 @@ namespace Server } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Commands/ConvertPlayers.cs b/Projects/Scripts/Commands/ConvertPlayers.cs index 5dacd925e..c37c971cb 100644 --- a/Projects/Scripts/Commands/ConvertPlayers.cs +++ b/Projects/Scripts/Commands/ConvertPlayers.cs @@ -7,7 +7,7 @@ using Server.Network; namespace Server.Commands { - public class ConvertPlayers + public static class ConvertPlayers { public static void Initialize() { diff --git a/Projects/Scripts/Commands/Decorate.cs b/Projects/Scripts/Commands/Decorate.cs index 5475fb6eb..4debc22a7 100644 --- a/Projects/Scripts/Commands/Decorate.cs +++ b/Projects/Scripts/Commands/Decorate.cs @@ -9,7 +9,7 @@ using Server.Mobiles; namespace Server.Commands { - public class Decorate + public static class Decorate { private static Mobile m_Mobile; private static int m_Count; @@ -878,9 +878,7 @@ namespace Server.Commands res = true; } else if ((item.ItemData.Flags & TileFlag.LightSource) != 0 && item.ItemData.Name == srcName) - { m_DeleteQueue.Enqueue(item); - } } } else if (srcItem is Teleporter || srcItem is FillableContainer || srcItem is BaseBook) diff --git a/Projects/Scripts/Commands/DecorateMag.cs b/Projects/Scripts/Commands/DecorateMag.cs index 38997aaad..4f0ba1386 100644 --- a/Projects/Scripts/Commands/DecorateMag.cs +++ b/Projects/Scripts/Commands/DecorateMag.cs @@ -10,7 +10,7 @@ using Server.Mobiles; namespace Server.Commands { - public class DecorateMag + public static class DecorateMag { private static Mobile m_Mobile; private static int m_Count; diff --git a/Projects/Scripts/Commands/Docs.cs b/Projects/Scripts/Commands/Docs.cs index c0e1fd763..152b1f31e 100644 --- a/Projects/Scripts/Commands/Docs.cs +++ b/Projects/Scripts/Commands/Docs.cs @@ -82,9 +82,7 @@ namespace Server.Commands if (baseInfo == null) m_Types[baseType] = baseInfo = new TypeInfo(baseType); - if (baseInfo.m_Derived == null) - baseInfo.m_Derived = new List(); - + baseInfo.m_Derived ??= new List(); baseInfo.m_Derived.Add(info); } @@ -97,9 +95,7 @@ namespace Server.Commands if (decInfo == null) m_Types[decType] = decInfo = new TypeInfo(decType); - if (decInfo.m_Nested == null) - decInfo.m_Nested = new List(); - + decInfo.m_Nested ??= new List(); decInfo.m_Nested.Add(info); } @@ -115,9 +111,7 @@ namespace Server.Commands if (ifaceInfo == null) m_Types[iface] = ifaceInfo = new TypeInfo(iface); - if (ifaceInfo.m_Derived == null) - ifaceInfo.m_Derived = new List(); - + ifaceInfo.m_Derived ??= new List(); ifaceInfo.m_Derived.Add(info); } } @@ -644,6 +638,7 @@ namespace Server.Commands m_Namespaces = new Dictionary>(); List assemblies = new List { Core.Assembly }; + assemblies.AddRange(AssemblyHandler.Assemblies); foreach (Assembly asm in AssemblyHandler.Assemblies) @@ -1163,37 +1158,21 @@ namespace Server.Commands Item item = items[i].Construct(); if (item is Sandals) - { rewards[5] = true; - } else if (item is SmallStretchedHideEastDeed || item is SmallStretchedHideSouthDeed) - { rewards[10] = rewards[11] = true; - } else if (item is MediumStretchedHideEastDeed || item is MediumStretchedHideSouthDeed) - { rewards[10] = rewards[11] = true; - } else if (item is LightFlowerTapestryEastDeed || item is LightFlowerTapestrySouthDeed) - { rewards[12] = rewards[13] = true; - } else if (item is DarkFlowerTapestryEastDeed || item is DarkFlowerTapestrySouthDeed) - { rewards[12] = rewards[13] = true; - } else if (item is BrownBearRugEastDeed || item is BrownBearRugSouthDeed) - { rewards[14] = rewards[15] = true; - } else if (item is PolarBearRugEastDeed || item is PolarBearRugSouthDeed) - { rewards[14] = rewards[15] = true; - } else if (item is ClothingBlessDeed) - { rewards[16] = true; - } else if (item is PowerScroll ps) { if (ps.Value == 105.0) @@ -1218,10 +1197,7 @@ namespace Server.Commands else rewards[4] = true; } - else if (item is RunicSewingKit rkit) - { - rewards[16 + CraftResources.GetIndex(rkit.Resource)] = true; - } + else if (item is RunicSewingKit rkit) rewards[16 + CraftResources.GetIndex(rkit.Resource)] = true; item.Delete(); } @@ -1439,37 +1415,21 @@ namespace Server.Commands Item item = items[i].Construct(); if (item is SturdyPickaxe || item is SturdyShovel) - { rewards[0] = true; - } else if (item is LeatherGlovesOfMining) - { rewards[1] = true; - } else if (item is StuddedGlovesOfMining) - { rewards[2] = true; - } else if (item is RingmailGlovesOfMining) - { rewards[3] = true; - } else if (item is GargoylesPickaxe) - { rewards[4] = true; - } else if (item is ProspectorsTool) - { rewards[5] = true; - } else if (item is PowderOfTemperament) - { rewards[6] = true; - } else if (item is ColoredAnvil) - { rewards[7] = true; - } else if (item is PowerScroll ps) { if (ps.Value == 105.0) @@ -1482,9 +1442,7 @@ namespace Server.Commands rewards[11] = true; } else if (item is RunicHammer rh) - { rewards[11 + CraftResources.GetIndex(rh.Resource)] = true; - } else if (item is AncientSmithyHammer ash) { if (ash.Bonus == 10) diff --git a/Projects/Scripts/Commands/GenTeleporter.cs b/Projects/Scripts/Commands/GenTeleporter.cs index 1c42392d7..a9e5e4497 100644 --- a/Projects/Scripts/Commands/GenTeleporter.cs +++ b/Projects/Scripts/Commands/GenTeleporter.cs @@ -3,7 +3,7 @@ using Server.Items; namespace Server.Commands { - public class GenTeleporter + public static class GenTeleporter { public static void Initialize() { @@ -282,7 +282,7 @@ namespace Server.Commands CreateTeleporter(2758, 2092, -20, 2756, 2097, 38, map, false); CreateTeleporter(2759, 2092, -20, 2756, 2097, 38, map, false); CreateTeleporter(2685, 2063, 39, 2685, 2063, -20, map, - false); // that should not be a teleporter: on OSI you simply fall under the ground + false); // that should not be a teleporter: on OSI you simply fall under the ground // Misc CreateTeleporter(5217, 18, 15, 5204, 74, 17, map, false); @@ -597,7 +597,7 @@ namespace Server.Commands CreateTeleporter(11, 1519, -27, 11, 873, -28, map, false); CreateTeleporter(12, 1519, -27, 12, 873, -27, map, false); - // Ratman Lair + // Ratman Lair CreateTeleporter(636, 813, -62, 164, 743, -28, map, false); CreateTeleporter(164, 746, -16, 636, 815, -52, map, false); @@ -775,47 +775,47 @@ namespace Server.Commands CreateTeleporter(548, 455, -40, 428, 113, -28, map, true); CreateTeleporter(429, 113, -28, 548, 455, -40, map, false); - CreateTeleporter(242, 27, -16, 372, 31, -31, map, false); // stairs - 0x754 - CreateTeleporter(242, 26, -16, 372, 30, -31, map, false); // stairs - 0x754 - CreateTeleporter(242, 25, -16, 372, 29, -31, map, false); // stairs - 0x754 - CreateTeleporter(371, 31, -36, 241, 27, -18, map, false); // stairs - 0x754 - CreateTeleporter(371, 30, -36, 241, 26, -18, map, false); // stairs - 0x754 + CreateTeleporter(242, 27, -16, 372, 31, -31, map, false); // stairs - 0x754 + CreateTeleporter(242, 26, -16, 372, 30, -31, map, false); // stairs - 0x754 + CreateTeleporter(242, 25, -16, 372, 29, -31, map, false); // stairs - 0x754 + CreateTeleporter(371, 31, -36, 241, 27, -18, map, false); // stairs - 0x754 + CreateTeleporter(371, 30, -36, 241, 26, -18, map, false); // stairs - 0x754 DestroyTeleporter(371, 29, -36, map); //To remove old erroneous teleporter CreateTeleporter(371, 29, -36, 241, 25, -18, map, false); // stairs - 0x754 - CreateTeleporter(272, 141, -16, 555, 427, -1, map, false); // stairs - 1st 0x753 - CreateTeleporter(273, 141, -16, 556, 427, -1, map, false); // stairs - 1st 0x753 - CreateTeleporter(274, 141, -16, 557, 427, -1, map, false); // stairs - 1st 0x753 - CreateTeleporter(555, 426, -6, 272, 140, -21, map, false); // stairs - 1st 0x753 - CreateTeleporter(556, 426, -6, 273, 140, -21, map, false); // stairs - 1st 0x753 - CreateTeleporter(557, 426, -6, 274, 140, -21, map, false); // stairs - 1st 0x753 + CreateTeleporter(272, 141, -16, 555, 427, -1, map, false); // stairs - 1st 0x753 + CreateTeleporter(273, 141, -16, 556, 427, -1, map, false); // stairs - 1st 0x753 + CreateTeleporter(274, 141, -16, 557, 427, -1, map, false); // stairs - 1st 0x753 + CreateTeleporter(555, 426, -6, 272, 140, -21, map, false); // stairs - 1st 0x753 + CreateTeleporter(556, 426, -6, 273, 140, -21, map, false); // stairs - 1st 0x753 + CreateTeleporter(557, 426, -6, 274, 140, -21, map, false); // stairs - 1st 0x753 - CreateTeleporter(265, 130, -31, 284, 72, -21, map, false); // stairs - 0x753 - CreateTeleporter(266, 130, -31, 285, 72, -21, map, false); // stairs - 0x753 - CreateTeleporter(267, 130, -31, 286, 72, -21, map, false); // stairs - 0x753 - CreateTeleporter(268, 130, -31, 287, 72, -21, map, false); // stairs - 0x753 - CreateTeleporter(284, 73, -16, 265, 131, -28, map, false); // stairs - 0x753 - CreateTeleporter(285, 73, -16, 266, 131, -28, map, false); // stairs - 0x753 - CreateTeleporter(286, 73, -16, 267, 131, -28, map, false); // stairs - 0x753 - CreateTeleporter(287, 73, -16, 268, 131, -28, map, false); // stairs - 0x753 + CreateTeleporter(265, 130, -31, 284, 72, -21, map, false); // stairs - 0x753 + CreateTeleporter(266, 130, -31, 285, 72, -21, map, false); // stairs - 0x753 + CreateTeleporter(267, 130, -31, 286, 72, -21, map, false); // stairs - 0x753 + CreateTeleporter(268, 130, -31, 287, 72, -21, map, false); // stairs - 0x753 + CreateTeleporter(284, 73, -16, 265, 131, -28, map, false); // stairs - 0x753 + CreateTeleporter(285, 73, -16, 266, 131, -28, map, false); // stairs - 0x753 + CreateTeleporter(286, 73, -16, 267, 131, -28, map, false); // stairs - 0x753 + CreateTeleporter(287, 73, -16, 268, 131, -28, map, false); // stairs - 0x753 - CreateTeleporter(284, 67, -30, 131, 128, -21, map, false); // stairs - 0x753 - CreateTeleporter(285, 67, -30, 132, 128, -21, map, false); // stairs - 0x753 - CreateTeleporter(286, 67, -30, 133, 128, -21, map, false); // stairs - 0x753 - CreateTeleporter(287, 67, -30, 134, 128, -21, map, false); // stairs - 0x753 - CreateTeleporter(131, 129, -16, 284, 68, -28, map, false); // stairs - 0x753 - CreateTeleporter(132, 129, -16, 285, 68, -28, map, false); // stairs - 0x753 - CreateTeleporter(133, 129, -16, 286, 68, -28, map, false); // stairs - 0x753 - CreateTeleporter(134, 129, -16, 287, 68, -28, map, false); // stairs - 0x753 + CreateTeleporter(284, 67, -30, 131, 128, -21, map, false); // stairs - 0x753 + CreateTeleporter(285, 67, -30, 132, 128, -21, map, false); // stairs - 0x753 + CreateTeleporter(286, 67, -30, 133, 128, -21, map, false); // stairs - 0x753 + CreateTeleporter(287, 67, -30, 134, 128, -21, map, false); // stairs - 0x753 + CreateTeleporter(131, 129, -16, 284, 68, -28, map, false); // stairs - 0x753 + CreateTeleporter(132, 129, -16, 285, 68, -28, map, false); // stairs - 0x753 + CreateTeleporter(133, 129, -16, 286, 68, -28, map, false); // stairs - 0x753 + CreateTeleporter(134, 129, -16, 287, 68, -28, map, false); // stairs - 0x753 - CreateTeleporter(358, 40, -36, 156, 88, -18, map, false); // stairs - 0x73A - CreateTeleporter(358, 41, -36, 156, 89, -18, map, false); // stairs - 0x73A - CreateTeleporter(358, 42, -36, 156, 90, -18, map, false); // stairs - 0x73A - CreateTeleporter(155, 88, -16, 357, 40, -31, map, false); // stairs - 0x73A - CreateTeleporter(155, 89, -16, 357, 41, -31, map, false); // stairs - 0x73A - CreateTeleporter(155, 90, -16, 357, 42, -31, map, false); // stairs - 0x73A + CreateTeleporter(358, 40, -36, 156, 88, -18, map, false); // stairs - 0x73A + CreateTeleporter(358, 41, -36, 156, 89, -18, map, false); // stairs - 0x73A + CreateTeleporter(358, 42, -36, 156, 90, -18, map, false); // stairs - 0x73A + CreateTeleporter(155, 88, -16, 357, 40, -31, map, false); // stairs - 0x73A + CreateTeleporter(155, 89, -16, 357, 41, -31, map, false); // stairs - 0x73A + CreateTeleporter(155, 90, -16, 357, 42, -31, map, false); // stairs - 0x73A CreateTeleporter(259, 90, -28, 236, 113, -28, map, true); @@ -923,7 +923,7 @@ namespace Server.Commands public void CreateTeleportersMap3(Map map) { - // CreateTeleporter( 408, 254, 2, 428, 319, 2, map, false ); // for doom quest; use blockers to avoid players teleporting into the ship! + // CreateTeleporter( 408, 254, 2, 428, 319, 2, map, false ); // for doom quest; use blockers to avoid players teleporting into the ship! // CreateTeleporter( 428, 321, 2, 422, 328, -1, map, false ); // for doom quest; use blockers to avoid players teleporting into the ship! // Doom Dungeon @@ -1040,4 +1040,4 @@ namespace Server.Commands } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Commands/Generic/Commands/Commands.cs b/Projects/Scripts/Commands/Generic/Commands/Commands.cs index 95e7de3f7..c0718109c 100644 --- a/Projects/Scripts/Commands/Generic/Commands/Commands.cs +++ b/Projects/Scripts/Commands/Generic/Commands/Commands.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Accounting; using Server.Engines.Help; using Server.Factions; @@ -12,7 +13,7 @@ using Server.Spells; namespace Server.Commands.Generic { - public class TargetCommands + public static class TargetCommands { public static List AllCommands{ get; } = new List(); @@ -185,10 +186,7 @@ namespace Server.Commands.Generic public override void ExecuteList(CommandEventArgs e, List list) { - if (list.Count == 1) - AddResponse("There is one matching object."); - else - AddResponse($"There are {list.Count} matching objects."); + AddResponse(list.Count == 1 ? "There is one matching object." : $"There are {list.Count} matching objects."); } } @@ -234,9 +232,7 @@ namespace Server.Commands.Generic NetState ns = mob.NetState; if (ns == null) - { LogFailure("That player is not online."); - } else { string url = e.GetString(0); @@ -244,10 +240,7 @@ namespace Server.Commands.Generic CommandLogging.WriteLine(from, "{0} {1} requesting to open web browser of {2} to {3}", from.AccessLevel, CommandLogging.Format(from), CommandLogging.Format(mob), url); - if (echo) - AddResponse("Awaiting user confirmation..."); - else - AddResponse("Open web browser request sent."); + AddResponse(echo ? "Awaiting user confirmation..." : "Open web browser request sent."); mob.SendGump(new WarningGump(1060637, 30720, $"A game master is requesting to open your web browser to the following URL:{url}", 0xFFC000, @@ -255,14 +248,10 @@ namespace Server.Commands.Generic } } else - { LogFailure("That is not a player."); - } } else - { LogFailure("Format: OpenBrowser "); - } } public override void Execute(CommandEventArgs e, object obj) @@ -336,7 +325,7 @@ namespace Server.Commands.Generic CommandLogging.WriteLine(from, "{0} {1} playing sound {2} for {3}", from.AccessLevel, CommandLogging.Format(from), index, CommandLogging.Format(mob)); - mob.Send(new PlaySound(index, mob.Location)); + Packets.SendPlaySound(mob.NetState, index, mob.Location); } else { @@ -458,14 +447,10 @@ namespace Server.Commands.Generic e.Mobile.SendGump(new AddGump(e.Mobile, match, 0, Type.EmptyTypes, false)); } else - { e.Mobile.SendGump(new AddGump(e.Mobile, match, 0, AddGump.Match(match).ToArray(), true)); - } } else - { return true; - } } else { @@ -634,19 +619,9 @@ namespace Server.Commands.Generic public override void Execute(CommandEventArgs e, object obj) { - if (obj == null) - { - AddResponse("The object is null."); - } - else - { - Type type = obj.GetType(); - - if (type.DeclaringType == null) - AddResponse($"The type of that object is {type.Name}."); - else - AddResponse($"The type of that object is {type.FullName}."); - } + AddResponse(obj == null ? + "The object is null." : + $"The type of that object is {obj.GetType().FullName}."); } } @@ -860,13 +835,9 @@ namespace Server.Commands.Generic if (m_Value) { if (!mob.Alive) - { LogFailure("They are already dead."); - } else if (!mob.CanBeDamaged()) - { LogFailure("They cannot be harmed."); - } else { CommandLogging.WriteLine(from, "{0} {1} killing {2}", from.AccessLevel, CommandLogging.Format(from), @@ -960,10 +931,7 @@ namespace Server.Commands.Generic m.PlaySound(0x228); m.Hidden = m_Value; - if (m_Value) - AddResponse("They have been hidden."); - else - AddResponse("They have been revealed."); + AddResponse(m_Value ? "They have been hidden." : "They have been revealed."); } } @@ -1002,9 +970,7 @@ namespace Server.Commands.Generic } } else - { LogFailure("They are not online."); - } } } @@ -1098,12 +1064,11 @@ namespace Server.Commands.Generic return; } - foreach (BaseHouse house in BaseHouse.AllHouses) - if (house.HasSecureItem(item) || house.HasLockedDownItem(item)) - { - e.Mobile.SendGump(new PropertiesGump(e.Mobile, house)); - return; - } + foreach (BaseHouse house in BaseHouse.AllHouses.Where(house => house.HasSecureItem(item) || house.HasLockedDownItem(item))) + { + e.Mobile.SendGump(new PropertiesGump(e.Mobile, house)); + return; + } LogFailure("No house was found."); } diff --git a/Projects/Scripts/Commands/Generic/Commands/DesignInsert.cs b/Projects/Scripts/Commands/Generic/Commands/DesignInsert.cs index cae91d825..541f4959c 100644 --- a/Projects/Scripts/Commands/Generic/Commands/DesignInsert.cs +++ b/Projects/Scripts/Commands/Generic/Commands/DesignInsert.cs @@ -149,7 +149,7 @@ namespace Server.Commands.Generic AddResponse("Awaiting confirmation..."); } - private void OnConfirmCallback(Mobile from, bool okay, List list, bool staticsOnly) + private void OnConfirmCallback(Mobile from, bool okay, IReadOnlyList list, bool staticsOnly) { bool flushToLog = false; @@ -191,13 +191,11 @@ namespace Server.Commands.Generic house.Delta(ItemDelta.Update); } else - { AddResponse("Command aborted."); - } Flush(from, flushToLog); } #endregion } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Commands/Generic/Extensions/Compilers/ConditionalCompiler.cs b/Projects/Scripts/Commands/Generic/Extensions/Compilers/ConditionalCompiler.cs index 6db1c7a08..9b9ecf962 100644 --- a/Projects/Scripts/Commands/Generic/Extensions/Compilers/ConditionalCompiler.cs +++ b/Projects/Scripts/Commands/Generic/Extensions/Compilers/ConditionalCompiler.cs @@ -160,10 +160,6 @@ namespace Server.Commands.Generic FieldAttributes.Private | FieldAttributes.InitOnly ); -// parseMethod.Invoke(null, -// parseArgs.Length == 2 ? new object[] {toParse, (int) parseArgs[1]} : new object[] {toParse}); - - il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldstr, toParse); @@ -234,36 +230,17 @@ namespace Server.Commands.Generic public override void Compile(MethodEmitter emitter) { - bool inverse = false; + bool inverse = m_Operator == StringOperator.NotEqual; - string methodName; - - switch (m_Operator) + string methodName = m_Operator switch { - case StringOperator.Equal: - methodName = "Equals"; - break; - - case StringOperator.NotEqual: - methodName = "Equals"; - inverse = true; - break; - - case StringOperator.Contains: - methodName = "Contains"; - break; - - case StringOperator.StartsWith: - methodName = "StartsWith"; - break; - - case StringOperator.EndsWith: - methodName = "EndsWith"; - break; - - default: - throw new InvalidOperationException("Invalid string comparison operator."); - } + StringOperator.Equal => "Equals", + StringOperator.NotEqual => "Equals", + StringOperator.Contains => "Contains", + StringOperator.StartsWith => "StartsWith", + StringOperator.EndsWith => "EndsWith", + _ => throw new InvalidOperationException("Invalid string comparison operator.") + }; if (m_IgnoreCase || methodName == "Equals") { diff --git a/Projects/Scripts/Commands/Generic/Extensions/DistinctExtension.cs b/Projects/Scripts/Commands/Generic/Extensions/DistinctExtension.cs index 682f4681c..cc3fcf846 100644 --- a/Projects/Scripts/Commands/Generic/Extensions/DistinctExtension.cs +++ b/Projects/Scripts/Commands/Generic/Extensions/DistinctExtension.cs @@ -32,8 +32,7 @@ namespace Server.Commands.Generic prop.CheckAccess(from); } - if (assembly == null) - assembly = new AssemblyEmitter("__dynamic"); + assembly ??= new AssemblyEmitter("__dynamic"); m_Comparer = DistinctCompiler.Compile(assembly, baseType, m_Properties.ToArray()); } diff --git a/Projects/Scripts/Commands/Generic/Extensions/SortExtension.cs b/Projects/Scripts/Commands/Generic/Extensions/SortExtension.cs index 5f2684cdb..cd1f757e1 100644 --- a/Projects/Scripts/Commands/Generic/Extensions/SortExtension.cs +++ b/Projects/Scripts/Commands/Generic/Extensions/SortExtension.cs @@ -31,8 +31,7 @@ namespace Server.Commands.Generic order.Property.CheckAccess(from); } - if (assembly == null) - assembly = new AssemblyEmitter("__dynamic"); + assembly ??= new AssemblyEmitter("__dynamic"); m_Comparer = SortCompiler.Compile(assembly, baseType, m_Orders.ToArray()); } @@ -69,7 +68,6 @@ namespace Server.Commands.Generic case "up": case "asc": case "ascending": - isAscending = true; ++offset; break; diff --git a/Projects/Scripts/Commands/Generic/Implementors/BaseCommandImplementor.cs b/Projects/Scripts/Commands/Generic/Implementors/BaseCommandImplementor.cs index 23edf03ea..ab37d795c 100644 --- a/Projects/Scripts/Commands/Generic/Implementors/BaseCommandImplementor.cs +++ b/Projects/Scripts/Commands/Generic/Implementors/BaseCommandImplementor.cs @@ -111,20 +111,15 @@ namespace Server.Commands.Generic case ObjectTypes.All: case ObjectTypes.Both: { - if (condIsItem) - items = true; - - if (condIsMobile) - mobiles = true; + items |= condIsItem; + mobiles |= condIsMobile; break; } case ObjectTypes.Items: { if (condIsItem) - { items = true; - } else if (condIsMobile) { from.SendMessage("You may not use a mobile type condition for this command."); @@ -136,9 +131,7 @@ namespace Server.Commands.Generic case ObjectTypes.Mobiles: { if (condIsMobile) - { mobiles = true; - } else if (condIsItem) { from.SendMessage("You may not use an item type condition for this command."); diff --git a/Projects/Scripts/Commands/Generic/Implementors/ContainedCommandImplementor.cs b/Projects/Scripts/Commands/Generic/Implementors/ContainedCommandImplementor.cs index 2425840fe..f68ff1e2c 100644 --- a/Projects/Scripts/Commands/Generic/Implementors/ContainedCommandImplementor.cs +++ b/Projects/Scripts/Commands/Generic/Implementors/ContainedCommandImplementor.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Items; using Server.Targeting; @@ -40,7 +41,7 @@ namespace Server.Commands.Generic from.SendMessage("That is not a container."); return; } - + try { Extensions ext = Extensions.Parse(from, ref args); @@ -70,4 +71,4 @@ namespace Server.Commands.Generic } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Commands/Generic/Implementors/GlobalCommandImplementor.cs b/Projects/Scripts/Commands/Generic/Implementors/GlobalCommandImplementor.cs index e68726237..85d4d7b7f 100644 --- a/Projects/Scripts/Commands/Generic/Implementors/GlobalCommandImplementor.cs +++ b/Projects/Scripts/Commands/Generic/Implementors/GlobalCommandImplementor.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; namespace Server.Commands.Generic { @@ -28,14 +29,10 @@ namespace Server.Commands.Generic List list = new List(); if (items) - foreach (Item item in World.Items.Values) - if (ext.IsValid(item)) - list.Add(item); + list.AddRange(World.Items.Values.Where(item => ext.IsValid(item))); if (mobiles) - foreach (Mobile mob in World.Mobiles.Values) - if (ext.IsValid(mob)) - list.Add(mob); + list.AddRange(World.Mobiles.Values.Where(mob => ext.IsValid(mob))); ext.Filter(list); @@ -47,4 +44,4 @@ namespace Server.Commands.Generic } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Commands/Generic/Implementors/ObjectConditional.cs b/Projects/Scripts/Commands/Generic/Implementors/ObjectConditional.cs index 72519c9c5..6124e0e34 100644 --- a/Projects/Scripts/Commands/Generic/Implementors/ObjectConditional.cs +++ b/Projects/Scripts/Commands/Generic/Implementors/ObjectConditional.cs @@ -30,8 +30,7 @@ namespace Server.Commands.Generic public void Compile(ref AssemblyEmitter emitter) { - if (emitter == null) - emitter = new AssemblyEmitter("__dynamic"); + emitter ??= new AssemblyEmitter("__dynamic"); m_Conditionals = new IConditional[m_Conditions.Length]; diff --git a/Projects/Scripts/Commands/Generic/Implementors/RegionCommandImplementor.cs b/Projects/Scripts/Commands/Generic/Implementors/RegionCommandImplementor.cs index 5739236f9..edf65f7d4 100644 --- a/Projects/Scripts/Commands/Generic/Implementors/RegionCommandImplementor.cs +++ b/Projects/Scripts/Commands/Generic/Implementors/RegionCommandImplementor.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; namespace Server.Commands.Generic { @@ -30,16 +31,7 @@ namespace Server.Commands.Generic List list = new List(); if (mobiles) - { - foreach (Mobile mob in reg.GetMobiles()) - { - if (!BaseCommand.IsAccessible(from, mob)) - continue; - - if (ext.IsValid(mob)) - list.Add(mob); - } - } + list.AddRange(reg.GetMobiles().Where(mob => BaseCommand.IsAccessible(from, mob)).Where(mob => ext.IsValid(mob))); else { command.LogFailure("This command does not support items."); @@ -56,4 +48,4 @@ namespace Server.Commands.Generic } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Commands/Generic/Implementors/SerialCommandImplementor.cs b/Projects/Scripts/Commands/Generic/Implementors/SerialCommandImplementor.cs index 5996b1466..57873a2d1 100644 --- a/Projects/Scripts/Commands/Generic/Implementors/SerialCommandImplementor.cs +++ b/Projects/Scripts/Commands/Generic/Implementors/SerialCommandImplementor.cs @@ -17,7 +17,7 @@ namespace Server.Commands.Generic { Serial serial = e.GetUInt32(0); - object obj = null; + IEntity obj = null; if (serial.IsItem) obj = World.FindItem(serial); @@ -25,22 +25,16 @@ namespace Server.Commands.Generic obj = World.FindMobile(serial); if (obj == null) - { e.Mobile.SendMessage("That is not a valid serial."); - } else { Commands.TryGetValue(e.GetString(1), out BaseCommand command); if (command == null) - { e.Mobile.SendMessage( "That is either an invalid command name or one that does not support this modifier."); - } else if (e.Mobile.AccessLevel < command.AccessLevel) - { e.Mobile.SendMessage("You do not have access to that command."); - } else { switch (command.ObjectTypes) diff --git a/Projects/Scripts/Commands/Handlers.cs b/Projects/Scripts/Commands/Handlers.cs index 723dfb2eb..f1015888f 100644 --- a/Projects/Scripts/Commands/Handlers.cs +++ b/Projects/Scripts/Commands/Handlers.cs @@ -1,10 +1,11 @@ using System.Collections.Generic; +using System.Linq; using System.Text; using Server.Commands.Generic; using Server.Engines.Help; using Server.Gumps; using Server.Items; -using Server.Menus.ItemLists; +using Server.Menus; using Server.Menus.Questions; using Server.Misc; using Server.Mobiles; @@ -16,7 +17,7 @@ using Server.Targets; namespace Server.Commands { - public class CommandHandlers + public static class CommandHandlers { public static void Initialize() { @@ -88,19 +89,17 @@ namespace Server.Commands { if (e.Length == 1 && !e.GetBoolean(0)) { - from.Send(SpeedControl.Disable); + Packets.SendSpeedControlDisabled(from.NetState); from.SendMessage("Speed boost has been disabled."); } else { - from.Send(SpeedControl.MountSpeed); + Packets.SendSpeedControlMount(from.NetState); from.SendMessage("Speed boost has been enabled."); } } else - { from.SendMessage("Format: SpeedBoost [true|false]"); - } } [Usage("Where")] @@ -159,18 +158,16 @@ namespace Server.Commands { PageEntry pe = PageQueue.GetEntry(targ); - if (pe?.Handler == from) - from.SendMessage("You may only use this command if you are handling their help page."); - else - from.SendMessage("You may only use this command on someone who has paged you."); + from.SendMessage(pe?.Handler == from + ? "You may only use this command if you are handling their help page." + : "You may only use this command on someone who has paged you."); return; } - if (targ.AddToBackpack(held)) - from.SendMessage("The item they were holding has been placed into their backpack."); - else - from.SendMessage("The item they were holding has been placed at their feet."); + from.SendMessage(targ.AddToBackpack(held) + ? "The item they were holding has been placed into their backpack." + : "The item they were holding has been placed at their feet."); held.ClearBounce(); @@ -220,14 +217,8 @@ namespace Server.Commands } List list = new List(); - - foreach (Item item in World.Items.Values) - if (item.Map == map && item.Parent == null) - list.Add(item); - - foreach (Mobile m in World.Mobiles.Values) - if (m.Map == map && !m.Player) - list.Add(m); + list.AddRange(World.Items.Values.Where(item => item.Map == map && item.Parent == null)); + list.AddRange(World.Mobiles.Values.Where(m => m.Map == map && !m.Player)); if (list.Count > 0) { @@ -277,9 +268,7 @@ namespace Server.Commands } } else - { from.SendMessage("There were no pets found for that player."); - } } else if (obj is Mobile master && master.Player) { @@ -308,9 +297,7 @@ namespace Server.Commands } } else - { from.SendMessage("There were no pets found for that player."); - } } else { @@ -349,15 +336,9 @@ namespace Server.Commands CommandLogging.WriteLine(m, "{0} {1} playing sound {2} (toAll={3})", m.AccessLevel, CommandLogging.Format(m), index, toAll); - Packet p = new PlaySound(index, m.Location); - - p.Acquire(); - foreach (NetState state in m.GetClientsInRange(12)) if (toAll || state.Mobile.CanSee(m)) - state.Send(p); - - p.Release(); + Packets.SendPlaySound(state, index, m.Location); } [Usage("Echo ")] @@ -366,10 +347,7 @@ namespace Server.Commands { string toEcho = e.ArgString.Trim(); - if (toEcho.Length > 0) - e.Mobile.SendMessage(toEcho); - else - e.Mobile.SendMessage("Format: Echo \"\""); + e.Mobile.SendMessage(toEcho.Length > 0 ? toEcho : "Format: Echo \"\""); } [Usage("Bank")] @@ -528,16 +506,12 @@ namespace Server.Commands Dictionary list = from.Map.Regions; - foreach (KeyValuePair kvp in list) - { - Region r = kvp.Value; - + foreach (var (_, r) in list) if (Insensitive.Equals(r.Name, name)) { from.Location = new Point3D(r.GoLocation); return; } - } for (int i = 0; i < Map.AllMaps.Count; ++i) { @@ -618,11 +592,7 @@ namespace Server.Commands { Mobile m = e.Mobile; - List list = new List(); - - foreach (CommandEntry entry in CommandSystem.Entries.Values) - if (m.AccessLevel >= entry.AccessLevel) - list.Add(entry); + List list = CommandSystem.Entries.Values.Where(entry => m.AccessLevel >= entry.AccessLevel).ToList(); list.Sort(); @@ -671,13 +641,8 @@ namespace Server.Commands public static void BroadcastMessage(AccessLevel ac, int hue, string message) { - foreach (NetState state in NetState.Instances) - { - Mobile m = state.Mobile; - - if (m?.AccessLevel >= ac) - m.SendMessage(hue, message); - } + foreach (Mobile m in NetState.Instances.Select(state => state.Mobile).Where(m => m?.AccessLevel >= ac)) + m.SendMessage(hue, message); } [Usage("AutoPageNotify")] diff --git a/Projects/Scripts/Commands/HelpInfo.cs b/Projects/Scripts/Commands/HelpInfo.cs index a868edf7e..8f1dc7946 100644 --- a/Projects/Scripts/Commands/HelpInfo.cs +++ b/Projects/Scripts/Commands/HelpInfo.cs @@ -9,7 +9,7 @@ using CommandInfoSorter = Server.Commands.Docs.CommandEntrySorter; namespace Server.Commands { - public class HelpInfo + public static class HelpInfo { public static Dictionary HelpInfos{ get; } = new Dictionary(); diff --git a/Projects/Scripts/Commands/Logging.cs b/Projects/Scripts/Commands/Logging.cs index 8c4f09b86..0bc629775 100644 --- a/Projects/Scripts/Commands/Logging.cs +++ b/Projects/Scripts/Commands/Logging.cs @@ -5,7 +5,7 @@ using Server.Accounting; namespace Server.Commands { - public class CommandLogging + public static class CommandLogging { private static char[] m_NotSafe = { '\\', '/', ':', '*', '?', '"', '<', '>', '|' }; public static bool Enabled{ get; set; } = true; diff --git a/Projects/Scripts/Commands/Properties.cs b/Projects/Scripts/Commands/Properties.cs index 60ed30a2f..c95ece9eb 100644 --- a/Projects/Scripts/Commands/Properties.cs +++ b/Projects/Scripts/Commands/Properties.cs @@ -196,7 +196,7 @@ namespace Server.Commands } } - return chain[chain.Length - 1]; + return chain[^1]; } public static string GetValue(Mobile from, object o, string name) @@ -328,7 +328,7 @@ namespace Server.Commands concat[i * 2 + 1] = i < chain.Length - 1 ? "." : " = "; } - concat[concat.Length - 1] = toString; + concat[^1] = toString; return string.Concat(concat); } @@ -382,7 +382,7 @@ namespace Server.Commands if (IsEnum(type)) try { - toSet = Enum.Parse(type, value, true); + toSet = Enum.Parse(type, value ?? "", true); } catch { @@ -654,7 +654,7 @@ namespace Server if (!IsBound) throw new NotYetBoundException(this); - return m_Chain[m_Chain.Length - 1].PropertyType; + return m_Chain[^1].PropertyType; } } diff --git a/Projects/Scripts/Commands/ShardTime.cs b/Projects/Scripts/Commands/ShardTime.cs index af91bba37..33e7ea882 100644 --- a/Projects/Scripts/Commands/ShardTime.cs +++ b/Projects/Scripts/Commands/ShardTime.cs @@ -2,7 +2,7 @@ namespace Server.Commands { - public class ShardTime + public static class ShardTime { public static void Initialize() { @@ -16,4 +16,4 @@ namespace Server.Commands e.Mobile.SendMessage(DateTime.UtcNow.ToString()); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Commands/SignParser.cs b/Projects/Scripts/Commands/SignParser.cs index 66176541b..d8133da8e 100644 --- a/Projects/Scripts/Commands/SignParser.cs +++ b/Projects/Scripts/Commands/SignParser.cs @@ -4,7 +4,7 @@ using Server.Items; namespace Server.Commands { - public class SignParser + public static class SignParser { private static Queue m_ToDelete = new Queue(); @@ -76,9 +76,7 @@ namespace Server.Commands from.SendMessage("Sign generating complete."); } else - { from.SendMessage("{0} not found!", cfg); - } } public static void Add_Static(int itemID, Point3D location, Map map, string name) @@ -94,17 +92,8 @@ namespace Server.Commands while (m_ToDelete.Count > 0) m_ToDelete.Dequeue().Delete(); - Item sign; - - if (name.StartsWith("#")) - { - sign = new LocalizedSign(itemID, Utility.ToInt32(name.Substring(1))); - } - else - { - sign = new Sign(itemID); - sign.Name = name; - } + Item sign = name.StartsWith("#") ? new LocalizedSign(itemID, Utility.ToInt32(name.Substring(1))) : + new Sign(itemID) {Name = name}; if (map == Map.Malas) { diff --git a/Projects/Scripts/Commands/Skills.cs b/Projects/Scripts/Commands/Skills.cs index 7decdfc6f..11ba065da 100644 --- a/Projects/Scripts/Commands/Skills.cs +++ b/Projects/Scripts/Commands/Skills.cs @@ -3,7 +3,7 @@ using Server.Targeting; namespace Server.Commands { - public class SkillsCommand + public static class SkillsCommand { public static void Initialize() { @@ -123,4 +123,4 @@ namespace Server.Commands } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Commands/SkillsMenu.cs b/Projects/Scripts/Commands/SkillsMenu.cs index 6b4e617ab..c97486d03 100644 --- a/Projects/Scripts/Commands/SkillsMenu.cs +++ b/Projects/Scripts/Commands/SkillsMenu.cs @@ -3,7 +3,7 @@ using Server.Targeting; namespace Server.Commands { - public class Skills + public static class Skills { public static void Initialize() { @@ -35,4 +35,4 @@ namespace Server.Commands } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Commands/Statics.cs b/Projects/Scripts/Commands/Statics.cs index 476f96790..48f9acc38 100644 --- a/Projects/Scripts/Commands/Statics.cs +++ b/Projects/Scripts/Commands/Statics.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; using System.IO; -using Server.Commands; using Server.Gumps; using Server.Items; -namespace Server +namespace Server.Commands { - public class Statics + public static class Statics { private const string BaseFreezeWarning = "{0} " + "Those items will be removed from the world and placed into the server data files. " + @@ -180,11 +179,8 @@ namespace Server int totalFrozen = 0; - foreach (KeyValuePair> de in mapTable) + foreach (var (map, table) in mapTable) { - Map map = de.Key; - Dictionary table = de.Value; - TileMatrix matrix = map.Tiles; using FileStream idxStream = OpenWrite(matrix.IndexStream); diff --git a/Projects/Scripts/Commands/VisibilityList.cs b/Projects/Scripts/Commands/VisibilityList.cs index 6e7afd9ec..0dfd9415f 100644 --- a/Projects/Scripts/Commands/VisibilityList.cs +++ b/Projects/Scripts/Commands/VisibilityList.cs @@ -49,9 +49,7 @@ namespace Server.Commands pm.SendMessage("#{0}: {1}", i + 1, list[i].Name); } else - { pm.SendMessage("Your visibility list is empty."); - } } } @@ -71,7 +69,7 @@ namespace Server.Commands Mobile m = list[i]; if (!m.CanSee(pm) && Utility.InUpdateRange(m, pm)) - m.Send(pm.RemovePacket); + Packets.SendRemoveEntity(m.NetState, pm.Serial); } } } @@ -84,58 +82,54 @@ namespace Server.Commands protected override void OnTarget(Mobile from, object targeted) { - if (from is PlayerMobile pm && targeted is Mobile targ) + if (!(from is PlayerMobile pm) || !(targeted is Mobile targ)) { - if (targ.AccessLevel <= pm.AccessLevel) - { - List list = pm.VisibilityList; + from.SendMessage("Add only mobiles to your visibility list."); + return; + } - if (list.Contains(targ)) - { - list.Remove(targ); - pm.SendMessage("{0} has been removed from your visibility list.", targ.Name); - } - else - { - list.Add(targ); - pm.SendMessage("{0} has been added to your visibility list.", targ.Name); - } + if (targ.AccessLevel > pm.AccessLevel) + { + pm.SendMessage("They can already see you!"); + return; + } - if (Utility.InUpdateRange(targ, from)) - { - NetState ns = targ.NetState; + List list = pm.VisibilityList; - if (ns != null) - { - if (targ.CanSee(pm)) - { - ns.Send(MobileIncoming.Create(ns, targ, pm)); - - if (ObjectPropertyList.Enabled) - { - ns.Send(pm.OPLPacket); - - foreach (Item item in pm.Items) - ns.Send(item.OPLPacket); - } - } - else - { - ns.Send(pm.RemovePacket); - } - } - } - } - else - { - pm.SendMessage("They can already see you!"); - } + if (list.Contains(targ)) + { + list.Remove(targ); + pm.SendMessage("{0} has been removed from your visibility list.", targ.Name); } else { - from.SendMessage("Add only mobiles to your visibility list."); + list.Add(targ); + pm.SendMessage("{0} has been added to your visibility list.", targ.Name); + } + + if (Utility.InUpdateRange(targ, from)) + { + NetState ns = targ.NetState; + + if (ns != null) + { + if (targ.CanSee(pm)) + { + Packets.SendMobileIncoming(ns, targ, pm); + + if (ObjectPropertyList.Enabled) + { + pm.PropertyList.Send(ns); + + foreach (Item item in pm.Items) + item.PropertyList.SendOPLInfo(ns); + } + } + else + Packets.SendRemoveEntity(ns, pm.Serial); + } } } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Commands/Wipe.cs b/Projects/Scripts/Commands/Wipe.cs index eec17443b..a8e4921f8 100644 --- a/Projects/Scripts/Commands/Wipe.cs +++ b/Projects/Scripts/Commands/Wipe.cs @@ -5,7 +5,7 @@ using Server.Multis; namespace Server.Commands { - public class Wipe + public static class Wipe { [Flags] public enum WipeType @@ -74,7 +74,7 @@ namespace Server.Commands if (!items && !multis || !mobiles) return; - + eable = map.GetObjectsInBounds(rect); foreach (IEntity obj in eable) @@ -91,4 +91,4 @@ namespace Server.Commands toDelete[i].Delete(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Context Menus/AddToSpellbookEntry.cs b/Projects/Scripts/Context Menus/AddToSpellbookEntry.cs index 18d1e0b35..48cc030bc 100644 --- a/Projects/Scripts/Context Menus/AddToSpellbookEntry.cs +++ b/Projects/Scripts/Context Menus/AddToSpellbookEntry.cs @@ -34,9 +34,7 @@ namespace Server.ContextMenus { } else if (book.HasSpell(m_Scroll.SpellID)) - { from.SendLocalizedMessage(500179); // That spell is already present in that spellbook. - } else { int val = m_Scroll.SpellID - book.BookOffset; @@ -47,11 +45,11 @@ namespace Server.ContextMenus m_Scroll.Consume(); - from.Send(new PlaySound(0x249, book.GetWorldLocation())); + Packets.SendPlaySound(from.NetState, 0x249, book.GetWorldLocation()); } } } } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/BulkOrders/Books/BOBGump.cs b/Projects/Scripts/Engines/BulkOrders/Books/BOBGump.cs index 4cbab8357..a7c6e37f3 100644 --- a/Projects/Scripts/Engines/BulkOrders/Books/BOBGump.cs +++ b/Projects/Scripts/Engines/BulkOrders/Books/BOBGump.cs @@ -4,7 +4,6 @@ using Server.Gumps; using Server.Items; using Server.Mobiles; using Server.Network; -using Server.Prompts; namespace Server.Engines.BulkOrders { diff --git a/Projects/Scripts/Engines/BulkOrders/Books/BulkOrderBook.cs b/Projects/Scripts/Engines/BulkOrders/Books/BulkOrderBook.cs index e73315712..8e6470dfb 100644 --- a/Projects/Scripts/Engines/BulkOrders/Books/BulkOrderBook.cs +++ b/Projects/Scripts/Engines/BulkOrders/Books/BulkOrderBook.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using Server.Gumps; using Server.Multis; -using Server.Prompts; using Server.Mobiles; using Server.ContextMenus; using Server.Items; diff --git a/Projects/Scripts/Engines/BulkOrders/LargeBOD.cs b/Projects/Scripts/Engines/BulkOrders/LargeBOD.cs index cafddf4e8..e711755e8 100644 --- a/Projects/Scripts/Engines/BulkOrders/LargeBOD.cs +++ b/Projects/Scripts/Engines/BulkOrders/LargeBOD.cs @@ -1,3 +1,4 @@ +using System.Linq; using Server.Mobiles; namespace Server.Engines.BulkOrders diff --git a/Projects/Scripts/Engines/BulkOrders/LargeTailorBOD.cs b/Projects/Scripts/Engines/BulkOrders/LargeTailorBOD.cs index 8cb608427..8f109ac99 100644 --- a/Projects/Scripts/Engines/BulkOrders/LargeTailorBOD.cs +++ b/Projects/Scripts/Engines/BulkOrders/LargeTailorBOD.cs @@ -2,7 +2,7 @@ namespace Server.Engines.BulkOrders { public class LargeTailorBOD : LargeBOD { - public static double[] m_TailoringMaterialChances = + public static readonly double[] m_TailoringMaterialChances = { 0.857421875, // None 0.125000000, // Spined @@ -19,7 +19,6 @@ namespace Server.Engines.BulkOrders switch (Utility.Random(14)) { default: - case 0: entries = LargeBulkEntry.ConvertEntries(this, LargeBulkEntry.Farmer); break; case 1: diff --git a/Projects/Scripts/Engines/BulkOrders/Rewards.cs b/Projects/Scripts/Engines/BulkOrders/Rewards.cs index c427bb54f..7de897822 100644 --- a/Projects/Scripts/Engines/BulkOrders/Rewards.cs +++ b/Projects/Scripts/Engines/BulkOrders/Rewards.cs @@ -357,7 +357,14 @@ namespace Server.Engines.BulkOrders int[][][] goldTable = m_GoldTable; int typeIndex = ComputeType(type, itemCount); - int quanIndex = quantity == 20 ? 2 : quantity == 15 ? 1 : 0; + + int quanIndex = quantity switch + { + 20 => 2, + 15 => 1, + _ => 0 + }; + int mtrlIndex = material >= BulkMaterialType.DullCopper && material <= BulkMaterialType.Valorite ? 1 + (material - BulkMaterialType.DullCopper) : 0; @@ -599,11 +606,28 @@ namespace Server.Engines.BulkOrders { int[][][] goldTable = Core.AOS ? m_AosGoldTable : m_OldGoldTable; - int typeIndex = (itemCount == 6 ? 3 : itemCount == 5 ? 2 : itemCount == 4 ? 1 : 0) * 2 + (exceptional ? 1 : 0); - int quanIndex = quantity == 20 ? 2 : quantity == 15 ? 1 : 0; - int mtrlIndex = material == BulkMaterialType.Barbed ? 3 : - material == BulkMaterialType.Horned ? 2 : - material == BulkMaterialType.Spined ? 1 : 0; + int typeIndex = itemCount switch + { + 6 => 3, + 5 => 2, + 4 => 1, + _ => 0 + } * 2 + (exceptional ? 1 : 0); + + int quanIndex = quantity switch + { + 20 => 2, + 15 => 1, + _ => 0 + }; + + int mtrlIndex = material switch + { + BulkMaterialType.Barbed => 3, + BulkMaterialType.Horned => 2, + BulkMaterialType.Spined => 1, + _ => 0 + }; int gold = goldTable[typeIndex][quanIndex][mtrlIndex]; @@ -615,7 +639,7 @@ namespace Server.Engines.BulkOrders #region Constructors - private static int[][] m_ClothHues = + private static readonly int[][] m_ClothHues = { new[] { 0x483, 0x48C, 0x488, 0x48A }, new[] { 0x495, 0x48B, 0x486, 0x485 }, @@ -678,13 +702,15 @@ namespace Server.Engines.BulkOrders }; } - private static Item CreateRunicKit(int type) - { - if (type >= 1 && type <= 3) - return new RunicSewingKit(CraftResource.RegularLeather + type, 60 - type * 15); + private static Item CreateRunicKit(int type) => + type >= 1 && type <= 3 + ? new RunicSewingKit(CraftResource.RegularLeather + type, 60 - type * 15) + : throw new InvalidOperationException(); - throw new InvalidOperationException(); - } + private static Item CreatePowerScroll(int type) => + type == 5 || type == 10 || type == 15 || type == 20 + ? new PowerScroll(SkillName.Tailoring, 100 + type) + : throw new InvalidOperationException(); private static Item CreatePowerScroll(int type) { diff --git a/Projects/Scripts/Engines/CannedEvil/ChampionSkullBrazier.cs b/Projects/Scripts/Engines/CannedEvil/ChampionSkullBrazier.cs index 6991ac13e..3cb1b14f1 100644 --- a/Projects/Scripts/Engines/CannedEvil/ChampionSkullBrazier.cs +++ b/Projects/Scripts/Engines/CannedEvil/ChampionSkullBrazier.cs @@ -65,22 +65,16 @@ namespace Server.Engines.CannedEvil Skull = null; if (from.Map != Map || !from.InRange(GetWorldLocation(), 3)) - { from.SendLocalizedMessage(500446); // That is too far away. - } else if (!Harrower.CanSpawn) - { from.SendMessage("The harrower has already been spawned."); - } else if (m_Skull == null) { from.SendLocalizedMessage(1049485); // What would you like to sacrifice? from.Target = new SacrificeTarget(this); } else - { - SendLocalizedMessageTo(from, 1049487, ""); // I already have my champions awakening skull! - } + SendLocalizedMessageTo(from, 1049487); // I already have my champions awakening skull! } public void EndSacrifice(Mobile from, ChampionSkull skull) @@ -92,25 +86,15 @@ namespace Server.Engines.CannedEvil Skull = null; if (from.Map != Map || !from.InRange(GetWorldLocation(), 3)) - { from.SendLocalizedMessage(500446); // That is too far away. - } else if (!Harrower.CanSpawn) - { from.SendMessage("The harrower has already been spawned."); - } else if (skull == null) - { - SendLocalizedMessageTo(from, 1049488, ""); // That is not my champions awakening skull! - } + SendLocalizedMessageTo(from, 1049488); // That is not my champions awakening skull! else if (m_Skull != null) - { - SendLocalizedMessageTo(from, 1049487, ""); // I already have my champions awakening skull! - } + SendLocalizedMessageTo(from, 1049487); // I already have my champions awakening skull! else if (!skull.IsChildOf(from.Backpack)) - { from.SendLocalizedMessage(1049486); // You can only sacrifice items that are in your backpack! - } else { if (skull.Type == Type) @@ -121,9 +105,7 @@ namespace Server.Engines.CannedEvil Skull = skull; } else - { - SendLocalizedMessageTo(from, 1049488, ""); // That is not my champions awakening skull! - } + SendLocalizedMessageTo(from, 1049488); // That is not my champions awakening skull! } } diff --git a/Projects/Scripts/Engines/CannedEvil/ChampionSpawn.cs b/Projects/Scripts/Engines/CannedEvil/ChampionSpawn.cs index 2cdbe0c67..0ee5a3caf 100644 --- a/Projects/Scripts/Engines/CannedEvil/ChampionSpawn.cs +++ b/Projects/Scripts/Engines/CannedEvil/ChampionSpawn.cs @@ -950,24 +950,24 @@ namespace Server.Engines.CannedEvil Dictionary validEntries = new Dictionary(); - foreach (KeyValuePair kvp in m_DamageEntries) - if (IsEligible(kvp.Key, artifact)) + foreach (var (key, value) in m_DamageEntries) + if (IsEligible(key, artifact)) { - validEntries.Add(kvp.Key, kvp.Value); - totalDamage += kvp.Value; + validEntries.Add(key, value); + totalDamage += value; } int randomDamage = Utility.RandomMinMax(1, totalDamage); totalDamage = 0; - foreach (KeyValuePair kvp in validEntries) + foreach (var (key, value) in validEntries) { - totalDamage += kvp.Value; + totalDamage += value; if (totalDamage >= randomDamage) { - GiveArtifact(kvp.Key, artifact); + GiveArtifact(key, artifact); return; } } @@ -1001,10 +1001,10 @@ namespace Server.Engines.CannedEvil writer.Write(m_SPawnSzMod); writer.Write(m_DamageEntries.Count); - foreach (KeyValuePair kvp in m_DamageEntries) + foreach (var (key, value) in m_DamageEntries) { - writer.Write(kvp.Key); - writer.Write(kvp.Value); + writer.Write(key); + writer.Write(value); } writer.Write(ConfinedRoaming); diff --git a/Projects/Scripts/Engines/Chat/Channel.cs b/Projects/Scripts/Engines/Chat/Channel.cs index bc1a54ba8..127c560bb 100644 --- a/Projects/Scripts/Engines/Chat/Channel.cs +++ b/Projects/Scripts/Engines/Chat/Channel.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; namespace Server.Engines.Chat { @@ -401,18 +402,7 @@ namespace Server.Engines.Chat } } - public static Channel FindChannelByName(string name) - { - for (int i = 0; i < Channels.Count; ++i) - { - Channel channel = Channels[i]; - - if (channel.m_Name == name) - return channel; - } - - return null; - } + public static Channel FindChannelByName(string name) => Channels.FirstOrDefault(channel => channel.m_Name == name); public static void Initialize() { diff --git a/Projects/Scripts/Engines/Chat/Chat.cs b/Projects/Scripts/Engines/Chat/Chat.cs index 705463ec5..0c673dba2 100644 --- a/Projects/Scripts/Engines/Chat/Chat.cs +++ b/Projects/Scripts/Engines/Chat/Chat.cs @@ -1,12 +1,13 @@ using System; using System.IO; +using System.Linq; using Server.Accounting; using Server.Misc; using Server.Network; namespace Server.Engines.Chat { - public class ChatSystem + public static class ChatSystem { public static bool Enabled{ get; set; } = true; @@ -18,7 +19,7 @@ namespace Server.Engines.Chat public static void SendCommandTo(Mobile to, ChatCommand type, string param1 = null, string param2 = null) { - to?.Send(new ChatMessagePacket(null, (int)type + 20, param1, param2)); + ChatPackets.SendChatMessage(to?.NetState, null, (int)type + 20, param1, param2); } public static void OpenChatWindowRequest(NetState state, PacketReader pvSrc) @@ -61,21 +62,11 @@ namespace Server.Engines.Chat { // TODO: Optimize this search - foreach (Account checkAccount in Accounts.GetAccounts()) + if (Accounts.GetAccounts().Cast().Any(checkAccount => Insensitive.Equals(checkAccount.GetTag("ChatName")?.Trim(), chatName))) { - string existingName = checkAccount.GetTag("ChatName"); - - if (existingName != null) - { - existingName = existingName.Trim(); - - if (Insensitive.Equals(existingName, chatName)) - { - from.SendMessage("Nickname already in use."); - SendCommandTo(from, ChatCommand.AskNewNickname); - return; - } - } + from.SendMessage("Nickname already in use."); + SendCommandTo(from, ChatCommand.AskNewNickname); + return; } accountChatName = chatName; @@ -129,17 +120,15 @@ namespace Server.Engines.Chat if (handler.RequireConference && channel == null) user.SendMessage(31); /* You must be in a conference to do this. - * To join a conference, select one from the Conference menu. - */ + * To join a conference, select one from the Conference menu. + */ else if (handler.RequireModerator && !user.IsModerator) user.SendMessage(29); // You must have operator status to do this. else handler.Callback(user, channel, param); } else - { Console.WriteLine("Client: {0}: Unknown chat action 0x{1:X}: {2}", state, actionID, param); - } } catch (Exception e) { @@ -147,4 +136,4 @@ namespace Server.Engines.Chat } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Chat/ChatActionHandlers.cs b/Projects/Scripts/Engines/Chat/ChatActionHandlers.cs index b6ad6c2df..5cf3b95c4 100644 --- a/Projects/Scripts/Engines/Chat/ChatActionHandlers.cs +++ b/Projects/Scripts/Engines/Chat/ChatActionHandlers.cs @@ -1,6 +1,6 @@ namespace Server.Engines.Chat { - public class ChatActionHandlers + public static class ChatActionHandlers { private static ChatActionHandler[] m_Handlers; @@ -112,8 +112,8 @@ namespace Server.Engines.Chat { from.IgnorePrivateMessage = true; from.SendMessage(38); /* You will no longer receive private messages. - * Those who send you a message will be notified that you are blocking incoming messages. - */ + * Those who send you a message will be notified that you are blocking incoming messages. + */ } public static void TogglePrivateMessages(ChatUser from, Channel channel, string param) diff --git a/Projects/Scripts/Engines/Chat/ChatUser.cs b/Projects/Scripts/Engines/Chat/ChatUser.cs index a24ee7508..d2d802da8 100644 --- a/Projects/Scripts/Engines/Chat/ChatUser.cs +++ b/Projects/Scripts/Engines/Chat/ChatUser.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using Server.Accounting; namespace Server.Engines.Chat @@ -64,16 +65,14 @@ namespace Server.Engines.Chat return false; } - public void SendMessage(int number, string param1 = null, string param2 = null) + public void SendMessage(int number, string param1 = "", string param2 = "") { - if (Mobile.NetState != null) - Mobile.Send(new ChatMessagePacket(Mobile, number, param1, param2)); + ChatPackets.SendChatMessage(Mobile.NetState, Mobile, number, param1, param2); } - public void SendMessage(int number, Mobile from, string param1, string param2) + public void SendMessage(int number, Mobile from, string param1 = "", string param2 = "") { - if (Mobile.NetState != null) - Mobile.Send(new ChatMessagePacket(from, number, param1, param2)); + ChatPackets.SendChatMessage(Mobile.NetState, from, number, param1, param2); } public bool IsIgnored(ChatUser check) => Ignored.Contains(check); @@ -81,9 +80,7 @@ namespace Server.Engines.Chat public void AddIgnored(ChatUser user) { if (IsIgnored(user)) - { SendMessage(22, user.Username); // You are already ignoring %1. - } else { Ignored.Add(user); @@ -106,9 +103,7 @@ namespace Server.Engines.Chat SendMessage(26); // You are no longer ignoring anyone. } else - { SendMessage(25, user.Username); // You are not ignoring %1. - } } public static ChatUser AddChatUser(Mobile from) @@ -172,18 +167,7 @@ namespace Server.Engines.Chat return c; } - public static ChatUser GetChatUser(string username) - { - for (int i = 0; i < m_Users.Count; ++i) - { - ChatUser user = m_Users[i]; - - if (user.Username == username) - return user; - } - - return null; - } + public static ChatUser GetChatUser(string username) => m_Users.FirstOrDefault(user => user.Username == username); public static void GlobalSendCommand(ChatCommand command, string param1, string param2 = null) { diff --git a/Projects/Scripts/Engines/Chat/Chatold.cs b/Projects/Scripts/Engines/Chat/Chatold.cs index 0f3626116..2ae2c4f35 100644 --- a/Projects/Scripts/Engines/Chat/Chatold.cs +++ b/Projects/Scripts/Engines/Chat/Chatold.cs @@ -1,6 +1,6 @@ namespace Server.Chat { - public class ChatSystem + public static class ChatSystem { public static void Initialize() { @@ -12,4 +12,4 @@ namespace Server.Chat e.Mobile.SendMessage("Chat is not currently supported."); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Chat/Packets.cs b/Projects/Scripts/Engines/Chat/Packets.cs index 3d8bfd563..ce41aa740 100644 --- a/Projects/Scripts/Engines/Chat/Packets.cs +++ b/Projects/Scripts/Engines/Chat/Packets.cs @@ -1,28 +1,36 @@ +using Server.Buffers; using Server.Network; namespace Server.Engines.Chat { - public sealed class ChatMessagePacket : Packet + public static class ChatPackets { - public ChatMessagePacket(Mobile who, int number, string param1, string param2) : base(0xB2) + public static void SendChatMessage(NetState ns, Mobile who, int number, string param1, string param2) { - if (param1 == null) - param1 = string.Empty; + if (ns == null) + return; - if (param2 == null) - param2 = string.Empty; + param1 ??= ""; + param2 ??= ""; - EnsureCapacity(13 + (param1.Length + param2.Length) * 2); + int length = 13 + (param1.Length + param2.Length) * 2; + //base(0xB2) - m_Stream.Write((ushort)(number - 20)); + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0xB2); // Packet ID + writer.Write((ushort)length); // Dynamic Length + + writer.Write((ushort)(number - 20)); if (who != null) - m_Stream.WriteAsciiFixed(who.Language, 4); + writer.WriteAsciiFixed(who.Language, 4); else - m_Stream.Write(0); + writer.Position += 4; - m_Stream.WriteBigUniNull(param1); - m_Stream.WriteBigUniNull(param2); + writer.WriteBigUniNull(param1); + writer.WriteBigUniNull(param2); + + ns.Send(writer.Span); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/ConPVP/Arena.cs b/Projects/Scripts/Engines/ConPVP/Arena.cs index 12703d633..c8a907a64 100644 --- a/Projects/Scripts/Engines/ConPVP/Arena.cs +++ b/Projects/Scripts/Engines/ConPVP/Arena.cs @@ -512,7 +512,7 @@ namespace Server.Engines.ConPVP if (offset < offsets.Length) p = offsets[offset++]; else - p = offsets[offsets.Length - 1]; + p = offsets[^1]; p.X = p.X * matrix[0, 0] + p.Y * matrix[0, 1]; p.Y = p.X * matrix[1, 0] + p.Y * matrix[1, 1]; @@ -574,12 +574,15 @@ namespace Server.Engines.ConPVP if (hasBounds) { List pets = new List(); + IPooledEnumerable eable = facet.GetMobilesInBounds(m_Bounds); - foreach (Mobile mob in facet.GetMobilesInBounds(m_Bounds)) + foreach (Mobile mob in eable) if (mob is BaseCreature pet && pet.Controlled && pet.ControlMaster != null && Players.Contains(pet.ControlMaster)) pets.Add(pet); + eable.Free(); + foreach (Mobile pet in pets) { pet.Combatant = null; @@ -749,7 +752,7 @@ namespace Server.Engines.ConPVP #region Offsets & Rotation - private static Point2D[] m_EdgeOffsets = + private static readonly Point2D[] m_EdgeOffsets = { /* * /\ @@ -772,7 +775,7 @@ namespace Server.Engines.ConPVP }; // nw corner - private static Point2D[] m_CornerOffsets = + private static readonly Point2D[] m_CornerOffsets = { /* * /\ @@ -793,7 +796,7 @@ namespace Server.Engines.ConPVP new Point2D(3, 0) }; - private static int[][,] m_Rotate = + private static readonly int[][,] m_Rotate = { new[,] { { +1, 0 }, { 0, +1 } }, // west new[,] { { -1, 0 }, { 0, -1 } }, // east diff --git a/Projects/Scripts/Engines/ConPVP/DuelContext.cs b/Projects/Scripts/Engines/ConPVP/DuelContext.cs index d4d2c388f..1d6a546b9 100644 --- a/Projects/Scripts/Engines/ConPVP/DuelContext.cs +++ b/Projects/Scripts/Engines/ConPVP/DuelContext.cs @@ -160,7 +160,7 @@ namespace Server.Engines.ConPVP if (spell is RecallSpell) from.SendMessage("You may not cast this spell."); - string title = null; + string title; string option; if (spell is ArcanistSpell) @@ -854,16 +854,9 @@ namespace Server.Engines.ConPVP Participant p = Participants[i]; if (p.Eliminated) - { - ++eliminated; - - if (eliminated == Participants.Count - 1) - hasWinner = true; - } + hasWinner |= ++eliminated == Participants.Count - 1; else - { winner = p; - } } return hasWinner ? winner ?? Participants[0] : null; @@ -1630,16 +1623,7 @@ namespace Server.Engines.ConPVP int rx = dx - dy; int ry = dx + dy; - bool eastToWest; - - if (rx >= 0 && ry >= 0) - eastToWest = false; - else if (rx >= 0) - eastToWest = true; - else if (ry >= 0) - eastToWest = true; - else - eastToWest = false; + bool eastToWest = (rx < 0 || ry < 0) && (rx >= 0 || ry >= 0); Effects.PlaySound(wall, Arena.Facet, 0x1F6); @@ -1817,9 +1801,7 @@ namespace Server.Engines.ConPVP } } else - { defs = basedef.Options; - } int changes = 0; @@ -1999,9 +1981,7 @@ namespace Server.Engines.ConPVP if (!Registered) return; - if (count != -1) - StartedReadyCountdown = true; - + StartedReadyCountdown |= count != -1; ReadyCount = count; if (count == 0) diff --git a/Projects/Scripts/Engines/ConPVP/Games/BombingRun.cs b/Projects/Scripts/Engines/ConPVP/Games/BombingRun.cs index 76318ee08..406d1121e 100644 --- a/Projects/Scripts/Engines/ConPVP/Games/BombingRun.cs +++ b/Projects/Scripts/Engines/ConPVP/Games/BombingRun.cs @@ -293,7 +293,7 @@ namespace Server.Engines.ConPVP if (list.Count > 0) { - Point3D p = list[list.Count - 1]; + Point3D p = list[^1]; if (p.X != ix || p.Y != iy || p.Z != iz) list.Add(new Point3D(ix, iy, iz)); @@ -308,7 +308,7 @@ namespace Server.Engines.ConPVP z += zslp; } - if (list.Count > 0 && list[list.Count - 1] != dest) + if (list.Count > 0 && list[^1] != dest) list.Add(dest); /*if ( dist3d > 4 && ( dest.X != org.X || dest.Y != org.Y ) ) @@ -429,10 +429,7 @@ namespace Server.Engines.ConPVP if (t.Z <= point.Z && t.Z + height >= point.Z && (id.Flags & (TileFlag.Impassable | TileFlag.Wall | TileFlag.NoShoot)) != 0) { - if (i > m_PathIdx) - point = m_Path[i - 1]; - else - point = GetWorldLocation(); + point = i > m_PathIdx ? m_Path[i - 1] : GetWorldLocation(); HitObject(point, t.Z, height); return; } @@ -448,13 +445,9 @@ namespace Server.Engines.ConPVP continue; if (i is BRGoal) - { height = 17; - } else if (i is Blocker) - { height = 20; - } else { ItemData id = i.ItemData; @@ -473,10 +466,7 @@ namespace Server.Engines.ConPVP (i is Blocker || loc.Z <= point.Z && loc.Z + height >= point.Z)) { found = true; - if (j > m_PathIdx) - point = m_Path[j - 1]; - else - point = GetWorldLocation(); + point = j > m_PathIdx ? m_Path[j - 1] : GetWorldLocation(); break; } } @@ -494,9 +484,7 @@ namespace Server.Engines.ConPVP HitObject(point, loc.Z, height); } else - { HitObject(point, loc.Z, height); - } return; } @@ -511,12 +499,11 @@ namespace Server.Engines.ConPVP if (m == null || m == Thrower) continue; - Point3D point; Point3D loc = m.Location; for (int j = m_PathIdx; j < pathCheckEnd && !found; j++) { - point = m_Path[j]; + Point3D point = m_Path[j]; if (loc.X == point.X && loc.Y == point.Y && loc.Z <= point.Z && loc.Z + 16 >= point.Z) @@ -550,9 +537,10 @@ namespace Server.Engines.ConPVP else if (m_Path.Count > 0) MoveToWorld(m_Path.Last); - int myZ = Map.GetAverageZ(X, Y); + int myZ = Map?.GetAverageZ(X, Y) ?? 0; + + StaticTile[] statics = Map?.Tiles?.GetStaticTiles(X, Y, true) ?? new StaticTile[0]; - StaticTile[] statics = Map.Tiles.GetStaticTiles(X, Y, true); for (int j = 0; j < statics.Length; j++) { StaticTile t = statics[j]; @@ -676,7 +664,7 @@ namespace Server.Engines.ConPVP if (m_Bomb.Parent == null && m_Bomb.m_Game?.Controller != null) { if (!m_Bomb.m_Flying && m_Bomb.Map != Map.Internal) - Effects.SendLocationEffect(m_Bomb.GetWorldLocation(), m_Bomb.Map, 0x377A, 16, 10, m_Bomb.Hue, 0); + Effects.SendLocationEffect(m_Bomb.GetWorldLocation(), m_Bomb.Map, 0x377A, 16, 10, m_Bomb.Hue); if (m_Bomb.Location != m_Bomb.m_Game.Controller.BombHome) { @@ -983,9 +971,7 @@ namespace Server.Engines.ConPVP total = entries.Count; } else - foreach (BRPlayerInfo player in section.Players.Values) - if (player.Score > 0) - total++; + total += section.Players.Values.Count(player => player.Score > 0); entries.Sort(); @@ -1722,12 +1708,13 @@ namespace Server.Engines.ConPVP for (int i = 0; i < m_Context.Participants.Count; ++i) { - if (!(m_Context.Participants[i] is Participant p) || p.Players == null) + DuelPlayer[] players = m_Context.Participants[i]?.Players; + if (players == null) continue; - for (int j = 0; j < p.Players.Length; ++j) + for (int j = 0; j < players.Length; ++j) { - DuelPlayer dp = p.Players[j]; + DuelPlayer dp = players[j]; if (dp?.Mobile != null) { @@ -1736,16 +1723,16 @@ namespace Server.Engines.ConPVP } } - if (i == winner.TeamID) + if (i == winner?.TeamID) continue; - if (p.Players != null) - for (int j = 0; j < p.Players.Length; ++j) - if (p.Players[j] != null) - p.Players[j].Eliminated = true; + for (int j = 0; j < players.Length; ++j) + if (players[j] != null) + players[j].Eliminated = true; } - m_Context.Finish(m_Context.Participants[winner.TeamID]); + if (winner != null) + m_Context.Finish(m_Context.Participants[winner.TeamID]); } public override void OnStop() diff --git a/Projects/Scripts/Engines/ConPVP/Games/CTF.cs b/Projects/Scripts/Engines/ConPVP/Games/CTF.cs index 608e1543c..9d631f312 100644 --- a/Projects/Scripts/Engines/ConPVP/Games/CTF.cs +++ b/Projects/Scripts/Engines/ConPVP/Games/CTF.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Text; using Server.Gumps; using Server.Items; @@ -70,17 +71,13 @@ namespace Server.Engines.ConPVP { CTFTeamInfo teamInfo = game.Controller.TeamInfo[i % 8]; - if (teamInfo?.Flag == null) - continue; - - entries.Add(teamInfo); + if (teamInfo?.Flag != null) + entries.Add(teamInfo); } else - foreach (CTFPlayerInfo player in section.Players.Values) - if (player.Score > 0) - entries.Add(player); + entries.AddRange(section.Players.Values.Where(player => player.Score > 0)); - entries.Sort(delegate(IRankedCTF a, IRankedCTF b) { return b.Score - a.Score; }); + entries.Sort((a, b) => b.Score - a.Score); int height = 0; @@ -111,7 +108,8 @@ namespace Server.Engines.ConPVP if (section == null) for (int i = 0; i < entries.Count; ++i) { - CTFTeamInfo teamInfo = entries[i] as CTFTeamInfo; + if (!(entries[i] is CTFTeamInfo teamInfo)) + continue; AddImage(30, 70 + i * 75, 10152); AddImage(30, 85 + i * 75, 10151); @@ -194,10 +192,7 @@ namespace Server.Engines.ConPVP private void AddColoredText(int x, int y, int width, int height, string text, int color) { - if (color == 0) - AddHtml(x, y, width, height, text); - else - AddHtml(x, y, width, height, Color(text, color)); + AddHtml(x, y, width, height, color == 0 ? text : Color(text, color)); } } @@ -246,10 +241,8 @@ namespace Server.Engines.ConPVP else if (ourTeam == useTeam) { if (Location == m_TeamInfo.Origin && Map == m_TeamInfo.Game.Facet) - { - from.Send(new UnicodeMessage(Serial, ItemID, MessageType.Regular, 0x3B2, 3, "ENU", Name, - "Touch me not for I am chaste.")); - } + Packets.SendUnicodeMessage(from.NetState, Serial, ItemID, MessageType.Regular, 0x3B2, 3, "ENU", Name, + "Touch me not for I am chaste."); else { CTFPlayerInfo playerInfo = useTeam[from]; @@ -306,9 +299,7 @@ namespace Server.Engines.ConPVP m_ReturnCount = Math.Min(m_ReturnCount, 10); } else - { SendHome(); - } } private void StopCountdown() @@ -417,9 +408,7 @@ namespace Server.Engines.ConPVP } } else - { from.LocalOverheadMessage(MessageType.Regular, 0x26, false, "Those are not my cookies."); - } } else if (obj is Mobile passTo) { @@ -943,15 +932,8 @@ namespace Server.Engines.ConPVP if (ourFlagCarrier != null && GetTeamInfo(ourFlagCarrier) == teamInfo) { - for (int j = 0; j < ourFlagCarrier.Aggressors.Count; ++j) - { - if (!(ourFlagCarrier.Aggressors[j] is AggressorInfo aggr) || - aggr.Defender != ourFlagCarrier || aggr.Attacker != mob) - continue; - + if (ourFlagCarrier.Aggressors.Any(t => t.Defender == ourFlagCarrier && t.Attacker == mob)) playerInfo.Score += 2; // helped defend guy capturing enemy flag - break; - } if (mob.Map == ourFlagCarrier.Map && ourFlagCarrier.InRange(mob, 12)) playerInfo.Score += 1; // helped defend guy capturing enemy flag diff --git a/Projects/Scripts/Engines/ConPVP/Games/DoubleDom.cs b/Projects/Scripts/Engines/ConPVP/Games/DoubleDom.cs index 48080203b..d516600cf 100644 --- a/Projects/Scripts/Engines/ConPVP/Games/DoubleDom.cs +++ b/Projects/Scripts/Engines/ConPVP/Games/DoubleDom.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Text; using Server.Gumps; using Server.Items; @@ -72,11 +73,9 @@ namespace Server.Engines.ConPVP entries.Add(teamInfo); } else - foreach (DDPlayerInfo player in section.Players.Values) - if (player.Score > 0) - entries.Add(player); + entries.AddRange(section.Players.Values.Where(player => player.Score > 0)); - entries.Sort(delegate(IRankedCTF a, IRankedCTF b) { return b.Score - a.Score; }); + entries.Sort((a, b) => b.Score - a.Score); int height = 0; @@ -107,7 +106,8 @@ namespace Server.Engines.ConPVP if (section == null) for (int i = 0; i < entries.Count; ++i) { - DDTeamInfo teamInfo = entries[i] as DDTeamInfo; + if (!(entries[i] is DDTeamInfo teamInfo)) + continue; AddImage(30, 70 + i * 75, 10152); AddImage(30, 85 + i * 75, 10151); diff --git a/Projects/Scripts/Engines/ConPVP/Games/KingOfTheHill.cs b/Projects/Scripts/Engines/ConPVP/Games/KingOfTheHill.cs index 5beded8eb..188ea8670 100644 --- a/Projects/Scripts/Engines/ConPVP/Games/KingOfTheHill.cs +++ b/Projects/Scripts/Engines/ConPVP/Games/KingOfTheHill.cs @@ -171,8 +171,7 @@ namespace Server.Engines.ConPVP King = m; - if (m_KingTimer == null) - m_KingTimer = new KingTimer(this); + m_KingTimer ??= new KingTimer(this); m_KingTimer.Stop(); m_KingTimer.StartHillTicker(); @@ -1113,12 +1112,13 @@ namespace Server.Engines.ConPVP for (int i = 0; i < m_Context.Participants.Count; ++i) { - if (!(m_Context.Participants[i] is Participant p) || p.Players == null) + DuelPlayer[] players = m_Context.Participants[i]?.Players; + if (players == null) continue; - for (int j = 0; j < p.Players.Length; ++j) + for (int j = 0; j < players.Length; ++j) { - DuelPlayer dp = p.Players[j]; + DuelPlayer dp = players[j]; if (dp?.Mobile != null) { @@ -1130,10 +1130,9 @@ namespace Server.Engines.ConPVP if (i == winner?.TeamID) continue; - if (p.Players != null) - for (int j = 0; j < p.Players.Length; ++j) - if (p.Players[j] != null) - p.Players[j].Eliminated = true; + for (int j = 0; j < players.Length; ++j) + if (players[j] != null) + players[j].Eliminated = true; } if (winner != null) @@ -1149,7 +1148,7 @@ namespace Server.Engines.ConPVP if (Controller.Hills[i] != null) Controller.Hills[i].Game = null; - foreach (KHBoard board in Controller.Boards) + foreach (var board in Controller.Boards) if (board != null) board.m_Game = null; diff --git a/Projects/Scripts/Engines/ConPVP/Games/TourneyMatch.cs b/Projects/Scripts/Engines/ConPVP/Games/TourneyMatch.cs index 1642a504f..e14e4840e 100644 --- a/Projects/Scripts/Engines/ConPVP/Games/TourneyMatch.cs +++ b/Projects/Scripts/Engines/ConPVP/Games/TourneyMatch.cs @@ -106,7 +106,7 @@ namespace Server.Engines.ConPVP foreach (Mobile view in mob.GetMobilesInRange(18)) if (!mob.CanSee(view)) - mob.Send(view.RemovePacket); + Packets.SendRemoveEntity(mob.NetState, view.Serial); mob.LocalOverheadMessage(MessageType.Emote, 0x3B2, false, "* Your mind focuses intently on the fight and all other distractions fade away *"); diff --git a/Projects/Scripts/Engines/ConPVP/Gumps/RulesetGump.cs b/Projects/Scripts/Engines/ConPVP/Gumps/RulesetGump.cs index f1359bae4..fe6842107 100644 --- a/Projects/Scripts/Engines/ConPVP/Gumps/RulesetGump.cs +++ b/Projects/Scripts/Engines/ConPVP/Gumps/RulesetGump.cs @@ -93,9 +93,7 @@ namespace Server.Engines.ConPVP for (int i = 0; i < info.Switches.Length; ++i) { int sid = info.Switches[i]; - - if (sid >= 0 && sid < m_Page.Options.Length) - opts[sid] = true; + opts[sid] |= sid >= 0 && sid < m_Page.Options.Length; } for (int i = 0; i < opts.Length; ++i) diff --git a/Projects/Scripts/Engines/ConPVP/Participant.cs b/Projects/Scripts/Engines/ConPVP/Participant.cs index 2f83d7fbe..9c5f8fbe1 100644 --- a/Projects/Scripts/Engines/ConPVP/Participant.cs +++ b/Projects/Scripts/Engines/ConPVP/Participant.cs @@ -173,7 +173,7 @@ namespace Server.Engines.ConPVP } Resize(Players.Length + 1); - Players[Players.Length - 1] = new DuelPlayer(player, this); + Players[^1] = new DuelPlayer(player, this); } public void Resize(int count) diff --git a/Projects/Scripts/Engines/ConPVP/Tournament.cs b/Projects/Scripts/Engines/ConPVP/Tournament.cs index bd2e9c569..355498447 100644 --- a/Projects/Scripts/Engines/ConPVP/Tournament.cs +++ b/Projects/Scripts/Engines/ConPVP/Tournament.cs @@ -433,7 +433,7 @@ namespace Server.Engines.ConPVP if (Pyramid.Levels.Count < 1) break; - PyramidLevel top = Pyramid.Levels[Pyramid.Levels.Count - 1]; + PyramidLevel top = Pyramid.Levels[^1]; if (top.FreeAdvance != null || top.Matches.Count != 1) break; @@ -451,7 +451,7 @@ namespace Server.Engines.ConPVP if (Pyramid.Levels.Count < 2) break; - PyramidLevel top = Pyramid.Levels[Pyramid.Levels.Count - 1]; + PyramidLevel top = Pyramid.Levels[^1]; if (top.FreeAdvance != null || top.Matches.Count != 1) break; @@ -471,7 +471,7 @@ namespace Server.Engines.ConPVP GiveAwards(part.Players, TrophyRank.Silver, cash / 2); } - PyramidLevel next = Pyramid.Levels[Pyramid.Levels.Count - 2]; + PyramidLevel next = Pyramid.Levels[^2]; if (next.Matches.Count > 2) break; @@ -495,7 +495,7 @@ namespace Server.Engines.ConPVP } } - private void GiveAwards(List players, TrophyRank rank, int cash) + private void GiveAwards(IReadOnlyList players, TrophyRank rank, int cash) { if (players.Count == 0) return; @@ -663,69 +663,39 @@ namespace Server.Engines.ConPVP try { if (EventController != null) - { Alert("The tournament has completed!", $"Team {EventController.GetTeamName(Pyramid.Levels[0].Matches[0].Participants.IndexOf(winner))} has won!"); - } else if (TourneyType == TourneyType.RandomTeam) - { Alert("The tournament has completed!", $"Team {Pyramid.Levels[0].Matches[0].Participants.IndexOf(winner) + 1} has won!"); - } else if (TourneyType == TourneyType.Faction) { if (m_ParticipantsPerMatch == 4) { - string name = "(null)"; - - switch (Pyramid.Levels[0].Matches[0].Participants.IndexOf( - winner)) + string name = Pyramid.Levels[0].Matches[0].Participants.IndexOf(winner) switch { - case 0: - { - name = "Minax"; - break; - } - case 1: - { - name = "Council of Mages"; - break; - } - case 2: - { - name = "True Britannians"; - break; - } - case 3: - { - name = "Shadowlords"; - break; - } - } + 0 => "Minax", + 1 => "Council of Mages", + 2 => "True Britannians", + 3 => "Shadowlords", + _ => "(null)" + }; Alert("The tournament has completed!", $"The {name} team has won!"); } else if (m_ParticipantsPerMatch == 2) - { Alert("The tournament has completed!", $"The {(Pyramid.Levels[0].Matches[0].Participants.IndexOf(winner) == 0 ? "Evil" : "Hero")} team has won!"); - } else - { Alert("The tournament has completed!", $"Team {Pyramid.Levels[0].Matches[0].Participants.IndexOf(winner) + 1} has won!"); - } } else if (TourneyType == TourneyType.RedVsBlue) - { Alert("The tournament has completed!", $"Team {(Pyramid.Levels[0].Matches[0].Participants.IndexOf(winner) == 0 ? "Red" : "Blue")} has won!"); - } else - { Alert("The tournament has completed!", $"{winner.NameList} {(winner.Players.Count > 1 ? "are" : "is")} the champion{(winner.Players.Count == 1 ? "" : "s")}."); - } } catch { @@ -739,7 +709,7 @@ namespace Server.Engines.ConPVP } else if (Pyramid.Levels.Count > 0) { - PyramidLevel activeLevel = Pyramid.Levels[Pyramid.Levels.Count - 1]; + PyramidLevel activeLevel = Pyramid.Levels[^1]; bool stillGoing = false; for (int i = 0; i < activeLevel.Matches.Count; ++i) @@ -846,7 +816,6 @@ namespace Server.Engines.ConPVP $"The {(Pyramid.Levels[0].Matches[0].Participants.IndexOf(winner) == 0 ? "Evil" : "Hero")} team has won!"); } else - { Alert("The tournament has completed!", $"Team {Pyramid.Levels[0].Matches[0].Participants.IndexOf(winner) + 1} has won!"); } diff --git a/Projects/Scripts/Engines/Craft/Core/CraftItem.cs b/Projects/Scripts/Engines/Craft/Core/CraftItem.cs index 23611a3ed..c53651f36 100644 --- a/Projects/Scripts/Engines/Craft/Core/CraftItem.cs +++ b/Projects/Scripts/Engines/Craft/Core/CraftItem.cs @@ -484,8 +484,7 @@ namespace Server.Engines.Craft if (m_TypesTable[j][0] == baseType) types[i] = m_TypesTable[j]; - if (types[i] == null) - types[i] = new[] { baseType }; + types[i] ??= new[] { baseType }; amounts[i] = craftRes.Amount; @@ -910,8 +909,7 @@ namespace Server.Engines.Craft hammer.Delete(); } - if (tool.UsesRemaining < 1 && tool.BreakOnDepletion) - toolBroken = true; + toolBroken |= tool.UsesRemaining < 1 && tool.BreakOnDepletion; if (toolBroken) tool.Delete(); @@ -1033,8 +1031,7 @@ namespace Server.Engines.Craft tool.UsesRemaining--; - if (tool.UsesRemaining < 1 && tool.BreakOnDepletion) - toolBroken = true; + toolBroken |= tool.UsesRemaining < 1 && tool.BreakOnDepletion; if (toolBroken) tool.Delete(); diff --git a/Projects/Scripts/Engines/Craft/Core/Recipes.cs b/Projects/Scripts/Engines/Craft/Core/Recipes.cs index a2b3578c3..74e5179d1 100644 --- a/Projects/Scripts/Engines/Craft/Core/Recipes.cs +++ b/Projects/Scripts/Engines/Craft/Core/Recipes.cs @@ -33,7 +33,7 @@ namespace Server.Engines.Craft public int ID{ get; } - public TextDefinition TextDefinition => m_TD ?? (m_TD = new TextDefinition(CraftItem.NameNumber, CraftItem.NameString)); + public TextDefinition TextDefinition => m_TD ??= new TextDefinition(CraftItem.NameNumber, CraftItem.NameString); public static void Initialize() { @@ -52,15 +52,13 @@ namespace Server.Engines.Craft { if (targeted is PlayerMobile mobile) { - foreach (KeyValuePair kvp in Recipes) - mobile.AcquireRecipe(kvp.Key); + foreach (var (key, _) in Recipes) + mobile.AcquireRecipe(key); m.SendMessage("You teach them all of the recipes."); } else - { m.SendMessage("That is not a player!"); - } }); } @@ -86,4 +84,4 @@ namespace Server.Engines.Craft }); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Craft/Core/Repair.cs b/Projects/Scripts/Engines/Craft/Core/Repair.cs index 2d74fc499..2fff2c4cb 100644 --- a/Projects/Scripts/Engines/Craft/Core/Repair.cs +++ b/Projects/Scripts/Engines/Craft/Core/Repair.cs @@ -491,7 +491,7 @@ namespace Server.Engines.Craft if (!usingDeed) { - CraftContext context = m_CraftSystem.GetContext(from); + m_CraftSystem.GetContext(from); from.SendGump(new CraftGump(from, m_CraftSystem, m_Tool, number)); } else @@ -504,4 +504,4 @@ namespace Server.Engines.Craft } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Craft/DefAlchemy.cs b/Projects/Scripts/Engines/Craft/DefAlchemy.cs index 85746fc1f..bfdeef6c8 100644 --- a/Projects/Scripts/Engines/Craft/DefAlchemy.cs +++ b/Projects/Scripts/Engines/Craft/DefAlchemy.cs @@ -17,7 +17,7 @@ namespace Server.Engines.Craft public override int GumpTitleNumber => 1044001; - public static CraftSystem CraftSystem => m_CraftSystem ?? (m_CraftSystem = new DefAlchemy()); + public static CraftSystem CraftSystem => m_CraftSystem ??= new DefAlchemy(); public override double GetChanceAtMin(CraftItem item) => 0.0; diff --git a/Projects/Scripts/Engines/Craft/DefBlacksmithy.cs b/Projects/Scripts/Engines/Craft/DefBlacksmithy.cs index c68c961ab..a5f98f5b4 100644 --- a/Projects/Scripts/Engines/Craft/DefBlacksmithy.cs +++ b/Projects/Scripts/Engines/Craft/DefBlacksmithy.cs @@ -30,7 +30,7 @@ namespace Server.Engines.Craft public override int GumpTitleNumber => 1044002; - public static CraftSystem CraftSystem => m_CraftSystem ?? (m_CraftSystem = new DefBlacksmithy()); + public static CraftSystem CraftSystem => m_CraftSystem ??= new DefBlacksmithy(); public override CraftECA ECA => CraftECA.ChanceMinusSixtyToFourtyFive; diff --git a/Projects/Scripts/Engines/Craft/DefBowFletching.cs b/Projects/Scripts/Engines/Craft/DefBowFletching.cs index 1af14ebf7..c5a676fb8 100644 --- a/Projects/Scripts/Engines/Craft/DefBowFletching.cs +++ b/Projects/Scripts/Engines/Craft/DefBowFletching.cs @@ -15,7 +15,7 @@ namespace Server.Engines.Craft public override int GumpTitleNumber => 1044006; - public static CraftSystem CraftSystem => m_CraftSystem ?? (m_CraftSystem = new DefBowFletching()); + public static CraftSystem CraftSystem => m_CraftSystem ??= new DefBowFletching(); public override CraftECA ECA => CraftECA.FiftyPercentChanceMinusTenPercent; diff --git a/Projects/Scripts/Engines/Craft/DefCarpentry.cs b/Projects/Scripts/Engines/Craft/DefCarpentry.cs index 4e965a2f0..3d2427ce9 100644 --- a/Projects/Scripts/Engines/Craft/DefCarpentry.cs +++ b/Projects/Scripts/Engines/Craft/DefCarpentry.cs @@ -15,7 +15,7 @@ namespace Server.Engines.Craft public override int GumpTitleNumber => 1044004; - public static CraftSystem CraftSystem => m_CraftSystem ?? (m_CraftSystem = new DefCarpentry()); + public static CraftSystem CraftSystem => m_CraftSystem ??= new DefCarpentry(); public override double GetChanceAtMin(CraftItem item) => 0.5; diff --git a/Projects/Scripts/Engines/Craft/DefCartography.cs b/Projects/Scripts/Engines/Craft/DefCartography.cs index 370664838..3da613c7a 100644 --- a/Projects/Scripts/Engines/Craft/DefCartography.cs +++ b/Projects/Scripts/Engines/Craft/DefCartography.cs @@ -15,7 +15,7 @@ namespace Server.Engines.Craft public override int GumpTitleNumber => 1044008; - public static CraftSystem CraftSystem => m_CraftSystem ?? (m_CraftSystem = new DefCartography()); + public static CraftSystem CraftSystem => m_CraftSystem ??= new DefCartography(); public override double GetChanceAtMin(CraftItem item) => 0.0; diff --git a/Projects/Scripts/Engines/Craft/DefCooking.cs b/Projects/Scripts/Engines/Craft/DefCooking.cs index b37f7d4af..242cae9f8 100644 --- a/Projects/Scripts/Engines/Craft/DefCooking.cs +++ b/Projects/Scripts/Engines/Craft/DefCooking.cs @@ -15,7 +15,7 @@ namespace Server.Engines.Craft public override int GumpTitleNumber => 1044003; - public static CraftSystem CraftSystem => m_CraftSystem ?? (m_CraftSystem = new DefCooking()); + public static CraftSystem CraftSystem => m_CraftSystem ??= new DefCooking(); public override CraftECA ECA => CraftECA.ChanceMinusSixtyToFourtyFive; diff --git a/Projects/Scripts/Engines/Craft/DefGlassblowing.cs b/Projects/Scripts/Engines/Craft/DefGlassblowing.cs index 4daf3d40f..edfe0a8b4 100644 --- a/Projects/Scripts/Engines/Craft/DefGlassblowing.cs +++ b/Projects/Scripts/Engines/Craft/DefGlassblowing.cs @@ -16,7 +16,7 @@ namespace Server.Engines.Craft public override int GumpTitleNumber => 1044622; - public static CraftSystem CraftSystem => m_CraftSystem ?? (m_CraftSystem = new DefGlassblowing()); + public static CraftSystem CraftSystem => m_CraftSystem ??= new DefGlassblowing(); public override double GetChanceAtMin(CraftItem item) => item.ItemType == typeof(HollowPrism) ? 0.5 : 0.0; diff --git a/Projects/Scripts/Engines/Craft/DefInscription.cs b/Projects/Scripts/Engines/Craft/DefInscription.cs index d8a5892eb..42a884656 100644 --- a/Projects/Scripts/Engines/Craft/DefInscription.cs +++ b/Projects/Scripts/Engines/Craft/DefInscription.cs @@ -36,7 +36,7 @@ namespace Server.Engines.Craft public override int GumpTitleNumber => 1044009; - public static CraftSystem CraftSystem => m_CraftSystem ?? (m_CraftSystem = new DefInscription()); + public static CraftSystem CraftSystem => m_CraftSystem ??= new DefInscription(); public override double GetChanceAtMin(CraftItem item) => 0.0; diff --git a/Projects/Scripts/Engines/Craft/DefMasonry.cs b/Projects/Scripts/Engines/Craft/DefMasonry.cs index 66b193e29..a4aefbb5c 100644 --- a/Projects/Scripts/Engines/Craft/DefMasonry.cs +++ b/Projects/Scripts/Engines/Craft/DefMasonry.cs @@ -16,7 +16,7 @@ namespace Server.Engines.Craft public override int GumpTitleNumber => 1044500; - public static CraftSystem CraftSystem => m_CraftSystem ?? (m_CraftSystem = new DefMasonry()); + public static CraftSystem CraftSystem => m_CraftSystem ??= new DefMasonry(); public override double GetChanceAtMin(CraftItem item) => 0.0; diff --git a/Projects/Scripts/Engines/Craft/DefTailoring.cs b/Projects/Scripts/Engines/Craft/DefTailoring.cs index cc4185fb8..826b3fc21 100644 --- a/Projects/Scripts/Engines/Craft/DefTailoring.cs +++ b/Projects/Scripts/Engines/Craft/DefTailoring.cs @@ -23,7 +23,7 @@ namespace Server.Engines.Craft public override int GumpTitleNumber => 1044005; - public static CraftSystem CraftSystem => m_CraftSystem ?? (m_CraftSystem = new DefTailoring()); + public static CraftSystem CraftSystem => m_CraftSystem ??= new DefTailoring(); public override CraftECA ECA => CraftECA.ChanceMinusSixtyToFourtyFive; diff --git a/Projects/Scripts/Engines/Craft/DefTinkering.cs b/Projects/Scripts/Engines/Craft/DefTinkering.cs index e2cd7f346..f38af4961 100644 --- a/Projects/Scripts/Engines/Craft/DefTinkering.cs +++ b/Projects/Scripts/Engines/Craft/DefTinkering.cs @@ -31,7 +31,7 @@ namespace Server.Engines.Craft public override int GumpTitleNumber => 1044007; - public static CraftSystem CraftSystem => m_CraftSystem ?? (m_CraftSystem = new DefTinkering()); + public static CraftSystem CraftSystem => m_CraftSystem ??= new DefTinkering(); public override double GetChanceAtMin(CraftItem item) { diff --git a/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleController.cs b/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleController.cs index 4dbad8c90..de6aca895 100644 --- a/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleController.cs +++ b/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleController.cs @@ -5,11 +5,6 @@ using Server.Mobiles; using Server.Network; using Server.Spells; -/* - this is From me to you, Under no terms, Conditions... K? to apply you - just simply Unpatch/delete, Stick these in, Same location.. Restart - */ - namespace Server.Engines.Doom { public class LeverPuzzleController : Item @@ -326,7 +321,7 @@ namespace Server.Engines.Doom SendLocationEffect(lp_Center, 0x1153, 0, 60, 1); PlaySounds(lp_Center, cs1); - Effects.SendBoltEffect(player, true); + Effects.SendBoltEffect(player); player.MoveToWorld(lr_Enter, Map.Malas); m_Timer = new LampRoomTimer(this); @@ -417,25 +412,24 @@ namespace Server.Engines.Doom public static void SendLocationEffect(IPoint3D p, int itemID, int speed, int duration, int hue) { - Effects.SendPacket(p, Map.Malas, new LocationEffect(p, itemID, speed, duration, hue, 0)); + Effects.SendLocationEffect(p, Map.Malas, itemID, speed, duration, hue); } public static void PlayerSendASCII(Mobile player, int index) { - player.Send(new AsciiMessage(Serial.MinusOne, 0xFFFF, MessageType.Label, MsgParams[index][0], - MsgParams[index][1], null, Msgs[index])); + Packets.SendAsciiMessage(player.NetState, Serial.MinusOne, 0xFFFF, MessageType.Label, MsgParams[index][0], + MsgParams[index][1], null, Msgs[index]); } /* I cant find any better way to send "speech" using fonts other than default */ public static void POHMessage(Mobile from, int index) { - Packet p = new AsciiMessage(from.Serial, from.Body, MessageType.Regular, MsgParams[index][0], + IPooledEnumerable eable = from.Map.GetClientsInRange(from.Location); + foreach (NetState state in eable) + Packets.SendAsciiMessage(state, from.Serial, from.Body, MessageType.Regular, MsgParams[index][0], MsgParams[index][1], from.Name, Msgs[index]); - p.Acquire(); - foreach (NetState state in from.Map.GetClientsInRange(from.Location)) - state.Send(p); - Packet.Release(p); + eable.Free(); } public override void Serialize(GenericWriter writer) diff --git a/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleItems.cs b/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleItems.cs index 967aaa563..322b3ea97 100644 --- a/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleItems.cs +++ b/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleItems.cs @@ -39,7 +39,7 @@ namespace Server.Engines.Doom public void CallBackMessage() { - PublicOverheadMessage(MessageType.Regular, 0x3B2, 1060003, ""); // You try to pry the box open... + PublicOverheadMessage(MessageType.Regular, 0x3B2, 1060003); // You try to pry the box open... } public override void OnAfterDelete() diff --git a/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleRegions.cs b/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleRegions.cs index 193961bae..443285803 100644 --- a/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleRegions.cs +++ b/Projects/Scripts/Engines/Doom/LeverPuzzle/LeverPuzzleRegions.cs @@ -77,17 +77,15 @@ namespace Server.Engines.Doom public Mobile m_Occupant; public LeverPuzzleRegion(LeverPuzzleController controller, int[] loc) - : base(null, Map.Malas, Find(LeverPuzzleController.lr_Enter, Map.Malas), new Rectangle2D(loc[0], loc[1], 1, 1)) - { + : base(null, Map.Malas, Find(LeverPuzzleController.lr_Enter, Map.Malas), new Rectangle2D(loc[0], loc[1], 1, 1)) => Register(); - } [CommandProperty(AccessLevel.GameMaster)] public Mobile Occupant => m_Occupant?.Alive == true ? m_Occupant : null; public override void OnEnter(Mobile m) { - if (m != null && m_Occupant == null && m is PlayerMobile && m.Alive) + if (m_Occupant == null && m is PlayerMobile && m.Alive) m_Occupant = m; } diff --git a/Projects/Scripts/Engines/Ethics/Core/Ethic.cs b/Projects/Scripts/Engines/Ethics/Core/Ethic.cs index 555add67a..7cf6bbb93 100644 --- a/Projects/Scripts/Engines/Ethics/Core/Ethic.cs +++ b/Projects/Scripts/Engines/Ethics/Core/Ethic.cs @@ -93,8 +93,8 @@ namespace Server.Ethics if (IsImbued(child, true)) return true; - return false; - } + public static bool IsImbued(Item item, bool recurse) => + Find(item) != null || recurse && item.Items.Any(child => IsImbued(child, true)); public static void Initialize() { diff --git a/Projects/Scripts/Engines/Ethics/Evil/Powers/Blight.cs b/Projects/Scripts/Engines/Ethics/Evil/Powers/Blight.cs index 59a4216e4..3d1d981cd 100644 --- a/Projects/Scripts/Engines/Ethics/Evil/Powers/Blight.cs +++ b/Projects/Scripts/Engines/Ethics/Evil/Powers/Blight.cs @@ -33,7 +33,9 @@ namespace Server.Ethics.Evil SpellHelper.GetSurfaceTop(ref p); - foreach (Mobile mob in from.Mobile.GetMobilesInRange(6)) + IPooledEnumerable eable = from.Mobile.GetMobilesInRange(6); + + foreach (Mobile mob in eable) { if (mob == from.Mobile || !SpellHelper.ValidIndirectTarget(from.Mobile, mob)) continue; @@ -54,6 +56,8 @@ namespace Server.Ethics.Evil powerFunctioned = true; } + eable.Free(); + if (powerFunctioned) { SpellHelper.Turn(from.Mobile, p); @@ -71,4 +75,4 @@ namespace Server.Ethics.Evil } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Ethics/Evil/Powers/UnholySense.cs b/Projects/Scripts/Engines/Ethics/Evil/Powers/UnholySense.cs index faf336aad..d62d6ea36 100644 --- a/Projects/Scripts/Engines/Ethics/Evil/Powers/UnholySense.cs +++ b/Projects/Scripts/Engines/Ethics/Evil/Powers/UnholySense.cs @@ -80,13 +80,11 @@ namespace Server.Ethics.Evil } } else - { sb.Append('.'); - } from.Mobile.LocalOverheadMessage(MessageType.Regular, 0x59, false, sb.ToString()); FinishInvoke(from); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Ethics/Hero/Powers/Bless.cs b/Projects/Scripts/Engines/Ethics/Hero/Powers/Bless.cs index f6ecfc8a6..b08df7afe 100644 --- a/Projects/Scripts/Engines/Ethics/Hero/Powers/Bless.cs +++ b/Projects/Scripts/Engines/Ethics/Hero/Powers/Bless.cs @@ -33,7 +33,9 @@ namespace Server.Ethics.Hero SpellHelper.GetSurfaceTop(ref p); - foreach (Mobile mob in from.Mobile.GetMobilesInRange(6)) + IPooledEnumerable eable = from.Mobile.GetMobilesInRange(6); + + foreach (Mobile mob in eable) { if (mob != from.Mobile && SpellHelper.ValidIndirectTarget(from.Mobile, mob)) continue; @@ -54,6 +56,8 @@ namespace Server.Ethics.Hero powerFunctioned = true; } + eable.Free(); + if (powerFunctioned) { SpellHelper.Turn(from.Mobile, p); @@ -71,4 +75,4 @@ namespace Server.Ethics.Hero } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Ethics/Hero/Powers/HolySense.cs b/Projects/Scripts/Engines/Ethics/Hero/Powers/HolySense.cs index dff3df97c..9a625cc2b 100644 --- a/Projects/Scripts/Engines/Ethics/Hero/Powers/HolySense.cs +++ b/Projects/Scripts/Engines/Ethics/Hero/Powers/HolySense.cs @@ -80,13 +80,11 @@ namespace Server.Ethics.Hero } } else - { sb.Append('.'); - } from.Mobile.LocalOverheadMessage(MessageType.Regular, 0x59, false, sb.ToString()); FinishInvoke(from); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Factions/Core/Faction.cs b/Projects/Scripts/Engines/Factions/Core/Faction.cs index 4f9e0c0a4..39861a99a 100644 --- a/Projects/Scripts/Engines/Factions/Core/Faction.cs +++ b/Projects/Scripts/Engines/Factions/Core/Faction.cs @@ -8,7 +8,6 @@ using Server.Ethics; using Server.Guilds; using Server.Items; using Server.Mobiles; -using Server.Prompts; using Server.Targeting; namespace Server.Factions @@ -133,21 +132,12 @@ namespace Server.Factions public static void HandleAtrophy() { - foreach (Faction f in Factions) - if (!f.State.IsAtrophyReady) - return; + if (Factions.Any(f => !f.State.IsAtrophyReady)) + return; - List activePlayers = new List(); + List activePlayers = (from f in Factions from ps in f.Members where ps.KillPoints > 0 && ps.IsActive select ps).ToList(); - foreach (Faction f in Factions) - foreach (PlayerState ps in f.Members) - if (ps.KillPoints > 0 && ps.IsActive) - activePlayers.Add(ps); - - int distrib = 0; - - foreach (Faction f in Factions) - distrib += f.State.CheckAtrophy(); + int distrib = Factions.Sum(f => f.State.CheckAtrophy()); if (activePlayers.Count == 0) return; @@ -158,12 +148,7 @@ namespace Server.Factions public static void DistributePoints(int distrib) { - List activePlayers = new List(); - - foreach (Faction f in Factions) - foreach (PlayerState ps in f.Members) - if (ps.KillPoints > 0 && ps.IsActive) - activePlayers.Add(ps); + List activePlayers = (from f in Factions from ps in f.Members where ps.KillPoints > 0 && ps.IsActive select ps).ToList(); if (activePlayers.Count > 0) for (int i = 0; i < distrib; ++i) @@ -187,13 +172,9 @@ namespace Server.Factions return; if (recvState == null || recvState.Faction != giveState.Faction) - { from.SendLocalizedMessage(1042497); // Only faction mates can be honored this way. - } else if (giveState.KillPoints < 5) - { from.SendLocalizedMessage(1042499); // You must have at least five kill points to honor them. - } else { recvState.LastHonorTime = DateTime.UtcNow; @@ -205,9 +186,7 @@ namespace Server.Factions } } else - { from.SendLocalizedMessage(1042496); // You may only honor another player. - } } public virtual void AddMember(Mobile mob) @@ -649,11 +628,7 @@ namespace Server.Factions public static void FactionItemReset_OnCommand(CommandEventArgs e) { - List items = new List(); - - foreach (Item item in World.Items.Values) - if (item is IFactionItem && !(item is HoodedShroudOfShadows)) - items.Add(item); + List items = World.Items.Values.Where(item => item is IFactionItem && !(item is HoodedShroudOfShadows)).ToList(); int[] hues = new int[Factions.Count * 2]; @@ -673,16 +648,7 @@ namespace Server.Factions if (fci.FactionItemState != null || item.LootType != LootType.Blessed) continue; - bool isHued = false; - - for (int j = 0; j < hues.Length; ++j) - if (item.Hue == hues[j]) - { - isHued = true; - break; - } - - if (isHued) + if (hues.Any(t => item.Hue == t)) { fci.FactionItemState = null; ++count; @@ -841,7 +807,7 @@ namespace Server.Factions Silver += tithed; - silver = silver - tithed; + silver -= tithed; if (silver > 0) mob.AddToBackpack(new Silver(silver)); @@ -887,19 +853,12 @@ namespace Server.Factions Faction smallest = FindSmallestFaction(); - if (smallest == null) - return true; // sanity - - if ((Members.Count + influx) * 100 / StabilityFactor > smallest.Members.Count) - return false; - - return true; + return smallest == null || (Members.Count + influx) * 100 / StabilityFactor <= smallest.Members.Count; } public static void HandleDeath(Mobile victim, Mobile killer) { - if (killer == null) - killer = victim.FindMostRecentDamager(true); + killer ??= victim.FindMostRecentDamager(true); PlayerState killerState = PlayerState.Find(killer); Container killerPack = killer?.Backpack; @@ -941,7 +900,7 @@ namespace Server.Factions int silver = killerState.Faction.AwardSilver(killer, bc.FactionSilverWorth); if (silver > 0) - killer.SendLocalizedMessage(1042748, + killer?.SendLocalizedMessage(1042748, silver.ToString("N0")); // Thou hast earned ~1_AMOUNT~ silver for vanquishing the vile creature. } @@ -982,7 +941,7 @@ namespace Server.Factions { if (victimState.KillPoints <= -6) { - killer.SendLocalizedMessage(501693); // This victim is not worth enough to get kill points from. + killer?.SendLocalizedMessage(501693); // This victim is not worth enough to get kill points from. #region Ethics @@ -1024,13 +983,12 @@ namespace Server.Factions { victimState.IsActive = true; - if (1 > Utility.Random(3)) - killerState.IsActive = true; + killerState.IsActive |= 1 > Utility.Random(3); int silver = killerState.Faction.AwardSilver(killer, award * 40); if (silver > 0) - killer.SendLocalizedMessage(1042736, + killer?.SendLocalizedMessage(1042736, $"{silver:N0} silver\t{victim.Name}"); // You have earned ~1_SILVER_AMOUNT~ pieces for vanquishing ~2_PLAYER_NAME~! } @@ -1039,9 +997,9 @@ namespace Server.Factions int offset = award != 1 ? 0 : 2; // for pluralization - string args = $"{award}\t{victim.Name}\t{killer.Name}"; + string args = $"{award}\t{victim.Name}\t{killer?.Name ?? ""}"; - killer.SendLocalizedMessage(1042737 + offset, + killer?.SendLocalizedMessage(1042737 + offset, args); // Thou hast been honored with ~1_KILL_POINTS~ kill point(s) for vanquishing ~2_DEAD_PLAYER~! victim.SendLocalizedMessage(1042738 + offset, args); // Thou has lost ~1_KILL_POINTS~ kill point(s) to ~3_ATTACKER_NAME~ for being vanquished! @@ -1073,7 +1031,7 @@ namespace Server.Factions } else { - killer.SendLocalizedMessage( + killer?.SendLocalizedMessage( 1042231); // You have recently defeated this enemy and thus their death brings you no honor. } } @@ -1284,9 +1242,7 @@ namespace Server.Factions AddResponse("They have been kicked from their faction."); } else - { LogFailure("They are not in a faction."); - } break; } @@ -1300,9 +1256,7 @@ namespace Server.Factions AddResponse("The account has been banned from joining factions."); } else - { AddResponse("The account is already banned from joining factions."); - } for (int i = 0; i < acct.Length; ++i) { @@ -1322,9 +1276,7 @@ namespace Server.Factions } } else - { LogFailure("They have no assigned account."); - } break; } @@ -1333,9 +1285,7 @@ namespace Server.Factions if (mob.Account is Account acct) { if (acct.GetTag("FactionBanned") == null) - { AddResponse("The account is not already banned from joining factions."); - } else { acct.RemoveTag("FactionBanned"); @@ -1343,9 +1293,7 @@ namespace Server.Factions } } else - { LogFailure("They have no assigned account."); - } break; } diff --git a/Projects/Scripts/Engines/Factions/Core/PlayerState.cs b/Projects/Scripts/Engines/Factions/Core/PlayerState.cs index 121b8a7fe..2425ba99f 100644 --- a/Projects/Scripts/Engines/Factions/Core/PlayerState.cs +++ b/Projects/Scripts/Engines/Factions/Core/PlayerState.cs @@ -260,9 +260,7 @@ namespace Server.Factions public void OnGivenSilverTo(Mobile mob) { - if (SilverGiven == null) - SilverGiven = new List(); - + SilverGiven ??= new List(); SilverGiven.Add(new SilverGivenEntry(mob)); } diff --git a/Projects/Scripts/Engines/Factions/Items/Power Faction Items/PowerFactionItem.cs b/Projects/Scripts/Engines/Factions/Items/Power Faction Items/PowerFactionItem.cs index 77e3baa4b..1039a98ad 100644 --- a/Projects/Scripts/Engines/Factions/Items/Power Faction Items/PowerFactionItem.cs +++ b/Projects/Scripts/Engines/Factions/Items/Power Faction Items/PowerFactionItem.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Linq; using Server.Factions; using Server.Mobiles; using Server.Network; @@ -41,9 +42,7 @@ namespace Server if (chance > Utility.Random(100)) { - int weight = 0; - - foreach (WeightedItem item in _items) weight += item.Weight; + int weight = _items.Sum(item => item.Weight); weight = Utility.Random(weight); @@ -177,4 +176,4 @@ namespace Server public Item Construct() => Activator.CreateInstance(Type) as Item; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Factions/Items/Power Faction Items/UrnOfAscension.cs b/Projects/Scripts/Engines/Factions/Items/Power Faction Items/UrnOfAscension.cs index 08b088de7..b03886141 100644 --- a/Projects/Scripts/Engines/Factions/Items/Power Faction Items/UrnOfAscension.cs +++ b/Projects/Scripts/Engines/Factions/Items/Power Faction Items/UrnOfAscension.cs @@ -25,7 +25,9 @@ namespace Server bool used = false; - foreach (Mobile mob in from.GetMobilesInRange(8)) + IPooledEnumerable eable = from.GetMobilesInRange(8); + + foreach (Mobile mob in eable) if (mob.Player && !mob.Alive && from.InLOS(mob)) { if (Faction.Find(mob) != ourFaction) continue; @@ -41,6 +43,8 @@ namespace Server } } + eable.Free(); + if (used) { from.LocalOverheadMessage(MessageType.Regular, 2219, false, "The urn shatters as you invoke its power."); diff --git a/Projects/Scripts/Engines/Factions/Items/Traps/BaseFactionTrap.cs b/Projects/Scripts/Engines/Factions/Items/Traps/BaseFactionTrap.cs index 898f40b5f..f54142a40 100644 --- a/Projects/Scripts/Engines/Factions/Items/Traps/BaseFactionTrap.cs +++ b/Projects/Scripts/Engines/Factions/Items/Traps/BaseFactionTrap.cs @@ -113,10 +113,15 @@ namespace Server.Factions return 502956; // You cannot place a trap on that. if (Core.ML) - foreach (Item item in m.GetItemsInRange(p, 0)) + { + IPooledEnumerable eable = m.GetItemsInRange(p, 0); + foreach (Item item in eable) if (item is BaseFactionTrap trap && trap.Faction == Faction) return 1075263; // There is already a trap belonging to your faction at this location.; + eable.Free(); + } + switch (AllowedPlacing) { case AllowedPlacing.FactionStronghold: @@ -129,22 +134,12 @@ namespace Server.Factions return 1010355; // This trap can only be placed in your stronghold } case AllowedPlacing.AnyFactionTown: - { - Town town = Town.FromRegion(Region.Find(p, m)); - - if (town != null) - return 0; - - return 1010356; // This trap can only be placed in a faction town - } + return Town.FromRegion(Region.Find(p, m)) != null ? 0 : 1010356; case AllowedPlacing.ControlledFactionTown: { Town town = Town.FromRegion(Region.Find(p, m)); - if (town != null && town.Owner == Faction) - return 0; - - return 1010357; // This trap can only be placed in a town your faction controls + return town != null && town.Owner == Faction ? 0 : 1010357; } } @@ -155,17 +150,16 @@ namespace Server.Factions { base.OnMovement(m, oldLocation); - if (!CheckDecay() && CheckRange(m.Location, oldLocation, 6)) - if (Faction.Find(m) != null && - (m.Skills.DetectHidden.Value - 80.0) / 20.0 > Utility.RandomDouble()) - PrivateOverheadLocalizedMessage(m, 1010154, MessageHue, "", ""); // [Faction Trap] + if (!CheckDecay() && CheckRange(m.Location, oldLocation, 6) && + Faction.Find(m) != null && (m.Skills.DetectHidden.Value - 80.0) / 20.0 > Utility.RandomDouble()) + PrivateOverheadLocalizedMessage(m, 1010154, MessageHue, "", ""); // [Faction Trap] } public void PrivateOverheadLocalizedMessage(Mobile to, int number, int hue, string name, string args) { NetState ns = to?.NetState; - ns?.Send(new MessageLocalized(Serial, ItemID, MessageType.Regular, hue, 3, number, name, args)); + Packets.SendMessageLocalized(ns, Serial, ItemID, MessageType.Regular, hue, 3, number, name, args); } public virtual bool CheckDecay() @@ -252,10 +246,7 @@ namespace Server.Factions if (faction == null && mob is BaseFactionGuard guard) faction = guard.Faction; - if (faction == null) - return false; - - return faction != Faction; + return faction != null && faction != Faction; } } } diff --git a/Projects/Scripts/Engines/Factions/Items/Traps/FactionExplosionTrap.cs b/Projects/Scripts/Engines/Factions/Items/Traps/FactionExplosionTrap.cs index 920e5fa72..8954ac22d 100644 --- a/Projects/Scripts/Engines/Factions/Items/Traps/FactionExplosionTrap.cs +++ b/Projects/Scripts/Engines/Factions/Items/Traps/FactionExplosionTrap.cs @@ -23,7 +23,7 @@ namespace Server.Factions public override void DoVisibleEffect() { - Effects.SendLocationEffect(GetWorldLocation(), Map, 0x36BD, 15, 10); + Effects.SendLocationEffect(GetWorldLocation(), Map, 0x36BD, 15); } public override void DoAttackEffect(Mobile m) diff --git a/Projects/Scripts/Engines/Factions/Items/Traps/FactionSawTrap.cs b/Projects/Scripts/Engines/Factions/Items/Traps/FactionSawTrap.cs index 6432656ff..acc3780e9 100644 --- a/Projects/Scripts/Engines/Factions/Items/Traps/FactionSawTrap.cs +++ b/Projects/Scripts/Engines/Factions/Items/Traps/FactionSawTrap.cs @@ -8,6 +8,10 @@ namespace Server.Factions { } + public FactionSawTrap(Serial serial) : base(serial) + { + } + public override int LabelNumber => 1041047; // faction saw trap public override int AttackMessage => 1010544; // The blade cuts deep into your skin! @@ -19,7 +23,7 @@ namespace Server.Factions public override void DoVisibleEffect() { - Effects.SendLocationEffect(Location, Map, 0x11AD, 25, 10); + Effects.SendLocationEffect(Location, Map, 0x11AD, 25); } public override void DoAttackEffect(Mobile m) diff --git a/Projects/Scripts/Engines/Factions/Mobiles/Guards/GuardAI.cs b/Projects/Scripts/Engines/Factions/Mobiles/Guards/GuardAI.cs index e31baae4a..2e4d01f6f 100644 --- a/Projects/Scripts/Engines/Factions/Mobiles/Guards/GuardAI.cs +++ b/Projects/Scripts/Engines/Factions/Mobiles/Guards/GuardAI.cs @@ -313,7 +313,9 @@ namespace Server.Factions actPrio = inactPrio = m_Mobile.GetDistanceToSqrt(comb); } - foreach (Mobile m in m_Mobile.GetMobilesInRange(12)) + IPooledEnumerable eable = m_Mobile.GetMobilesInRange(12); + + foreach (Mobile m in eable) if (m != m_Mobile && CanDispel(m)) { double prio = m_Mobile.GetDistanceToSqrt(m); @@ -331,6 +333,8 @@ namespace Server.Factions } } + eable.Free(); + return active ?? inactive; } diff --git a/Projects/Scripts/Engines/Harvest/Fishing.cs b/Projects/Scripts/Engines/Harvest/Fishing.cs index 79064a01d..33bdbd705 100644 --- a/Projects/Scripts/Engines/Harvest/Fishing.cs +++ b/Projects/Scripts/Engines/Harvest/Fishing.cs @@ -23,7 +23,7 @@ namespace Server.Engines.Harvest new MutateEntry(0.0, 125.0, -2375.0, false, typeof(PrizedFish), typeof(WondrousFish), typeof(TrulyRareFish), typeof(PeculiarFish)), new MutateEntry(0.0, 105.0, -420.0, false, typeof(Boots), typeof(Shoes), typeof(Sandals), typeof(ThighBoots)), - new MutateEntry(0.0, 200.0, -200.0, false, new Type[1] { null }) + new MutateEntry(0.0, 200.0, -200.0, false, new Type[] { null }) }; private static int[] m_WaterTiles = @@ -87,7 +87,7 @@ namespace Server.Engines.Harvest Definitions.Add(fish); } - public static Fishing System => m_System ?? (m_System = new Fishing()); + public static Fishing System => m_System ??= new Fishing(); public HarvestDefinition Definition{ get; } diff --git a/Projects/Scripts/Engines/Harvest/Lumberjacking.cs b/Projects/Scripts/Engines/Harvest/Lumberjacking.cs index c66eead6c..e5b5b8ffa 100644 --- a/Projects/Scripts/Engines/Harvest/Lumberjacking.cs +++ b/Projects/Scripts/Engines/Harvest/Lumberjacking.cs @@ -126,7 +126,7 @@ namespace Server.Engines.Harvest Definitions.Add(lumber); } - public static Lumberjacking System => m_System ?? (m_System = new Lumberjacking()); + public static Lumberjacking System => m_System ??= new Lumberjacking(); public HarvestDefinition Definition{ get; } diff --git a/Projects/Scripts/Engines/Harvest/Mining.cs b/Projects/Scripts/Engines/Harvest/Mining.cs index 043ebbc52..a4091cceb 100644 --- a/Projects/Scripts/Engines/Harvest/Mining.cs +++ b/Projects/Scripts/Engines/Harvest/Mining.cs @@ -153,7 +153,7 @@ namespace Server.Engines.Harvest #endregion } - public static Mining System => m_System ?? (m_System = new Mining()); + public static Mining System => m_System ??= new Mining(); public HarvestDefinition OreAndStone{ get; } diff --git a/Projects/Scripts/Engines/Help/HelpGump.cs b/Projects/Scripts/Engines/Help/HelpGump.cs index f99b5c308..305dc5c35 100644 --- a/Projects/Scripts/Engines/Help/HelpGump.cs +++ b/Projects/Scripts/Engines/Help/HelpGump.cs @@ -1,7 +1,9 @@ using System; +using System.Linq; using Server.Engines.ConPVP; using Server.Factions; using Server.Gumps; +using Server.Menus; using Server.Menus.Questions; using Server.Mobiles; using Server.Multis; @@ -27,9 +29,7 @@ namespace Server.Engines.Help public override void OnResponse(NetState state, int index) { if (index == 0) - { m_From.SendLocalizedMessage(1005306, "", 0x35); // Help request unchanged. - } else if (index == 1) { PageEntry entry = PageQueue.GetEntry(m_From); @@ -141,49 +141,49 @@ namespace Server.Engines.Help AddButton(80, 90, 5540, 5541, 7); AddHtmlLocalized(110, 90, 450, 145, 1062572, true, - true); /* Another player is harassing me (or Exploiting). - * VERBAL HARASSMENT - * Use this option when another player is verbally harassing your character. - * Verbal harassment behaviors include but are not limited to, using bad language, threats etc.. - * Before you submit a complaint be sure you understand what constitutes harassment - * � what is verbal harassment? - - * and that you have followed these steps: - * 1. You have asked the player to stop and they have continued. - * 2. You have tried to remove yourself from the situation. - * 3. You have done nothing to instigate or further encourage the harassment. - * 4. You have added the player to your ignore list. - * - How do I ignore a player? - * 5. You have read and understand Origin�s definition of harassment. - * 6. Your account information is up to date. (Including a current email address) - * *If these steps have not been taken, GMs may be unable to take action against the offending player. - * **A chat log will be review by a GM to assess the validity of this complaint. - * Abuse of this system is a violation of the Rules of Conduct. - * EXPLOITING - * Use this option to report someone who may be exploiting or cheating. - * � What constitutes an exploit? - */ + true); /* Another player is harassing me (or Exploiting). + * VERBAL HARASSMENT + * Use this option when another player is verbally harassing your character. + * Verbal harassment behaviors include but are not limited to, using bad language, threats etc.. + * Before you submit a complaint be sure you understand what constitutes harassment + * � what is verbal harassment? - + * and that you have followed these steps: + * 1. You have asked the player to stop and they have continued. + * 2. You have tried to remove yourself from the situation. + * 3. You have done nothing to instigate or further encourage the harassment. + * 4. You have added the player to your ignore list. + * - How do I ignore a player? + * 5. You have read and understand Origin�s definition of harassment. + * 6. Your account information is up to date. (Including a current email address) + * *If these steps have not been taken, GMs may be unable to take action against the offending player. + * **A chat log will be review by a GM to assess the validity of this complaint. + * Abuse of this system is a violation of the Rules of Conduct. + * EXPLOITING + * Use this option to report someone who may be exploiting or cheating. + * � What constitutes an exploit? + */ AddButton(80, 240, 5540, 5541, 8); AddHtmlLocalized(110, 240, 450, 145, 1062573, true, - true); /* Another player is harassing me using game mechanics. - * - * PHYSICAL HARASSMENT - * Use this option when another player is harassing your character using game mechanics. - * Physical harassment includes but is not limited to luring, Kill Stealing, and any act that causes a players death in Trammel. - * Before you submit a complaint be sure you understand what constitutes harassment - * � what is physical harassment? - * and that you have followed these steps: - * 1. You have asked the player to stop and they have continued. - * 2. You have tried to remove yourself from the situation. - * 3. You have done nothing to instigate or further encourage the harassment. - * 4. You have added the player to your ignore list. - * - how do I ignore a player? - * 5. You have read and understand Origin�s definition of harassment. - * 6. Your account information is up to date. (Including a current email address) - * *If these steps have not been taken, GMs may be unable to take action against the offending player. - * **This issue will be reviewed by a GM to assess the validity of this complaint. - * Abuse of this system is a violation of the Rules of Conduct. - */ + true); /* Another player is harassing me using game mechanics. + * + * PHYSICAL HARASSMENT + * Use this option when another player is harassing your character using game mechanics. + * Physical harassment includes but is not limited to luring, Kill Stealing, and any act that causes a players death in Trammel. + * Before you submit a complaint be sure you understand what constitutes harassment + * � what is physical harassment? + * and that you have followed these steps: + * 1. You have asked the player to stop and they have continued. + * 2. You have tried to remove yourself from the situation. + * 3. You have done nothing to instigate or further encourage the harassment. + * 4. You have added the player to your ignore list. + * - how do I ignore a player? + * 5. You have read and understand Origin�s definition of harassment. + * 6. Your account information is up to date. (Including a current email address) + * *If these steps have not been taken, GMs may be unable to take action against the offending player. + * **This issue will be reviewed by a GM to assess the validity of this complaint. + * Abuse of this system is a violation of the Rules of Conduct. + */ AddButton(150, 390, 5540, 5541, 0, GumpButtonType.Page, 1); AddHtmlLocalized(180, 390, 335, 40, 1001015); // NO - I meant to ask for help with another matter. @@ -196,9 +196,8 @@ namespace Server.Engines.Help private static void EventSink_HelpRequest(HelpRequestEventArgs e) { - foreach (Gump g in e.Mobile.NetState.Gumps) - if (g is HelpGump) - return; + if (e.Mobile.NetState.Gumps.OfType().Any()) + return; if (!PageQueue.CheckAllowedToPage(e.Mobile)) return; @@ -224,9 +223,9 @@ namespace Server.Engines.Help return false; } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { - Mobile from = state.Mobile; + Mobile from = sender.Mobile; PageType type = (PageType)(-1); diff --git a/Projects/Scripts/Engines/Help/PagePrompt.cs b/Projects/Scripts/Engines/Help/PagePrompt.cs index 4ab9e3a79..612819b36 100644 --- a/Projects/Scripts/Engines/Help/PagePrompt.cs +++ b/Projects/Scripts/Engines/Help/PagePrompt.cs @@ -1,5 +1,3 @@ -using Server.Prompts; - namespace Server.Engines.Help { public class PagePrompt : Prompt @@ -16,11 +14,11 @@ namespace Server.Engines.Help public override void OnResponse(Mobile from, string text) { from.SendLocalizedMessage(501234, "", - 0x35); /* The next available Counselor/Game Master will respond as soon as possible. - * Please check your Journal for messages every few minutes. - */ + 0x35); /* The next available Counselor/Game Master will respond as soon as possible. + * Please check your Journal for messages every few minutes. + */ PageQueue.Enqueue(new PageEntry(from, text, m_Type)); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Help/PagePromptGump.cs b/Projects/Scripts/Engines/Help/PagePromptGump.cs index 982991a35..7987e690a 100644 --- a/Projects/Scripts/Engines/Help/PagePromptGump.cs +++ b/Projects/Scripts/Engines/Help/PagePromptGump.cs @@ -48,9 +48,9 @@ namespace Server.Engines.Help else { m_From.SendLocalizedMessage(501234, "", - 0x35); /* The next available Counselor/Game Master will respond as soon as possible. - * Please check your Journal for messages every few minutes. - */ + 0x35); /* The next available Counselor/Game Master will respond as soon as possible. + * Please check your Journal for messages every few minutes. + */ PageQueue.Enqueue(new PageEntry(m_From, text, m_Type)); } diff --git a/Projects/Scripts/Engines/Help/PageQueue.cs b/Projects/Scripts/Engines/Help/PageQueue.cs index f719ddea8..2062702a7 100644 --- a/Projects/Scripts/Engines/Help/PageQueue.cs +++ b/Projects/Scripts/Engines/Help/PageQueue.cs @@ -82,8 +82,6 @@ namespace Server.Engines.Help private class InternalTimer : Timer { - private static TimeSpan StatusDelay = TimeSpan.FromMinutes(2.0); - private PageEntry m_Entry; public InternalTimer(PageEntry entry) : base(TimeSpan.FromSeconds(1.0), StatusDelay) => m_Entry = entry; diff --git a/Projects/Scripts/Engines/Help/PageQueueGump.cs b/Projects/Scripts/Engines/Help/PageQueueGump.cs index a87f3d40e..124697ca9 100644 --- a/Projects/Scripts/Engines/Help/PageQueueGump.cs +++ b/Projects/Scripts/Engines/Help/PageQueueGump.cs @@ -32,7 +32,7 @@ namespace Server.Engines.Help AddHtmlLocalized(34, 28, 65, 24, 3001002, 0xFFFFFF); // Message } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { m_Mobile.SendGump(new PageResponseGump(m_Mobile, m_Name, m_Text)); @@ -100,20 +100,20 @@ namespace Server.Engines.Help } } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID >= 1 && info.ButtonID <= m_List.Length) { if (PageQueue.List.IndexOf(m_List[info.ButtonID - 1]) >= 0) { - PageEntryGump g = new PageEntryGump(state.Mobile, m_List[info.ButtonID - 1]); + PageEntryGump g = new PageEntryGump(sender.Mobile, m_List[info.ButtonID - 1]); - g.SendTo(state); + g.SendTo(sender); } else { - state.Mobile.SendGump(new PageQueueGump()); - state.Mobile.SendMessage("That page has been removed."); + sender.Mobile.SendGump(new PageQueueGump()); + sender.Mobile.SendMessage("That page has been removed."); } } } @@ -553,12 +553,12 @@ namespace Server.Engines.Help g.SendTo(state); } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID != 0 && PageQueue.List.IndexOf(m_Entry) < 0) { - state.Mobile.SendGump(new PageQueueGump()); - state.Mobile.SendMessage("That page has been removed."); + sender.Mobile.SendGump(new PageQueueGump()); + sender.Mobile.SendMessage("That page has been removed."); return; } @@ -566,18 +566,18 @@ namespace Server.Engines.Help { case 0: // close { - if (m_Entry.Handler != state.Mobile) + if (m_Entry.Handler != sender.Mobile) { PageQueueGump g = new PageQueueGump(); - g.SendTo(state); + g.SendTo(sender); } break; } case 1: // go to sender { - Mobile m = state.Mobile; + Mobile m = sender.Mobile; if (m_Entry.Sender.Deleted) { @@ -594,14 +594,14 @@ namespace Server.Engines.Help m.SendMessage("You have been teleported to that page's sender."); - Resend(state); + Resend(sender); } break; } case 2: // go to handler { - Mobile m = state.Mobile; + Mobile m = sender.Mobile; Mobile h = m_Entry.Handler; if (h != null) @@ -620,20 +620,20 @@ namespace Server.Engines.Help m.MoveToWorld(h.Location, h.Map); m.SendMessage("You have been teleported to that page's handler."); - Resend(state); + Resend(sender); } } else { m.SendMessage("Nobody is handling that page."); - Resend(state); + Resend(sender); } break; } case 3: // go to page location { - Mobile m = state.Mobile; + Mobile m = sender.Mobile; if (m_Entry.PageMap == null || m_Entry.PageMap == Map.Internal) { @@ -644,9 +644,9 @@ namespace Server.Engines.Help // m_Entry.AddResponse(state.Mobile, "[Go PageLoc]"); m.MoveToWorld(m_Entry.PageLocation, m_Entry.PageMap); - state.Mobile.SendMessage("You have been teleported to the original page location."); + sender.Mobile.SendMessage("You have been teleported to the original page location."); - Resend(state); + Resend(sender); } break; @@ -656,16 +656,14 @@ namespace Server.Engines.Help if (m_Entry.Handler == null) { // m_Entry.AddResponse(state.Mobile, "[Handling]"); - m_Entry.Handler = state.Mobile; + m_Entry.Handler = sender.Mobile; - state.Mobile.SendMessage("You are now handling the page."); + sender.Mobile.SendMessage("You are now handling the page."); } else - { - state.Mobile.SendMessage("Someone is already handling that page."); - } + sender.Mobile.SendMessage("Someone is already handling that page."); - Resend(state); + Resend(sender); break; } @@ -676,59 +674,57 @@ namespace Server.Engines.Help // m_Entry.AddResponse(state.Mobile, "[Deleting]"); PageQueue.Remove(m_Entry); - state.Mobile.SendMessage("You delete the page."); + sender.Mobile.SendMessage("You delete the page."); PageQueueGump g = new PageQueueGump(); - g.SendTo(state); + g.SendTo(sender); } else { - state.Mobile.SendMessage("Someone is handling that page, it can not be deleted."); + sender.Mobile.SendMessage("Someone is handling that page, it can not be deleted."); - Resend(state); + Resend(sender); } break; } case 6: // abandon page { - if (m_Entry.Handler == state.Mobile) + if (m_Entry.Handler == sender.Mobile) { // m_Entry.AddResponse(state.Mobile, "[Abandoning]"); - state.Mobile.SendMessage("You abandon the page."); + sender.Mobile.SendMessage("You abandon the page."); m_Entry.Handler = null; } else - { - state.Mobile.SendMessage("You are not handling that page."); - } + sender.Mobile.SendMessage("You are not handling that page."); - Resend(state); + Resend(sender); break; } case 7: // page handled { - if (m_Entry.Handler == state.Mobile) + if (m_Entry.Handler == sender.Mobile) { // m_Entry.AddResponse(state.Mobile, "[Handled]"); PageQueue.Remove(m_Entry); m_Entry.Handler = null; - state.Mobile.SendMessage("You mark the page as handled, and remove it from the queue."); + sender.Mobile.SendMessage("You mark the page as handled, and remove it from the queue."); PageQueueGump g = new PageQueueGump(); - g.SendTo(state); + g.SendTo(sender); } else { - state.Mobile.SendMessage("You are not handling that page."); + sender.Mobile.SendMessage("You are not handling that page."); - Resend(state); + Resend(sender); } break; @@ -743,20 +739,20 @@ namespace Server.Engines.Help //m_Entry.Sender.SendMessage( 0x482, "{0} tells you:", state.Mobile.Name ); //m_Entry.Sender.SendMessage( 0x482, text.Text ); - Resend(state); + Resend(sender); break; } case 9: // predef overview { - Resend(state); - state.Mobile.SendGump(new PredefGump(state.Mobile, null)); + Resend(sender); + sender.Mobile.SendGump(new PredefGump(sender.Mobile, null)); break; } case 10: // View Speech Log { - Resend(state); + Resend(sender); if (m_Entry.SpeechLog != null) state.Mobile.SendGump(new SpeechLogGump(m_Entry.Sender, m_Entry.SpeechLog)); @@ -772,7 +768,7 @@ namespace Server.Engines.Help m_Entry.Sender.SendGump(new MessageSentGump(m_Entry.Sender, state.Mobile.Name, preresp[index].Message)); - Resend(state); + Resend(sender); break; } diff --git a/Projects/Scripts/Engines/Help/SpeechLogGump.cs b/Projects/Scripts/Engines/Help/SpeechLogGump.cs index 7996e18f7..1afb7aea3 100644 --- a/Projects/Scripts/Engines/Help/SpeechLogGump.cs +++ b/Projects/Scripts/Engines/Help/SpeechLogGump.cs @@ -46,9 +46,7 @@ namespace Server.Engines.Help string sLog; if (page < 0 || page > lastPage) - { sLog = ""; - } else { int max = log.Count - (lastPage - page) * MaxEntriesPerPage; diff --git a/Projects/Scripts/Engines/Help/StuckMenu.cs b/Projects/Scripts/Engines/Help/StuckMenu.cs index 9c6519417..313b82c73 100644 --- a/Projects/Scripts/Engines/Help/StuckMenu.cs +++ b/Projects/Scripts/Engines/Help/StuckMenu.cs @@ -14,9 +14,9 @@ namespace Server.Menus.Questions Locations = locations; } - public int Name{ get; } + public int Name { get; } - public Point3D[] Locations{ get; } + public Point3D[] Locations { get; } } public class StuckMenu : Gump @@ -162,7 +162,7 @@ namespace Server.Menus.Questions m_Mobile.Frozen = false; } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { StopClose(); diff --git a/Projects/Scripts/Engines/Khaldun/PuzzleChest.cs b/Projects/Scripts/Engines/Khaldun/PuzzleChest.cs index 271a06410..6263a9b4d 100644 --- a/Projects/Scripts/Engines/Khaldun/PuzzleChest.cs +++ b/Projects/Scripts/Engines/Khaldun/PuzzleChest.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Gumps; using Server.Network; @@ -47,22 +48,9 @@ namespace Server.Items int version = reader.ReadEncodedInt(); int length = reader.ReadEncodedInt(); - for (int i = 0;; i++) - if (i < length) - { - PuzzleChestCylinder cylinder = (PuzzleChestCylinder)reader.ReadInt(); - if (i < Cylinders.Length) - Cylinders[i] = cylinder; - } - else if (i < Cylinders.Length) - { - Cylinders[i] = RandomCylinder(); - } - else - { - break; - } + for (int i = 0; i < Cylinders.Length; i++) + Cylinders[i] = i < length ? (PuzzleChestCylinder)reader.ReadInt() : RandomCylinder(); } public PuzzleChestCylinder[] Cylinders{ get; } = new PuzzleChestCylinder[Length]; @@ -296,7 +284,7 @@ namespace Server.Items { case 0: { - Effects.SendLocationEffect(to, to.Map, 0x113A, 20, 10); + Effects.SendLocationEffect(to, to.Map, 0x113A, 20); to.PlaySound(0x231); to.LocalOverheadMessage(MessageType.Regular, 0x44, 1010523); // A toxic vapor envelops thee. @@ -326,7 +314,7 @@ namespace Server.Items } default: { - to.BoltEffect(0); + to.BoltEffect(); to.LocalOverheadMessage(MessageType.Regular, 0xDA, 1010526); // Lightning arcs through thy body. AOS.Damage(to, to, Utility.RandomMinMax(10, 40), 0, 0, 0, 0, 100); @@ -409,12 +397,8 @@ namespace Server.Items for (int i = 0; i < 2; i++) { - Item item; - - if (Core.AOS) - item = Loot.RandomArmorOrShieldOrWeaponOrJewelry(); - else - item = Loot.RandomArmorOrShieldOrWeapon(); + Item item = Core.AOS ? + Loot.RandomArmorOrShieldOrWeaponOrJewelry() : Loot.RandomArmorOrShieldOrWeapon(); if (item is BaseWeapon weapon) { @@ -475,13 +459,7 @@ namespace Server.Items public void CleanupGuesses() { - List toDelete = new List(); - - foreach (KeyValuePair kvp in m_Guesses) - if (DateTime.UtcNow - kvp.Value.When > CleanupTime) - toDelete.Add(kvp.Key); - - foreach (Mobile m in toDelete) + foreach (Mobile m in from kvp in m_Guesses where DateTime.UtcNow - kvp.Value.When > CleanupTime select kvp.Key) m_Guesses.Remove(m); } @@ -499,10 +477,10 @@ namespace Server.Items for (int i = 0; i < Hints.Length; i++) writer.Write((int)Hints[i]); writer.WriteEncodedInt(m_Guesses.Count); - foreach (KeyValuePair kvp in m_Guesses) + foreach (var (key, value) in m_Guesses) { - writer.Write(kvp.Key); - kvp.Value.Serialize(writer); + writer.Write(key); + value.Serialize(writer); } } @@ -680,9 +658,7 @@ namespace Server.Items } if (info.ButtonID == 1) - { m_Chest.SubmitSolution(m_From, m_Solution); - } else { if (info.Switches.Length == 0) diff --git a/Projects/Scripts/Engines/MLQuests/Gumps/RaceChangeGump.cs b/Projects/Scripts/Engines/MLQuests/Gumps/RaceChangeGump.cs index 4292a91dd..9ae4c9238 100644 --- a/Projects/Scripts/Engines/MLQuests/Gumps/RaceChangeGump.cs +++ b/Projects/Scripts/Engines/MLQuests/Gumps/RaceChangeGump.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Linq; +using Server.Buffers; using Server.Gumps; using Server.Items; using Server.Mobiles; @@ -87,7 +89,7 @@ namespace Server.Engines.MLQuests.Gumps CloseCurrent(ns); m_Pending[ns] = new RaceChangeState(owner, ns, targetRace); - ns.Send(new RaceChanger(from.Female, targetRace)); + SendRaceChanger(ns, from.Female, targetRace); } private static void CloseCurrent(NetState ns) @@ -98,7 +100,7 @@ namespace Server.Engines.MLQuests.Gumps m_Pending.Remove(ns); } - ns.Send(CloseRaceChanger.Instance); + SendCloseRaceChanger(ns); } private static void Timeout(NetState ns) @@ -106,30 +108,21 @@ namespace Server.Engines.MLQuests.Gumps if (IsPending(ns)) { m_Pending.Remove(ns); - ns.Send(CloseRaceChanger.Instance); + SendCloseRaceChanger(ns); } } public static bool IsWearingEquipment(Mobile from) { - foreach (Item item in from.Items) - switch (item.Layer) + return from.Items.Select(item => item.Layer switch { - case Layer.Hair: - case Layer.FacialHair: - case Layer.Backpack: - case Layer.Mount: - case Layer.Bank: - { - continue; // ignore - } - default: - { - return true; - } - } - - return false; + Layer.Hair => false, + Layer.FacialHair => false, + Layer.Backpack => false, + Layer.Mount => false, + Layer.Bank => false, + _ => true + }).FirstOrDefault(); } private static bool CanChange(PlayerMobile from, Race targetRace) @@ -238,38 +231,34 @@ namespace Server.Engines.MLQuests.Gumps m_Timeout = Timer.DelayCall(m_TimeoutDelay, Timeout, ns); } } - } - public sealed class RaceChanger : Packet - { - public RaceChanger(bool female, Race targetRace) - : base(0xBF) + public static void SendRaceChanger(NetState ns, bool female, Race targetRace) { - EnsureCapacity(7); + if (ns == null) + return; - m_Stream.Write((short)0x2A); - m_Stream.Write((byte)(female ? 1 : 0)); - m_Stream.Write((byte)(targetRace.RaceID + 1)); + SpanWriter writer = new SpanWriter(stackalloc byte[7]); + writer.Write((byte)0xBF); // Packet ID + writer.Write((ushort)0x07); // Dynamic Length + + writer.Write((short)0x2A); + writer.Write(female); + writer.Write((byte)(targetRace.RaceID + 1)); + + ns.Send(writer.Span); + } + + private static void SendCloseRaceChanger(NetState ns) + { + ns?.Send(stackalloc byte[] + { + 0xBF, // Packet ID + 0x07, // Dynamic Length + 0x00, + 0xFF + }); } } - - public sealed class CloseRaceChanger : Packet - { - public static readonly Packet Instance = SetStatic(new CloseRaceChanger()); - - private CloseRaceChanger() - : base(0xBF) - { - EnsureCapacity(7); - - m_Stream.Write((short)0x2A); - m_Stream.Write((byte)0); - m_Stream.Write((byte)0xFF); - } - } - - #region For testing - public class RaceChangeDeed : Item, IRaceChanger { [Constructible] @@ -330,6 +319,4 @@ namespace Server.Engines.MLQuests.Gumps int version = reader.ReadInt(); } } - - #endregion } diff --git a/Projects/Scripts/Engines/MLQuests/MLQuest.cs b/Projects/Scripts/Engines/MLQuests/MLQuest.cs index 4231451b5..599f6f86a 100644 --- a/Projects/Scripts/Engines/MLQuests/MLQuest.cs +++ b/Projects/Scripts/Engines/MLQuests/MLQuest.cs @@ -86,14 +86,7 @@ namespace Server.Engines.MLQuests public virtual int Version => 0; - public bool HasObjective() where T : BaseObjective - { - foreach (BaseObjective obj in Objectives) - if (obj is T) - return true; - - return false; - } + public bool HasObjective() where T : BaseObjective => Objectives.OfType().Any(); public virtual void Generate() { @@ -151,11 +144,7 @@ namespace Server.Engines.MLQuests } } - foreach (BaseObjective obj in Objectives) - if (!obj.CanOffer(quester, pm, message)) - return false; - - return true; + return Objectives.All(obj => obj.CanOffer(quester, pm, message)); } public virtual void SendOffer(IQuestGiver quester, PlayerMobile pm) diff --git a/Projects/Scripts/Engines/MLQuests/MLQuestContext.cs b/Projects/Scripts/Engines/MLQuests/MLQuestContext.cs index 052f04544..17b886604 100644 --- a/Projects/Scripts/Engines/MLQuests/MLQuestContext.cs +++ b/Projects/Scripts/Engines/MLQuests/MLQuestContext.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Mobiles; namespace Server.Engines.MLQuests @@ -113,14 +114,7 @@ namespace Server.Engines.MLQuests return quest != null && HasDoneQuest(quest); } - public bool HasDoneQuest(MLQuest quest) - { - foreach (MLDoneQuestInfo info in m_DoneQuests) - if (info.m_Quest == quest) - return true; - - return false; - } + public bool HasDoneQuest(MLQuest quest) => m_DoneQuests.Any(info => info.m_Quest == quest); public bool HasDoneQuest(MLQuest quest, out DateTime nextAvailable) { @@ -180,20 +174,10 @@ namespace Server.Engines.MLQuests { MLQuest quest = MLQuestSystem.FindQuest(questType); - if (quest == null) - return null; - - return FindInstance(quest); + return quest == null ? null : FindInstance(quest); } - public MLQuestInstance FindInstance(MLQuest quest) - { - foreach (MLQuestInstance instance in QuestInstances) - if (instance.Quest == quest) - return instance; - - return null; - } + public MLQuestInstance FindInstance(MLQuest quest) => QuestInstances.FirstOrDefault(instance => instance.Quest == quest); public bool IsDoingQuest(Type questType) { diff --git a/Projects/Scripts/Engines/MLQuests/MLQuestEntry.cs b/Projects/Scripts/Engines/MLQuests/MLQuestEntry.cs index 84e28db5a..095802ca8 100644 --- a/Projects/Scripts/Engines/MLQuests/MLQuestEntry.cs +++ b/Projects/Scripts/Engines/MLQuests/MLQuestEntry.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Engines.MLQuests.Gumps; using Server.Engines.MLQuests.Objectives; using Server.Engines.MLQuests.Rewards; @@ -36,16 +37,7 @@ namespace Server.Engines.MLQuests Objectives = new BaseObjectiveInstance[quest.Objectives.Count]; - BaseObjectiveInstance obj; - bool timed = false; - - for (int i = 0; i < quest.Objectives.Count; ++i) - { - Objectives[i] = obj = quest.Objectives[i].CreateInstance(this); - - if (obj.IsTimed) - timed = true; - } + bool timed = quest.Objectives.Aggregate(false, (current, t) => current | t.CreateInstance(this).IsTimed); Register(); @@ -113,14 +105,8 @@ namespace Server.Engines.MLQuests Removed = true; } - public bool AllowsQuestItem(Item item, Type type) - { - foreach (BaseObjectiveInstance objective in Objectives) - if (!objective.Expired && objective.AllowsQuestItem(item, type)) - return true; - - return false; - } + public bool AllowsQuestItem(Item item, Type type) => + Objectives.Any(objective => !objective.Expired && objective.AllowsQuestItem(item, type)); public bool IsCompleted() { @@ -252,13 +238,11 @@ namespace Server.Engines.MLQuests if (Quest.ObjectiveType == ObjectiveType.All) { // TODO: 1115877 - You no longer have the required items to complete this quest. - foreach (BaseObjectiveInstance objective in Objectives) - if (!objective.IsCompleted()) - return; + if (Objectives.Any(objective => !objective.IsCompleted())) + return; - foreach (BaseObjectiveInstance objective in Objectives) - if (!objective.OnBeforeClaimReward()) - return; + if (Objectives.Any(objective => !objective.OnBeforeClaimReward())) + return; foreach (BaseObjectiveInstance objective in Objectives) objective.OnClaimReward(); @@ -314,14 +298,7 @@ namespace Server.Engines.MLQuests { // On OSI a more naive method of checking is used. // For containers, only the actual container item counts. - bool canFit = true; - - foreach (Item rewardItem in rewards) - if (!Player.AddToBackpack(rewardItem)) - { - canFit = false; - break; - } + bool canFit = rewards.All(rewardItem => Player.AddToBackpack(rewardItem)); if (!canFit) { diff --git a/Projects/Scripts/Engines/MLQuests/MLQuestPersistence.cs b/Projects/Scripts/Engines/MLQuests/MLQuestPersistence.cs index 87f3cfa5c..66c861788 100644 --- a/Projects/Scripts/Engines/MLQuests/MLQuestPersistence.cs +++ b/Projects/Scripts/Engines/MLQuests/MLQuestPersistence.cs @@ -14,8 +14,7 @@ namespace Server.Engines.MLQuests public static void EnsureExistence() { - if (m_Instance == null) - m_Instance = new MLQuestPersistence(); + m_Instance ??= new MLQuestPersistence(); } public override void Serialize(GenericWriter writer) @@ -55,4 +54,4 @@ namespace Server.Engines.MLQuests MLQuest.Deserialize(reader, version); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/MLQuests/MLQuestSystem.cs b/Projects/Scripts/Engines/MLQuests/MLQuestSystem.cs index 32ec0c488..c65dd5640 100644 --- a/Projects/Scripts/Engines/MLQuests/MLQuestSystem.cs +++ b/Projects/Scripts/Engines/MLQuests/MLQuestSystem.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using Server.Commands; using Server.Commands.Generic; using Server.Engines.MLQuests.Gumps; @@ -213,7 +214,7 @@ namespace Server.Engines.MLQuests return; } - bool enable = e.Length == 1 ? e.GetBoolean(0) : true; + bool enable = e.Length != 1 || e.GetBoolean(0); foreach (MLQuest quest in Quests.Values) quest.SaveEnabled = enable; @@ -329,17 +330,8 @@ namespace Server.Engines.MLQuests } } - public static bool CanMarkQuestItem(PlayerMobile pm, Item item, Type type) - { - MLQuestContext context = GetContext(pm); - - if (context != null) - foreach (MLQuestInstance quest in context.QuestInstances) - if (!quest.ClaimReward && quest.AllowsQuestItem(item, type)) - return true; - - return false; - } + public static bool CanMarkQuestItem(PlayerMobile pm, Item item, Type type) => + GetContext(pm)?.QuestInstances.Any(quest => !quest.ClaimReward && quest.AllowsQuestItem(item, type)) == true; private static void OnMarkQuestItem(PlayerMobile pm, Item item, Type type) { @@ -563,8 +555,7 @@ namespace Server.Engines.MLQuests * Save first quest that reaches the CanOffer call. * If no quests are valid at all, return this quest for displaying the CanOffer error message. */ - if (fallback == null) - fallback = quest; + fallback ??= quest; if (quest.CanOffer(quester, pm, context, false)) m_EligiblePool.Add(quest); @@ -643,7 +634,7 @@ namespace Server.Engines.MLQuests if (questType == null) return null; // no longer a type - return FindQuest(questType); + return questType == null ? null : FindQuest(questType); } public static MLQuest FindQuest(Type questType) diff --git a/Projects/Scripts/Engines/MLQuests/Mobiles/BoonCollector.cs b/Projects/Scripts/Engines/MLQuests/Mobiles/BoonCollector.cs index 0ba0dff6d..303bed91c 100644 --- a/Projects/Scripts/Engines/MLQuests/Mobiles/BoonCollector.cs +++ b/Projects/Scripts/Engines/MLQuests/Mobiles/BoonCollector.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Engines.MLQuests.Definitions; using Server.Engines.MLQuests.Gumps; using Server.Items; @@ -135,20 +136,7 @@ namespace Server.Engines.MLQuests.Mobiles { MLQuestContext context = MLQuestSystem.GetContext(pm); - if (context == null) - return 0; - - int result = 0; - - foreach (Type type in Needed) - { - MLQuest quest = MLQuestSystem.FindQuest(type); - - if (quest == null || context.HasDoneQuest(quest)) - ++result; - } - - return result; + return context == null ? 0 : Needed.Select(MLQuestSystem.FindQuest).Count(quest => quest == null || context.HasDoneQuest(quest)); } public virtual void OnComplete(PlayerMobile pm) diff --git a/Projects/Scripts/Engines/MLQuests/Mobiles/SirHelper.cs b/Projects/Scripts/Engines/MLQuests/Mobiles/SirHelper.cs index ac70f3b68..b92f56b41 100644 --- a/Projects/Scripts/Engines/MLQuests/Mobiles/SirHelper.cs +++ b/Projects/Scripts/Engines/MLQuests/Mobiles/SirHelper.cs @@ -42,9 +42,7 @@ namespace Server.Engines.MLQuests.Mobiles public override bool GetGender() => false; - public override void CheckMorph() - { - } + public override bool CheckMorph() => true; public override void InitOutfit() { @@ -53,22 +51,9 @@ namespace Server.Engines.MLQuests.Mobiles HairHue = FacialHairHue = 0x8A7; AddItem(new Sandals()); - - Item item; - - item = new Cloak(); - item.ItemID = 0x26AD; - item.Hue = 0x455; - AddItem(item); - - item = new Robe(); - item.ItemID = 0x26AE; - item.Hue = 0x4AB; - AddItem(item); - - item = new Backpack(); - item.Movable = false; - AddItem(item); + AddItem(new Cloak{ ItemID = 0x26AD, Hue = 0x455}); + AddItem(new Robe {ItemID = 0x26AE, Hue = 0x4AB}); + AddItem(new Backpack {Movable = false}); } public override void OnDoubleClick(Mobile from) @@ -92,32 +77,23 @@ namespace Server.Engines.MLQuests.Mobiles if (m_NextShout <= DateTime.UtcNow) { - Packet shoutPacket = null; - - foreach (NetState state in GetClientsInRange(12)) + IPooledEnumerable eable = GetClientsInRange(12); + foreach (NetState state in eable) { Mobile m = state.Mobile; if (m.CanSee(this) && m.InLOS(this) && m.CanBeginAction(this)) - { - if (shoutPacket == null) - shoutPacket = Packet.Acquire(new MessageLocalized(Serial, Body, MessageType.Regular, 946, 3, - 1078099, Name, "")); // Double Click On Me For Help! - - state.Send(shoutPacket); - } + Packets.SendMessageLocalized(state, Serial, Body, MessageType.Regular, 946, 3, + 1078099, Name); // Double Click On Me For Help! } - Packet.Release(shoutPacket); + eable.Free(); m_NextShout = DateTime.UtcNow + m_ShoutDelay; } } - private void EndLock(Mobile m) - { - m.EndAction(this); - } + private void EndLock(Mobile m) => m.EndAction(this); public override void Serialize(GenericWriter writer) { @@ -135,4 +111,4 @@ namespace Server.Engines.MLQuests.Mobiles Frozen = true; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/MLQuests/Objectives/EscortObjective.cs b/Projects/Scripts/Engines/MLQuests/Objectives/EscortObjective.cs index a81783ed4..d21af44a0 100644 --- a/Projects/Scripts/Engines/MLQuests/Objectives/EscortObjective.cs +++ b/Projects/Scripts/Engines/MLQuests/Objectives/EscortObjective.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using Server.Gumps; using Server.Misc; using Server.Mobiles; @@ -20,14 +21,13 @@ namespace Server.Engines.MLQuests.Objectives MLQuestContext context = MLQuestSystem.GetContext(pm); if (context != null) - foreach (MLQuestInstance instance in context.QuestInstances) - if (instance.Quest.IsEscort) - { - if (message) - MLQuestSystem.Tell(quester, pm, 500896); // I see you already have an escort. + if (context.QuestInstances.Any(instance => instance.Quest.IsEscort)) + { + if (message) + MLQuestSystem.Tell(quester, pm, 500896); // I see you already have an escort. - return false; - } + return false; + } DateTime nextEscort = pm.LastEscortTime + BaseEscortable.EscortDelay; diff --git a/Projects/Scripts/Engines/MLQuests/Objectives/KillObjective.cs b/Projects/Scripts/Engines/MLQuests/Objectives/KillObjective.cs index 89f47f269..0f35da79a 100644 --- a/Projects/Scripts/Engines/MLQuests/Objectives/KillObjective.cs +++ b/Projects/Scripts/Engines/MLQuests/Objectives/KillObjective.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using Server.Gumps; using Server.Mobiles; @@ -91,22 +92,21 @@ namespace Server.Engines.MLQuests.Objectives { int desired = Objective.DesiredAmount; - foreach (Type acceptedType in Objective.AcceptedTypes) - if (acceptedType.IsAssignableFrom(type)) - { - if (Objective.Area?.Contains(mob) == false) - return false; + if (Objective.AcceptedTypes.Any(acceptedType => acceptedType.IsAssignableFrom(type))) + { + if (Objective.Area?.Contains(mob) == false) + return false; - PlayerMobile pm = Instance.Player; + PlayerMobile pm = Instance.Player; - if (++Slain >= desired) - pm.SendLocalizedMessage(1075050); // You have killed all the required quest creatures of this type. - else - pm.SendLocalizedMessage(1075051, - (desired - Slain).ToString()); // You have killed a quest creature. ~1_val~ more left. + if (++Slain >= desired) + pm.SendLocalizedMessage(1075050); // You have killed all the required quest creatures of this type. + else + pm.SendLocalizedMessage(1075051, + (desired - Slain).ToString()); // You have killed a quest creature. ~1_val~ more left. - return true; - } + return true; + } return false; } diff --git a/Projects/Scripts/Engines/MLQuests/QuestArea.cs b/Projects/Scripts/Engines/MLQuests/QuestArea.cs index 92e2986a4..74f2c3ef9 100644 --- a/Projects/Scripts/Engines/MLQuests/QuestArea.cs +++ b/Projects/Scripts/Engines/MLQuests/QuestArea.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; namespace Server.Engines.MLQuests { @@ -34,14 +35,7 @@ namespace Server.Engines.MLQuests // Debug method public void Validate() { - bool found = false; - - foreach (Region r in Region.Regions) - if (r.Name == RegionName && (ForceMap == null || r.Map == ForceMap)) - { - found = true; - break; - } + bool found = Region.Regions.Any(r => r.Name == RegionName && (ForceMap == null || r.Map == ForceMap)); if (!found) Console.WriteLine("Warning: QuestArea region '{0}' does not exist (ForceMap = {1})", RegionName, diff --git a/Projects/Scripts/Engines/MyRunUO/LayerComparer.cs b/Projects/Scripts/Engines/MyRunUO/LayerComparer.cs new file mode 100644 index 000000000..cf00d5b67 --- /dev/null +++ b/Projects/Scripts/Engines/MyRunUO/LayerComparer.cs @@ -0,0 +1,81 @@ +using System.Collections.Generic; + +namespace Server.Engines.MyRunUO +{ + public class LayerComparer : IComparer + { + private static Layer PlateArms = (Layer)255; + private static Layer ChainTunic = (Layer)254; + private static Layer LeatherShorts = (Layer)253; + + private static Layer[] m_DesiredLayerOrder = + { + Layer.Cloak, + Layer.Bracelet, + Layer.Ring, + Layer.Shirt, + Layer.Pants, + Layer.InnerLegs, + Layer.Shoes, + LeatherShorts, + Layer.Arms, + Layer.InnerTorso, + LeatherShorts, + PlateArms, + Layer.MiddleTorso, + Layer.OuterLegs, + Layer.Neck, + Layer.Waist, + Layer.Gloves, + Layer.OuterTorso, + Layer.OneHanded, + Layer.TwoHanded, + Layer.FacialHair, + Layer.Hair, + Layer.Helm, + Layer.Talisman + }; + + public static readonly IComparer Instance = new LayerComparer(); + + static LayerComparer() + { + TranslationTable = new int[256]; + + for (int i = 0; i < m_DesiredLayerOrder.Length; ++i) + TranslationTable[(int)m_DesiredLayerOrder[i]] = m_DesiredLayerOrder.Length - i; + } + + public static int[] TranslationTable{ get; } + + public int Compare(Item a, Item b) + { + if (a == null) + return b == null ? 0 : 1; + + if (b == null) + return -1; + + Layer aLayer = Fix(a.ItemID, a.Layer); + Layer bLayer = Fix(b.ItemID, b.Layer); + + return TranslationTable[(int)bLayer] - TranslationTable[(int)aLayer]; + } + + public static bool IsValid(Item item) => TranslationTable[(int)item.Layer] > 0; + + public Layer Fix(int itemID, Layer oldLayer) + { + if (itemID == 0x1410 || itemID == 0x1417) // platemail arms + return PlateArms; + + if (itemID == 0x13BF || itemID == 0x13C4) // chainmail tunic + return ChainTunic; + + if (itemID == 0x1C08 || itemID == 0x1C09 || itemID == 0x1C00 || itemID == 0x1C01) // leather skirt/shorts + return LeatherShorts; + + return oldLayer; + } + } +} \ No newline at end of file diff --git a/Projects/Scripts/Engines/Party/Packets.cs b/Projects/Scripts/Engines/Party/Packets.cs index e417d0b3c..cabd86171 100644 --- a/Projects/Scripts/Engines/Party/Packets.cs +++ b/Projects/Scripts/Engines/Party/Packets.cs @@ -1,77 +1,175 @@ +using Server.Buffers; using Server.Network; namespace Server.Engines.PartySystem { - public sealed class PartyEmptyList : Packet + public static class PartyPackets { - public PartyEmptyList(Mobile m) : base(0xBF) + public static void SendPartyEmptyList(NetState ns, Mobile m) { - EnsureCapacity(7); + if (ns == null) + return; - m_Stream.Write((short)0x0006); - m_Stream.Write((byte)0x02); - m_Stream.Write((byte)0); - m_Stream.Write(m.Serial); + SpanWriter writer = new SpanWriter(stackalloc byte[11]); + writer.Write((byte)0xBF); // Packet ID + writer.Write((short)11); // Dynamic Length + + writer.Write((short)0x06); + writer.Write((byte)0x02); + writer.Position++; // Writer(0); // Number of members + writer.Write(m.Serial); + + ns.Send(writer.Span); } - } - public sealed class PartyMemberList : Packet - { - public PartyMemberList(Party p) : base(0xBF) + public static void SendPartyMemberList(NetState ns, Party p) { - EnsureCapacity(7 + p.Count * 4); + if (ns == null) + return; - m_Stream.Write((short)0x0006); - m_Stream.Write((byte)0x01); - m_Stream.Write((byte)p.Count); + ushort length = (ushort)(7 + p.Count * 4); + + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0xBF); // Packet ID + writer.Write(length); // Dynamic Length + + writer.Write((short)0x06); + writer.Write((byte)0x01); + writer.Write((byte)p.Count); for (int i = 0; i < p.Count; ++i) - m_Stream.Write(p[i].Mobile.Serial); + writer.Write(p[i].Mobile.Serial); + + ns.Send(writer.Span); } - } - public sealed class PartyRemoveMember : Packet - { - public PartyRemoveMember(Mobile removed, Party p) : base(0xBF) + public static void SendPartyRemoveMember(NetState ns, Mobile removed, Party p) { - EnsureCapacity(11 + p.Count * 4); + if (ns == null) + return; - m_Stream.Write((short)0x0006); - m_Stream.Write((byte)0x02); - m_Stream.Write((byte)p.Count); + ushort length = (ushort)(11 + p.Count * 4); - m_Stream.Write(removed.Serial); + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0xBF); // Packet ID + writer.Write(length); // Dynamic Length + + writer.Write((short)0x06); + writer.Write((byte)0x02); + writer.Write((byte)p.Count); + writer.Write(removed.Serial); for (int i = 0; i < p.Count; ++i) - m_Stream.Write(p[i].Mobile.Serial); - } - } + writer.Write(p[i].Mobile.Serial); - public sealed class PartyTextMessage : Packet - { - public PartyTextMessage(bool toAll, Mobile from, string text) : base(0xBF) + ns.Send(writer.Span); + } + + public static void SendPartyRemoveMemberToAll(Mobile removed, Party p) { - if (text == null) - text = ""; - - EnsureCapacity(12 + text.Length * 2); - - m_Stream.Write((short)0x0006); - m_Stream.Write((byte)(toAll ? 0x04 : 0x03)); - m_Stream.Write(from.Serial); - m_Stream.WriteBigUniNull(text); + for (int i = 0; i < p.Members.Count; i++) + SendPartyRemoveMember(p[i].Mobile.NetState, removed, p); } - } - public sealed class PartyInvitation : Packet - { - public PartyInvitation(Mobile leader) : base(0xBF) + public static void SendPartyTextMessage(NetState ns, bool toAll, Mobile from, string text) { - EnsureCapacity(10); + if (ns == null) + return; - m_Stream.Write((short)0x0006); - m_Stream.Write((byte)0x07); - m_Stream.Write(leader.Serial); + ushort length = (ushort)(12 + text.Length * 2); + + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0xBF); // Packet ID + writer.Write(length); // Dynamic Length + + writer.Write((short)0x06); + writer.Write((byte)(toAll ? 0x04 : 0x03)); + writer.Write(from.Serial); + + writer.WriteBigUniNull(text); + + ns.Send(writer.Span); + } + + public static void SendPartyTextMessageToAll(Party p, bool toAll, Mobile from, string text) + { + for (int i = 0; i < p.Members.Count; ++i) + SendPartyTextMessage(p.Members[i].Mobile.NetState, toAll, from, text); + } + + public static void SendPartyInvitation(NetState ns, Mobile leader) + { + if (ns == null) + return; + + SpanWriter writer = new SpanWriter(stackalloc byte[10]); + writer.Write((byte)0xBF); // Packet ID + writer.Write((short)10); // Dynamic Length + + writer.Write((short)0x06); + writer.Write((byte)0x07); + writer.Write(leader.Serial); + + ns.Send(writer.Span); + } + + public static void SendPartyMessageLocalizedToAll(Party p, Serial serial, int graphic, MessageType type, int hue, int font, int number, string name = "", + string args = "") + { + for (int i = 0; i < p.Members.Count; ++i) + Packets.SendMessageLocalized(p.Members[i].Mobile.NetState, serial, graphic, type, hue, font, number, name, args); + + for (int i = 0; i < p.Listeners.Count; ++i) + { + Mobile mob = p.Listeners[i]; + + if (mob.Party != p) + Packets.SendMessageLocalized(mob.NetState, serial, graphic, type, hue, font, number, name, args); + } + } + + public static void SendPartyMessageLocalizedAffixToAll(Party p, Serial serial, int graphic, MessageType type, int hue, int font, int number, + string name = "", AffixType affixType = AffixType.System, string affix = "", string args = "") + { + for (int i = 0; i < p.Members.Count; ++i) + Packets.SendMessageLocalizedAffix(p.Members[i].Mobile.NetState, serial, graphic, type, hue, font, number, name, affixType, affix, args); + + for (int i = 0; i < p.Listeners.Count; ++i) + { + Mobile mob = p.Listeners[i]; + + if (mob.Party != p) + Packets.SendMessageLocalizedAffix(mob.NetState, serial, graphic, type, hue, font, number, name, affixType, affix, args); + } + } + + public static void SendPartyUnicodeMessageToAll(Party p, Serial serial, int graphic, MessageType type, int hue, int font, string lang, string name, + string text) + { + for (int i = 0; i < p.Members.Count; ++i) + Packets.SendUnicodeMessage(p.Members[i].Mobile.NetState, serial, graphic, type, hue, font, lang, name, text); + + for (int i = 0; i < p.Listeners.Count; ++i) + { + Mobile mob = p.Listeners[i]; + + if (mob.Party != p) + Packets.SendUnicodeMessage(p.Members[i].Mobile.NetState, serial, graphic, type, hue, font, lang, name, text); + } + } + + public static void SendPartyAsciiMessageToAll(Party p, Serial serial, int graphic, MessageType type, int hue, int font, string name, string text) + { + for (int i = 0; i < p.Members.Count; ++i) + Packets.SendAsciiMessage(p.Members[i].Mobile.NetState, serial, graphic, type, hue, font, name, text); + + for (int i = 0; i < p.Listeners.Count; ++i) + { + Mobile mob = p.Listeners[i]; + + if (mob.Party != p) + Packets.SendAsciiMessage(p.Members[i].Mobile.NetState, serial, graphic, type, hue, font, name, text); + } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Party/Party.cs b/Projects/Scripts/Engines/Party/Party.cs index 015ccbea4..037376b12 100644 --- a/Projects/Scripts/Engines/Party/Party.cs +++ b/Projects/Scripts/Engines/Party/Party.cs @@ -9,7 +9,6 @@ namespace Server.Engines.PartySystem public class Party : IParty { public const int Capacity = 10; - private List m_Listeners; // staff listening public Party(Mobile leader) { @@ -17,7 +16,7 @@ namespace Server.Engines.PartySystem Members = new List(); Candidates = new List(); - m_Listeners = new List(); + Listeners = new List(); Members.Add(new PartyMemberInfo(leader)); } @@ -30,58 +29,32 @@ namespace Server.Engines.PartySystem public List Candidates{ get; } + public List Listeners { get; } // staff listening + public PartyMemberInfo this[int index] => Members[index]; - public PartyMemberInfo this[Mobile m] - { - get - { - for (int i = 0; i < Members.Count; ++i) - if (Members[i].Mobile == m) - return Members[i]; - - return null; - } - } + public PartyMemberInfo this[Mobile m] => Members.FirstOrDefault(t => t.Mobile == m); public void OnStamChanged(Mobile m) { - Packet p = null; - for (int i = 0; i < Members.Count; ++i) { Mobile c = Members[i].Mobile; if (c != m && m.Map == c.Map && Utility.InUpdateRange(c, m) && c.CanSee(m)) - { - if (p == null) - p = Packet.Acquire(new MobileStamN(m)); - - c.Send(p); - } + Packets.SendNormalizedMobileStam(c.NetState, c); } - - Packet.Release(p); } public void OnManaChanged(Mobile m) { - Packet p = null; - for (int i = 0; i < Members.Count; ++i) { Mobile c = Members[i].Mobile; if (c != m && m.Map == c.Map && Utility.InUpdateRange(c, m) && c.CanSee(m)) - { - if (p == null) - p = Packet.Acquire(new MobileManaN(m)); - - c.Send(p); - } + Packets.SendNormalizedMobileMana(c.NetState, c); } - - Packet.Release(p); } public void OnStatsQuery(Mobile beholder, Mobile beheld) @@ -90,9 +63,9 @@ namespace Server.Engines.PartySystem Utility.InUpdateRange(beholder, beheld)) { if (!beholder.CanSee(beheld)) - beholder.Send(new MobileStatusCompact(beheld.CanBeRenamedBy(beholder), beheld)); + Packets.SendMobileStatusCompact(beholder.NetState, beheld, beheld.CanBeRenamedBy(beholder)); - beholder.Send(new MobileAttributesN(beheld)); + Packets.SendNormalizedMobileAttributes(beholder.NetState, beheld); } } @@ -121,14 +94,14 @@ namespace Server.Engines.PartySystem { from.SendMessage("They are not in a party."); } - else if (p.m_Listeners.Contains(from)) + else if (p.Listeners.Contains(from)) { - p.m_Listeners.Remove(from); + p.Listeners.Remove(from); from.SendMessage("You are no longer listening to that party."); } else { - p.m_Listeners.Add(from); + p.Listeners.Add(from); from.SendMessage("You are now listening to that party."); } } @@ -184,35 +157,25 @@ namespace Server.Engines.PartySystem Members.Add(new PartyMemberInfo(m)); m.Party = this; - Packet memberList = Packet.Acquire(new PartyMemberList(this)); - Packet attrs = Packet.Acquire(new MobileAttributesN(m)); - for (int i = 0; i < Members.Count; ++i) { Mobile f = Members[i].Mobile; + NetState ns = f.NetState; - f.Send(memberList); + PartyPackets.SendPartyMemberList(ns, this); if (f != m) { - f.Send(new MobileStatusCompact(m.CanBeRenamedBy(f), m)); - f.Send(attrs); - m.Send(new MobileStatusCompact(f.CanBeRenamedBy(m), f)); - m.Send(new MobileAttributesN(f)); + Packets.SendMobileStatusCompact(ns, m, m.CanBeRenamedBy(f)); + Packets.SendNormalizedMobileAttributes(ns, m); + Packets.SendMobileStatusCompact(ns, f, f.CanBeRenamedBy(m)); + Packets.SendNormalizedMobileAttributes(ns, f); } } - - Packet.Release(memberList); - Packet.Release(attrs); } } - public void OnAccept(Mobile from) - { - OnAccept(from, false); - } - - public void OnAccept(Mobile from, bool force) + public void OnAccept(Mobile from, bool force = false) { Faction ourFaction = Faction.Find(Leader); Faction theirFaction = Faction.Find(from); @@ -221,8 +184,8 @@ namespace Server.Engines.PartySystem return; // : joined the party. - SendToAll(new MessageLocalizedAffix(Serial.MinusOne, -1, MessageType.Label, 0x3B2, 3, 1008094, "", - AffixType.Prepend | AffixType.System, from.Name, "")); + PartyPackets.SendPartyMessageLocalizedAffixToAll(this, Serial.MinusOne, -1, MessageType.Label, + 0x3B2, 3, 1008094, "",AffixType.Prepend | AffixType.System, from.Name); from.SendLocalizedMessage(1005445); // You have been added to the party. @@ -238,14 +201,15 @@ namespace Server.Engines.PartySystem from.SendLocalizedMessage(1008092); // You notify them that you do not wish to join the party. Candidates.Remove(from); - from.Send(new PartyEmptyList(from)); + PartyPackets.SendPartyEmptyList(from.NetState, from); if (Candidates.Count == 0 && Members.Count <= 1) { for (int i = 0; i < Members.Count; ++i) { - this[i].Mobile.Send(new PartyEmptyList(this[i].Mobile)); - this[i].Mobile.Party = null; + Mobile m = this[i].Mobile; + PartyPackets.SendPartyEmptyList(m.NetState, m); + m.Party = null; } Members.Clear(); @@ -255,9 +219,7 @@ namespace Server.Engines.PartySystem public void Remove(Mobile m) { if (m == Leader) - { Disband(); - } else { for (int i = 0; i < Members.Count; ++i) @@ -266,19 +228,21 @@ namespace Server.Engines.PartySystem Members.RemoveAt(i); m.Party = null; - m.Send(new PartyEmptyList(m)); + PartyPackets.SendPartyEmptyList(m.NetState, m); m.SendLocalizedMessage(1005451); // You have been removed from the party. - SendToAll(new PartyRemoveMember(m, this)); - SendToAll(1005452); // A player has been removed from your party. + PartyPackets.SendPartyRemoveMemberToAll(m, this); + // A player has been removed from your party. + PartyPackets.SendPartyMessageLocalizedToAll(this, Serial.MinusOne, -1, MessageType.Regular, 0x3B2, 3, 1005452, "System"); break; } if (Members.Count == 1) { - SendToAll(1005450); // The last person has left the party... + // The last person has left the party... + PartyPackets.SendPartyMessageLocalizedToAll(this, Serial.MinusOne, -1, MessageType.Regular, 0x3B2, 3, 1005450, "System"); Disband(); } } @@ -288,12 +252,14 @@ namespace Server.Engines.PartySystem public void Disband() { - SendToAll(1005449); // Your party has disbanded. + // Your party has disbanded. + PartyPackets.SendPartyMessageLocalizedToAll(this, Serial.MinusOne, -1, MessageType.Regular, 0x3B2, 3, 1005449, "System"); for (int i = 0; i < Members.Count; ++i) { - this[i].Mobile.Send(new PartyEmptyList(this[i].Mobile)); - this[i].Mobile.Party = null; + Mobile m = this[i].Mobile; + PartyPackets.SendPartyEmptyList(m.NetState, m); + m.Party = null; } Members.Clear(); @@ -320,82 +286,57 @@ namespace Server.Engines.PartySystem p.Candidates.Add(target); // : You are invited to join the party. Type /accept to join or /decline to decline the offer. - target.Send(new MessageLocalizedAffix(Serial.MinusOne, -1, MessageType.Label, 0x3B2, 3, 1008089, "", - AffixType.Prepend | AffixType.System, from.Name, "")); + Packets.SendMessageLocalizedAffix(target.NetState, Serial.MinusOne, -1, MessageType.Label, 0x3B2, 3, 1008089, "", + AffixType.Prepend | AffixType.System, from.Name); from.SendLocalizedMessage(1008090); // You have invited them to join the party. - target.Send(new PartyInvitation(from)); + PartyPackets.SendPartyInvitation(target.NetState, from); target.Party = from; DeclineTimer.Start(target, from); } - public void SendToAll(int number) - { - SendToAll(number, "", 0x3B2); - } - - public void SendToAll(int number, string args) - { - SendToAll(number, args, 0x3B2); - } - - public void SendToAll(int number, string args, int hue) - { - SendToAll(new MessageLocalized(Serial.MinusOne, -1, MessageType.Regular, hue, 3, number, "System", args)); - } - public void SendPublicMessage(Mobile from, string text) { - SendToAll(new PartyTextMessage(true, from, text)); + PartyPackets.SendPartyTextMessageToAll(this, true, from, text); - for (int i = 0; i < m_Listeners.Count; ++i) + for (int i = 0; i < Listeners.Count; ++i) { - Mobile mob = m_Listeners[i]; + Mobile mob = Listeners[i]; if (mob.Party != this) - m_Listeners[i].SendMessage("[{0}]: {1}", from.Name, text); + Listeners[i].SendMessage("[{0}]: {1}", from.Name, text); } - SendToStaffMessage(from, "[Party]: {0}", text); + SendToStaffMessage(from, $"[Party]: {text}"); } public void SendPrivateMessage(Mobile from, Mobile to, string text) { - to.Send(new PartyTextMessage(false, from, text)); + PartyPackets.SendPartyTextMessage(to.NetState, false, from, text); - for (int i = 0; i < m_Listeners.Count; ++i) + for (int i = 0; i < Listeners.Count; ++i) { - Mobile mob = m_Listeners[i]; + Mobile mob = Listeners[i]; if (mob.Party != this) - m_Listeners[i].SendMessage("[{0}]->[{1}]: {2}", from.Name, to.Name, text); + Listeners[i].SendMessage("[{0}]->[{1}]: {2}", from.Name, to.Name, text); } - SendToStaffMessage(from, "[Party]->[{0}]: {1}", to.Name, text); + SendToStaffMessage(from, $"[Party]->[{to.Name}]: {text}"); } private void SendToStaffMessage(Mobile from, string text) { - Packet p = null; - foreach (NetState ns in from.GetClientsInRange(8)) { Mobile mob = ns.Mobile; if (mob?.AccessLevel >= AccessLevel.GameMaster && mob.AccessLevel > from.AccessLevel && - mob.Party != this && !m_Listeners.Contains(mob)) - { - if (p == null) - p = Packet.Acquire(new UnicodeMessage(from.Serial, from.Body, MessageType.Regular, from.SpeechHue, 3, - from.Language, from.Name, text)); - - ns.Send(p); - } + mob.Party != this && !Listeners.Contains(mob)) + Packets.SendUnicodeMessage(ns, from.Serial, from.Body, MessageType.Regular, from.SpeechHue, 3, from.Language, from.Name, text); } - - Packet.Release(p); } private void SendToStaffMessage(Mobile from, string format, params object[] args) @@ -403,25 +344,6 @@ namespace Server.Engines.PartySystem SendToStaffMessage(from, string.Format(format, args)); } - public void SendToAll(Packet p) - { - p.Acquire(); - - for (int i = 0; i < Members.Count; ++i) - Members[i].Mobile.Send(p); - - if (p is MessageLocalized || p is MessageLocalizedAffix || p is UnicodeMessage || p is AsciiMessage) - for (int i = 0; i < m_Listeners.Count; ++i) - { - Mobile mob = m_Listeners[i]; - - if (mob.Party != this) - mob.Send(p); - } - - p.Release(); - } - private class RejoinTimer : Timer { private Mobile m_Mobile; @@ -436,11 +358,7 @@ namespace Server.Engines.PartySystem return; m_Mobile.SendLocalizedMessage(1005437); // You have rejoined the party. - m_Mobile.Send(new PartyMemberList(p)); - - Packet message = Packet.Acquire(new MessageLocalizedAffix(Serial.MinusOne, -1, MessageType.Label, 0x3B2, 3, - 1008087, "", AffixType.Prepend | AffixType.System, m_Mobile.Name, "")); - Packet attrs = Packet.Acquire(new MobileAttributesN(m_Mobile)); + PartyPackets.SendPartyMemberList(m_Mobile.NetState, p); foreach (PartyMemberInfo mi in p.Members) { @@ -448,16 +366,15 @@ namespace Server.Engines.PartySystem if (m != m_Mobile) { - m.Send(message); - m.Send(new MobileStatusCompact(m_Mobile.CanBeRenamedBy(m), m_Mobile)); - m.Send(attrs); - m_Mobile.Send(new MobileStatusCompact(m.CanBeRenamedBy(m_Mobile), m)); - m_Mobile.Send(new MobileAttributesN(m)); + NetState ns = m.NetState; + Packets.SendMessageLocalizedAffix(ns, Serial.MinusOne, -1, MessageType.Label, 0x3B2, 3, + 1008087, "", AffixType.Prepend | AffixType.System, m_Mobile.Name); + Packets.SendMobileStatusCompact(ns, m_Mobile, m_Mobile.CanBeRenamedBy(m)); + Packets.SendNormalizedMobileAttributes(ns, m_Mobile); + Packets.SendMobileStatusCompact(ns, m, m.CanBeRenamedBy(m_Mobile)); + Packets.SendNormalizedMobileAttributes(ns, m); } } - - Packet.Release(message); - Packet.Release(attrs); } } } diff --git a/Projects/Scripts/Engines/Pathing/FastAStarAlgorithm.cs b/Projects/Scripts/Engines/Pathing/FastAStarAlgorithm.cs index 312e995c0..640b624bf 100644 --- a/Projects/Scripts/Engines/Pathing/FastAStarAlgorithm.cs +++ b/Projects/Scripts/Engines/Pathing/FastAStarAlgorithm.cs @@ -1,19 +1,17 @@ using System.Collections; using Server.Mobiles; -using CalcMoves = Server.Movement.Movement; -using MoveImpl = Server.Movement.MovementImpl; -namespace Server.PathAlgorithms.FastAStar +namespace Server.PathAlgorithms { - public struct PathNode - { - public int cost, total; - public int parent, next, prev; - public int z; - } - public class FastAStarAlgorithm : PathAlgorithm { + public struct PathNode + { + public int cost, total; + public int parent, next, prev; + public int z; + } + private const int MaxDepth = 300; private const int AreaSize = 38; @@ -134,18 +132,18 @@ namespace Server.PathAlgorithms.FastAStar if (bc != null) { - MoveImpl.AlwaysIgnoreDoors = bc.CanOpenDoors; - MoveImpl.IgnoreMovableImpassables = bc.CanMoveOverObstacles; + MovementImpl.AlwaysIgnoreDoors = bc.CanOpenDoors; + MovementImpl.IgnoreMovableImpassables = bc.CanMoveOverObstacles; } - MoveImpl.Goal = goal; + MovementImpl.Goal = goal; int[] vals = m_Successors; int count = GetSuccessors(bestNode, m, map); - MoveImpl.AlwaysIgnoreDoors = false; - MoveImpl.IgnoreMovableImpassables = false; - MoveImpl.Goal = Point3D.Zero; + MovementImpl.AlwaysIgnoreDoors = false; + MovementImpl.IgnoreMovableImpassables = false; + MovementImpl.Goal = Point3D.Zero; if (count == 0) break; @@ -158,26 +156,26 @@ namespace Server.PathAlgorithms.FastAStar if (wasTouched) continue; - + int newCost = m_Nodes[bestNode].cost + 1; int newTotal = newCost + Heuristic(newNode % AreaSize, newNode / AreaSize % AreaSize, m_Nodes[newNode].z); if (m_Nodes[newNode].total <= newTotal) continue; - + m_Nodes[newNode].parent = bestNode; m_Nodes[newNode].cost = newCost; m_Nodes[newNode].total = newTotal; if (m_OnOpen[newNode]) continue; - + AddToChain(newNode); if (newNode != destNode) continue; - + int pathCount = 0; int parent = m_Nodes[newNode].parent; @@ -296,7 +294,7 @@ namespace Server.PathAlgorithms.FastAStar if (x < 0 || x >= AreaSize || y < 0 || y >= AreaSize) continue; - if (CalcMoves.CheckMovement(m, map, p3D, (Direction)i, out int z)) + if (Movement.CheckMovement(m, map, p3D, (Direction)i, out int z)) { int idx = GetIndex(x + m_xOffset, y + m_yOffset, z); @@ -311,4 +309,4 @@ namespace Server.PathAlgorithms.FastAStar return count; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Pathing/FastMovement.cs b/Projects/Scripts/Engines/Pathing/FastMovement.cs index d71530a80..ae3fa8b67 100644 --- a/Projects/Scripts/Engines/Pathing/FastMovement.cs +++ b/Projects/Scripts/Engines/Pathing/FastMovement.cs @@ -8,7 +8,7 @@ using Server.Mobiles; #endregion -namespace Server.Movement +namespace Server { public class FastMovementImpl : IMovementImpl { @@ -179,7 +179,7 @@ namespace Server.Movement private static bool Check( Map map, Mobile m, - List items, + IReadOnlyCollection items, int x, int y, int startTop, diff --git a/Projects/Scripts/Engines/Pathing/Movement.cs b/Projects/Scripts/Engines/Pathing/Movement.cs index e04e7b1a8..6fbf02972 100644 --- a/Projects/Scripts/Engines/Pathing/Movement.cs +++ b/Projects/Scripts/Engines/Pathing/Movement.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using Server.Items; using Server.Mobiles; -namespace Server.Movement +namespace Server { public class MovementImpl : IMovementImpl { @@ -316,7 +316,7 @@ namespace Server.Movement return true; } - private bool Check(Map map, Mobile m, List items, List mobiles, int x, int y, int startTop, int startZ, + private bool Check(Map map, Mobile m, List items, IReadOnlyList mobiles, int x, int y, int startTop, int startZ, bool canSwim, bool cantWalk, out int newZ) { newZ = 0; @@ -500,7 +500,7 @@ namespace Server.Movement !t.Alive || !m.Alive || t.IsDeadBondedPet || m.IsDeadBondedPet || t.Hidden && t.AccessLevel > AccessLevel.Player; - private void GetStartZ(Mobile m, Map map, Point3D loc, List itemList, out int zLow, out int zTop) + private void GetStartZ(Mobile m, Map map, Point3D loc, IReadOnlyList itemList, out int zLow, out int zTop) { int xCheck = loc.X, yCheck = loc.Y; diff --git a/Projects/Scripts/Engines/Pathing/MovementPath.cs b/Projects/Scripts/Engines/Pathing/MovementPath.cs index 17a7f7409..ef993e52e 100644 --- a/Projects/Scripts/Engines/Pathing/MovementPath.cs +++ b/Projects/Scripts/Engines/Pathing/MovementPath.cs @@ -1,8 +1,6 @@ using System; using Server.Items; using Server.PathAlgorithms; -using Server.PathAlgorithms.FastAStar; -using Server.PathAlgorithms.SlowAStar; using Server.Spells; using Server.Targeting; @@ -84,7 +82,7 @@ namespace Server for (int i = 0; i < path.Directions.Length; ++i) { - Movement.Movement.Offset(path.Directions[i], ref x, ref y); + Movement.Offset(path.Directions[i], ref x, ref y); new RecallRune().MoveToWorld(new Point3D(x, y, z + zOffset), from.Map); } diff --git a/Projects/Scripts/Engines/Pathing/PathAlgorithm.cs b/Projects/Scripts/Engines/Pathing/PathAlgorithm.cs index 07500b988..9d04dd9ac 100644 --- a/Projects/Scripts/Engines/Pathing/PathAlgorithm.cs +++ b/Projects/Scripts/Engines/Pathing/PathAlgorithm.cs @@ -2,7 +2,7 @@ namespace Server.PathAlgorithms { public abstract class PathAlgorithm { - private static Direction[] m_CalcDirections = { + private static readonly Direction[] m_CalcDirections = { Direction.Up, Direction.North, Direction.Right, @@ -29,4 +29,4 @@ namespace Server.PathAlgorithms return m_CalcDirections[v]; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Pathing/PathFollower.cs b/Projects/Scripts/Engines/Pathing/PathFollower.cs index 6780ba930..43004f0b0 100644 --- a/Projects/Scripts/Engines/Pathing/PathFollower.cs +++ b/Projects/Scripts/Engines/Pathing/PathFollower.cs @@ -1,5 +1,4 @@ using System; -using CalcMoves = Server.Movement.Movement; namespace Server { @@ -52,7 +51,7 @@ namespace Server { int x = p.X, y = p.Y; - CalcMoves.Offset(dirs[index], ref x, ref y); + Movement.Offset(dirs[index], ref x, ref y); p.X = x; p.Y = y; diff --git a/Projects/Scripts/Engines/Pathing/SlowAStarAlgorithm.cs b/Projects/Scripts/Engines/Pathing/SlowAStarAlgorithm.cs index e09d23520..3b36291ab 100644 --- a/Projects/Scripts/Engines/Pathing/SlowAStarAlgorithm.cs +++ b/Projects/Scripts/Engines/Pathing/SlowAStarAlgorithm.cs @@ -1,20 +1,18 @@ using System; using Server.Mobiles; -using CalcMoves = Server.Movement.Movement; -using MoveImpl = Server.Movement.MovementImpl; -namespace Server.PathAlgorithms.SlowAStar +namespace Server.PathAlgorithms { - public struct PathNode - { - public int x, y, z; - public int g, h; - public int px, py, pz; - public int dir; - } - public class SlowAStarAlgorithm : PathAlgorithm { + public struct PathNode + { + public int x, y, z; + public int g, h; + public int px, py, pz; + public int dir; + } + private const int MaxDepth = 300; private const int MaxNodes = MaxDepth * 16; public static PathAlgorithm Instance = new SlowAStarAlgorithm(); @@ -148,11 +146,11 @@ namespace Server.PathAlgorithms.SlowAStar if (bc != null) { - MoveImpl.AlwaysIgnoreDoors = bc.CanOpenDoors; - MoveImpl.IgnoreMovableImpassables = bc.CanMoveOverObstacles; + MovementImpl.AlwaysIgnoreDoors = bc.CanOpenDoors; + MovementImpl.IgnoreMovableImpassables = bc.CanMoveOverObstacles; } - MoveImpl.Goal = goal; + MovementImpl.Goal = goal; int x; int y; @@ -162,7 +160,6 @@ namespace Server.PathAlgorithms.SlowAStar switch (i) { default: - case 0: x = 0; y = -1; break; @@ -196,7 +193,7 @@ namespace Server.PathAlgorithms.SlowAStar break; } - if (CalcMoves.CheckMovement(m, map, new Point3D(curNode.x, curNode.y, curNode.z), (Direction)i, out z)) + if (Movement.CheckMovement(m, map, new Point3D(curNode.x, curNode.y, curNode.z), (Direction)i, out z)) { successors[sucCount].x = x + curNode.x; successors[sucCount].y = y + curNode.y; @@ -204,9 +201,9 @@ namespace Server.PathAlgorithms.SlowAStar } } - MoveImpl.AlwaysIgnoreDoors = false; - MoveImpl.IgnoreMovableImpassables = false; - MoveImpl.Goal = Point3D.Zero; + MovementImpl.AlwaysIgnoreDoors = false; + MovementImpl.IgnoreMovableImpassables = false; + MovementImpl.Goal = Point3D.Zero; if (sucCount == 0 || ++depth > MaxDepth) break; @@ -272,4 +269,4 @@ namespace Server.PathAlgorithms.SlowAStar return null; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Plants/EmptyTheBowlGump.cs b/Projects/Scripts/Engines/Plants/EmptyTheBowlGump.cs index fdd97d00e..5b98406c2 100644 --- a/Projects/Scripts/Engines/Plants/EmptyTheBowlGump.cs +++ b/Projects/Scripts/Engines/Plants/EmptyTheBowlGump.cs @@ -75,7 +75,7 @@ namespace Server.Engines.Plants } case 2: // Help { - from.Send(new DisplayHelpTopic(71, true)); // EMPTYING THE BOWL + ContentPackets.SendDisplayHelpTopic(from.NetState, 17, true); // EMPTYING THE BOWL from.SendGump(new EmptyTheBowlGump(m_Plant)); diff --git a/Projects/Scripts/Engines/Plants/MainPlantGump.cs b/Projects/Scripts/Engines/Plants/MainPlantGump.cs index 835b8ed10..ae5da309a 100644 --- a/Projects/Scripts/Engines/Plants/MainPlantGump.cs +++ b/Projects/Scripts/Engines/Plants/MainPlantGump.cs @@ -264,9 +264,7 @@ namespace Server.Engines.Plants case 1: // Reproduction menu { if (m_Plant.PlantStatus > PlantStatus.BowlOfDirt) - { from.SendGump(new ReproductionGump(m_Plant)); - } else { from.SendLocalizedMessage(1061885); // You need to plant a seed in the bowl first. @@ -278,32 +276,28 @@ namespace Server.Engines.Plants } case 2: // Infestation { - from.Send(new DisplayHelpTopic(54, true)); // INFESTATION LEVEL - + ContentPackets.SendDisplayHelpTopic(from.NetState, 54, true); // INFESTATION LEVEL from.SendGump(new MainPlantGump(m_Plant)); break; } case 3: // Fungus { - from.Send(new DisplayHelpTopic(56, true)); // FUNGUS LEVEL - + ContentPackets.SendDisplayHelpTopic(from.NetState, 56, true); // FUNGUS LEVEL from.SendGump(new MainPlantGump(m_Plant)); break; } case 4: // Poison { - from.Send(new DisplayHelpTopic(58, true)); // POISON LEVEL - + ContentPackets.SendDisplayHelpTopic(from.NetState, 58, true); // POISON LEVEL from.SendGump(new MainPlantGump(m_Plant)); break; } case 5: // Disease { - from.Send(new DisplayHelpTopic(60, true)); // DISEASE LEVEL - + ContentPackets.SendDisplayHelpTopic(from.NetState, 60, true); // DISEASE LEVEL from.SendGump(new MainPlantGump(m_Plant)); break; @@ -320,9 +314,7 @@ namespace Server.Engines.Plants $"#{m_Plant.GetLocalizedPlantStatus()}"); // Target the container you wish to use to water the ~1_val~. } else - { m_Plant.Pour(from, bev); - } from.SendGump(new MainPlantGump(m_Plant)); @@ -354,7 +346,7 @@ namespace Server.Engines.Plants } case 11: // Help { - from.Send(new DisplayHelpTopic(48, true)); // PLANT GROWING + ContentPackets.SendDisplayHelpTopic(from.NetState, 48, true); // PLANT GROWING from.SendGump(new MainPlantGump(m_Plant)); @@ -374,9 +366,7 @@ namespace Server.Engines.Plants Item item = GetPotion(from, effects); if (item != null) - { m_Plant.Pour(from, item); - } else { if (m_Plant.ApplyPotion(effects[0], true, out int message)) diff --git a/Projects/Scripts/Engines/Plants/Network/DisplayHelpTopic.cs b/Projects/Scripts/Engines/Plants/Network/DisplayHelpTopic.cs deleted file mode 100644 index e026d8a03..000000000 --- a/Projects/Scripts/Engines/Plants/Network/DisplayHelpTopic.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Server.Network -{ - public class DisplayHelpTopic : Packet - { - public DisplayHelpTopic(int topicID, bool display) : base(0xBF) - { - EnsureCapacity(11); - - m_Stream.Write((short)0x17); - m_Stream.Write((byte)1); - m_Stream.Write(topicID); - m_Stream.Write(display); - } - } -} \ No newline at end of file diff --git a/Projects/Scripts/Engines/Plants/PlantItem.cs b/Projects/Scripts/Engines/Plants/PlantItem.cs index 6e825842b..db0a0124c 100644 --- a/Projects/Scripts/Engines/Plants/PlantItem.cs +++ b/Projects/Scripts/Engines/Plants/PlantItem.cs @@ -84,8 +84,7 @@ namespace Server.Engines.Plants } else { - if (PlantSystem == null) - PlantSystem = new PlantSystem(this, false); + PlantSystem ??= new PlantSystem(this, false); int hits = (int)(PlantSystem.MaxHits * ratio); diff --git a/Projects/Scripts/Engines/Plants/PlantResources.cs b/Projects/Scripts/Engines/Plants/PlantResources.cs index 32eae6913..6059c5140 100644 --- a/Projects/Scripts/Engines/Plants/PlantResources.cs +++ b/Projects/Scripts/Engines/Plants/PlantResources.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using Server.Items; namespace Server.Engines.Plants @@ -31,15 +32,9 @@ namespace Server.Engines.Plants public Type ResourceType{ get; } - public static PlantResourceInfo GetInfo(PlantType plantType, PlantHue plantHue) - { - foreach (PlantResourceInfo info in m_ResourceList) - if (info.PlantType == plantType && info.PlantHue == plantHue) - return info; - - return null; - } + public static PlantResourceInfo GetInfo(PlantType plantType, PlantHue plantHue) => + m_ResourceList.FirstOrDefault(info => info.PlantType == plantType && info.PlantHue == plantHue); public Item CreateResource() => (Item)Activator.CreateInstance(ResourceType); } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Plants/PlantSystem.cs b/Projects/Scripts/Engines/Plants/PlantSystem.cs index 25539101c..832a63fd1 100644 --- a/Projects/Scripts/Engines/Plants/PlantSystem.cs +++ b/Projects/Scripts/Engines/Plants/PlantSystem.cs @@ -383,6 +383,7 @@ namespace Server.Engines.Plants return 1060827; // soft if (Water <= 3) return 1060828; // squishy + return 1060829; // sopping wet } diff --git a/Projects/Scripts/Engines/Plants/PlantType.cs b/Projects/Scripts/Engines/Plants/PlantType.cs index aaeb5ea27..0010b253f 100644 --- a/Projects/Scripts/Engines/Plants/PlantType.cs +++ b/Projects/Scripts/Engines/Plants/PlantType.cs @@ -261,21 +261,13 @@ namespace Server.Engines.Plants double rand = Utility.RandomDouble(); - if (rand < 0.5 / exp4) - return PlantType.CommonGreenBonsai; - if (rand < 1.0 / exp4) - return PlantType.CommonPinkBonsai; - if (rand < (k1 * 0.5 + 1.0) / exp4) - return PlantType.UncommonGreenBonsai; - if (rand < exp1 / exp4) - return PlantType.UncommonPinkBonsai; - if (rand < (k2 * 0.5 + exp1) / exp4) - return PlantType.RareGreenBonsai; - if (rand < exp2 / exp4) - return PlantType.RarePinkBonsai; - if (rand < exp3 / exp4) - return PlantType.ExceptionalBonsai; - return PlantType.ExoticBonsai; + return rand < 0.5 / exp4 ? PlantType.CommonGreenBonsai : + rand < 1.0 / exp4 ? PlantType.CommonPinkBonsai : + rand < (k1 * 0.5 + 1.0) / exp4 ? PlantType.UncommonGreenBonsai : + rand < exp1 / exp4 ? PlantType.UncommonPinkBonsai : + rand < (k2 * 0.5 + exp1) / exp4 ? PlantType.RareGreenBonsai : + rand < exp2 / exp4 ? PlantType.RarePinkBonsai : + rand < exp3 / exp4 ? PlantType.ExceptionalBonsai : PlantType.ExoticBonsai; } public static bool IsCrossable(PlantType plantType) => GetInfo(plantType).Crossable; @@ -356,4 +348,4 @@ namespace Server.Engines.Plants return hueInfo.IsBright() ? 1113493 : 1113492; // ~1_amount~ [bright] ~2_color~ ~3_type~ seeds } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Plants/PollinateTarget.cs b/Projects/Scripts/Engines/Plants/PollinateTarget.cs index f7d0ded40..22b8e1cd9 100644 --- a/Projects/Scripts/Engines/Plants/PollinateTarget.cs +++ b/Projects/Scripts/Engines/Plants/PollinateTarget.cs @@ -14,50 +14,30 @@ namespace Server.Engines.Plants from.InRange(m_Plant.GetWorldLocation(), 3)) { if (!m_Plant.IsUsableBy(from)) - { m_Plant.LabelTo(from, 1061856); // You must have the item in your backpack or locked down in order to use it. - } else if (!m_Plant.IsCrossable) - { m_Plant.LabelTo(from, 1053050); // You cannot gather pollen from a mutated plant! - } else if (!m_Plant.PlantSystem.PollenProducing) - { m_Plant.LabelTo(from, 1053051); // You cannot gather pollen from a plant in this stage of development! - } else if (m_Plant.PlantSystem.Health < PlantHealth.Healthy) - { m_Plant.LabelTo(from, 1053052); // You cannot gather pollen from an unhealthy plant! - } else { if (!(targeted is PlantItem targ) || targ.PlantStatus >= PlantStatus.DecorativePlant || targ.PlantStatus <= PlantStatus.BowlOfDirt) - { m_Plant.LabelTo(from, 1053070); // You can only pollinate other specially grown plants! - } else if (!targ.IsUsableBy(from)) - { targ.LabelTo(from, 1061856); // You must have the item in your backpack or locked down in order to use it. - } else if (!targ.IsCrossable) - { targ.LabelTo(from, 1053073); // You cannot cross-pollinate with a mutated plant! - } else if (!targ.PlantSystem.PollenProducing) - { targ.LabelTo(from, 1053074); // This plant is not in the flowering stage. You cannot pollinate it! - } else if (targ.PlantSystem.Health < PlantHealth.Healthy) - { targ.LabelTo(from, 1053075); // You cannot pollinate an unhealthy plant! - } else if (targ.PlantSystem.Pollinated) - { targ.LabelTo(from, 1053072); // This plant has already been pollinated! - } else if (targ == m_Plant) { targ.PlantSystem.Pollinated = true; @@ -85,4 +65,4 @@ namespace Server.Engines.Plants m_Plant.IsUsableBy(from)) from.SendGump(new ReproductionGump(m_Plant)); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Plants/ReproductionGump.cs b/Projects/Scripts/Engines/Plants/ReproductionGump.cs index ead5ca625..5506bf512 100644 --- a/Projects/Scripts/Engines/Plants/ReproductionGump.cs +++ b/Projects/Scripts/Engines/Plants/ReproductionGump.cs @@ -138,24 +138,21 @@ namespace Server.Engines.Plants } case 3: // Pollination { - from.Send(new DisplayHelpTopic(67, true)); // POLLINATION STATE - + ContentPackets.SendDisplayHelpTopic(from.NetState, 67, true); // POLLINATION STATE from.SendGump(new ReproductionGump(m_Plant)); break; } case 4: // Resources { - from.Send(new DisplayHelpTopic(69, true)); // RESOURCE PRODUCTION - + ContentPackets.SendDisplayHelpTopic(from.NetState, 69, true); // RESOURCE PRODUCTION from.SendGump(new ReproductionGump(m_Plant)); break; } case 5: // Seeds { - from.Send(new DisplayHelpTopic(68, true)); // SEED PRODUCTION - + ContentPackets.SendDisplayHelpTopic(from.NetState, 68, true); // SEED PRODUCTION from.SendGump(new ReproductionGump(m_Plant)); break; @@ -200,9 +197,7 @@ namespace Server.Engines.Plants m_Plant.LabelTo(from, 1053055); // Mutated plants do not produce resources! } else if (system.AvailableResources == 0) - { m_Plant.LabelTo(from, 1053056); // This plant has no resources to gather! - } else { Item resource = resInfo.CreateResource(); @@ -229,13 +224,9 @@ namespace Server.Engines.Plants PlantSystem system = m_Plant.PlantSystem; if (!m_Plant.Reproduces) - { m_Plant.LabelTo(from, 1053060); // Mutated plants do not produce seeds! - } else if (system.AvailableSeeds == 0) - { m_Plant.LabelTo(from, 1053061); // This plant has no seeds to gather! - } else { Seed seed = new Seed(system.SeedType, system.SeedHue, true); diff --git a/Projects/Scripts/Engines/Plants/SetToDecorativeGump.cs b/Projects/Scripts/Engines/Plants/SetToDecorativeGump.cs index 5b3a60bce..4e63c8166 100644 --- a/Projects/Scripts/Engines/Plants/SetToDecorativeGump.cs +++ b/Projects/Scripts/Engines/Plants/SetToDecorativeGump.cs @@ -64,7 +64,7 @@ namespace Server.Engines.Plants } case 2: // Help { - from.Send(new DisplayHelpTopic(70, true)); // DECORATIVE MODE + ContentPackets.SendDisplayHelpTopic(from.NetState, 70, true); // DECORATIVE MODE from.SendGump(new SetToDecorativeGump(m_Plant)); diff --git a/Projects/Scripts/Engines/Quests/Collector/Items/Obsidian.cs b/Projects/Scripts/Engines/Quests/Collector/Items/Obsidian.cs index d48cd0da2..a0e87b719 100644 --- a/Projects/Scripts/Engines/Quests/Collector/Items/Obsidian.cs +++ b/Projects/Scripts/Engines/Quests/Collector/Items/Obsidian.cs @@ -167,11 +167,10 @@ namespace Server.Engines.Quests.Collector { if (m_Quantity < m_Completed) { - if (!IsChildOf(from.Backpack)) - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Regular, 0x2C, 3, 500309, "", - "")); // Nothing Happens. - else + if (IsChildOf(from.Backpack)) from.Target = new InternalTarget(this); + else + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Regular, 0x2C, 3, 500309); // Nothing Happens. } } @@ -245,15 +244,15 @@ namespace Server.Engines.Quests.Collector if (targObsidian.Quantity >= m_Completed) targObsidian.StatueName = RandomName(from); - from.Send(new AsciiMessage(targObsidian.Serial, targObsidian.ItemID, MessageType.Regular, 0x59, 3, - m_Obsidian.Name, "Something Happened.")); + Packets.SendAsciiMessage(from.NetState, targObsidian.Serial, targObsidian.ItemID, MessageType.Regular, 0x59, 3, + m_Obsidian.Name, "Something Happened."); return; } - from.Send(new MessageLocalized(m_Obsidian.Serial, m_Obsidian.ItemID, MessageType.Regular, 0x2C, 3, 500309, - m_Obsidian.Name, "")); // Nothing Happens. + Packets.SendMessageLocalized(from.NetState, m_Obsidian.Serial, m_Obsidian.ItemID, MessageType.Regular, 0x2C, 3, 500309, + m_Obsidian.Name); // Nothing Happens. } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Quests/Collector/Objectives.cs b/Projects/Scripts/Engines/Quests/Collector/Objectives.cs index c59bd2a2b..9157eba14 100644 --- a/Projects/Scripts/Engines/Quests/Collector/Objectives.cs +++ b/Projects/Scripts/Engines/Quests/Collector/Objectives.cs @@ -359,4 +359,4 @@ namespace Server.Engines.Quests.Collector { public override object Message => 1055136; } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Quests/Core/Items/EnchantedSextant.cs b/Projects/Scripts/Engines/Quests/Core/Items/EnchantedSextant.cs index 2bb1b0fe0..9282a47f1 100644 --- a/Projects/Scripts/Engines/Quests/Core/Items/EnchantedSextant.cs +++ b/Projects/Scripts/Engines/Quests/Core/Items/EnchantedSextant.cs @@ -99,11 +99,10 @@ namespace Server.Items else if (from.Map == Map.Ilshenar) { #if false - banks = m_IlshenarBanks; - moongates = PMList.Ilshenar; + banks = m_IlshenarBanks; + moongates = PMList.Ilshenar; #else - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Label, 0x482, 3, 1061684, "", - "")); // The magic of the sextant fails... + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, 0x482, 3, 1061684); // The magic of the sextant fails... return; #endif } @@ -154,7 +153,7 @@ namespace Server.Items else moonMsg = 1048018; // You are next to a Moongate at the moment. - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Label, 0x482, 3, moonMsg, "", "")); + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, 0x482, 3, moonMsg); int bankMsg; if (bankDistance == double.MaxValue) @@ -166,7 +165,7 @@ namespace Server.Items else bankMsg = 1048019; // You are next to a Bank at the moment. - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Label, 0x5AA, 3, bankMsg, "", "")); + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, 0x5AA, 3, bankMsg); } public override void Serialize(GenericWriter writer) @@ -183,4 +182,4 @@ namespace Server.Items int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Quests/Core/QuestSerializer.cs b/Projects/Scripts/Engines/Quests/Core/QuestSerializer.cs index fcec07493..e8aabf4aa 100644 --- a/Projects/Scripts/Engines/Quests/Core/QuestSerializer.cs +++ b/Projects/Scripts/Engines/Quests/Core/QuestSerializer.cs @@ -44,9 +44,7 @@ namespace Server.Engines.Quests switch (encoding) { default: - { return null; - } case 0x01: // indexed { int index = reader.ReadEncodedInt(); @@ -75,9 +73,7 @@ namespace Server.Engines.Quests switch (encoding) { default: - { return null; - } case 0x01: { Type type = ReadType(QuestSystem.QuestTypes, reader); @@ -94,9 +90,7 @@ namespace Server.Engines.Quests public static void Serialize(QuestSystem qs, GenericWriter writer) { if (qs == null) - { writer.WriteEncodedInt(0x00); - } else { writer.WriteEncodedInt(0x01); @@ -114,9 +108,7 @@ namespace Server.Engines.Quests switch (encoding) { default: - { return null; - } case 0x01: { Type type = ReadType(referenceTable, reader); @@ -133,9 +125,7 @@ namespace Server.Engines.Quests public static void Serialize(Type[] referenceTable, QuestObjective obj, GenericWriter writer) { if (obj == null) - { writer.WriteEncodedInt(0x00); - } else { writer.WriteEncodedInt(0x01); @@ -153,9 +143,7 @@ namespace Server.Engines.Quests switch (encoding) { default: - { return null; - } case 0x01: { Type type = ReadType(referenceTable, reader); @@ -172,9 +160,7 @@ namespace Server.Engines.Quests public static void Serialize(Type[] referenceTable, QuestConversation conv, GenericWriter writer) { if (conv == null) - { writer.WriteEncodedInt(0x00); - } else { writer.WriteEncodedInt(0x01); diff --git a/Projects/Scripts/Engines/Quests/Core/QuestSystem.cs b/Projects/Scripts/Engines/Quests/Core/QuestSystem.cs index 01397d2a0..129093721 100644 --- a/Projects/Scripts/Engines/Quests/Core/QuestSystem.cs +++ b/Projects/Scripts/Engines/Quests/Core/QuestSystem.cs @@ -259,7 +259,7 @@ namespace Server.Engines.Quests From.SendGump(new QuestObjectivesGump(Objectives)); - QuestObjective last = Objectives[Objectives.Count - 1]; + QuestObjective last = Objectives[^1]; if (last.Info != null) From.SendGump(new QuestItemInfoGump(last.Info)); @@ -276,7 +276,7 @@ namespace Server.Engines.Quests From.SendGump(new QuestConversationsGump(Conversations)); - QuestConversation last = Conversations[Conversations.Count - 1]; + QuestConversation last = Conversations[^1]; if (last.Info != null) From.SendGump(new QuestItemInfoGump(last.Info)); diff --git a/Projects/Scripts/Engines/Quests/Dark Tides/Items/KronusScroll.cs b/Projects/Scripts/Engines/Quests/Dark Tides/Items/KronusScroll.cs index b0cdb7038..81912200d 100644 --- a/Projects/Scripts/Engines/Quests/Dark Tides/Items/KronusScroll.cs +++ b/Projects/Scripts/Engines/Quests/Dark Tides/Items/KronusScroll.cs @@ -1,13 +1,12 @@ using System; using Server.Items; using Server.Mobiles; -using Server.Network; namespace Server.Engines.Quests.Necro { public class KronusScroll : QuestItem { - private static readonly Rectangle2D m_WellOfTearsArea = new Rectangle2D(2080, 1346, 10, 10); + private static Rectangle2D m_WellOfTearsArea = new Rectangle2D(2080, 1346, 10, 10); private static readonly Map m_WellOfTearsMap = Map.Malas; [Constructible] @@ -134,9 +133,7 @@ namespace Server.Engines.Quests.Necro int hue = Utility.RandomList(0x481, 0x482, 0x489, 0x497, 0x66D); - Effects.SendPacket(from, map, - new HuedEffect(EffectType.Moving, Serial.Zero, Serial.Zero, 0x36D4, from, to, 0, 0, false, true, - hue, 0)); + Effects.SendMovingEffect(from, to, map, 0x36D4, 0, 0, false, true, hue); } } @@ -155,4 +152,4 @@ namespace Server.Engines.Quests.Necro } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Quests/Dark Tides/Items/MaabusCoffin.cs b/Projects/Scripts/Engines/Quests/Dark Tides/Items/MaabusCoffin.cs index d1e311a1d..c6ce70243 100644 --- a/Projects/Scripts/Engines/Quests/Dark Tides/Items/MaabusCoffin.cs +++ b/Projects/Scripts/Engines/Quests/Dark Tides/Items/MaabusCoffin.cs @@ -65,8 +65,8 @@ namespace Server.Engines.Quests.Necro Maabus.Delete(); Maabus = null; - foreach (MaabusCoffinComponent c in Components) - c.TurnToFull(); + foreach (AddonComponent addonComponent in Components) + (addonComponent as MaabusCoffinComponent)?.TurnToFull(); } public override void Serialize(GenericWriter writer) @@ -151,4 +151,4 @@ namespace Server.Engines.Quests.Necro m_EmptyItemID = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Quests/Dark Tides/Objectives.cs b/Projects/Scripts/Engines/Quests/Dark Tides/Objectives.cs index 4eb61cc39..f39afebba 100644 --- a/Projects/Scripts/Engines/Quests/Dark Tides/Objectives.cs +++ b/Projects/Scripts/Engines/Quests/Dark Tides/Objectives.cs @@ -258,7 +258,7 @@ namespace Server.Engines.Quests.Necro public class FindWellOfTearsObjective : QuestObjective { - private static readonly Rectangle2D m_WellOfTearsArea = new Rectangle2D(2080, 1346, 10, 10); + private static Rectangle2D m_WellOfTearsArea = new Rectangle2D(2080, 1346, 10, 10); private bool m_Inside; diff --git a/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Conversations.cs b/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Conversations.cs index 1ed974af4..c62b965ab 100644 --- a/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Conversations.cs +++ b/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Conversations.cs @@ -36,29 +36,29 @@ namespace Server.Engines.Quests.Haven if (System.From.Profession == 2) // magician return 1049386; -/* Uzeraan nods at you with approval and begins to speak... - * - * Now that you are ready, let me give you your first task. - * - * As I mentioned earlier, we have been trying to fight back the wicked - * Horde Minions which have recently begun attacking our cities - * - but to no avail. Our need is great! - * - * Your first task will be to assess the situation in the mountain pass, - * and help our troops defeat the Horde Minions there. - * - * Take the road marked with glowing runes, that starts just outside of this mansion. - * Before you go into battle, it would be prudent to - * review combat techniques as well as - * information on healing yourself, - * using your Paladin ability 'Close Wounds'. - * - * To aid you in your fight, you may also wish to - * purchase equipment from Frank the Blacksmith, - * who is standing just South of here. - * - * Good luck young Paladin! - */ + /* Uzeraan nods at you with approval and begins to speak... + * + * Now that you are ready, let me give you your first task. + * + * As I mentioned earlier, we have been trying to fight back the wicked + * Horde Minions which have recently begun attacking our cities + * - but to no avail. Our need is great! + * + * Your first task will be to assess the situation in the mountain pass, + * and help our troops defeat the Horde Minions there. + * + * Take the road marked with glowing runes, that starts just outside of this mansion. + * Before you go into battle, it would be prudent to + * review combat techniques as well as + * information on healing yourself, + * using your Paladin ability 'Close Wounds'. + * + * To aid you in your fight, you may also wish to + * purchase equipment from Frank the Blacksmith, + * who is standing just South of here. + * + * Good luck young Paladin! + */ return 1060388; } } @@ -73,7 +73,7 @@ namespace Server.Engines.Quests.Haven public class UzeraanReportConversation : QuestConversation { - private static QuestItemInfo[] m_Info = + private static readonly QuestItemInfo[] m_Info = { new QuestItemInfo(1026153, 0x1822), // teleporter new QuestItemInfo(1048032, 0xE76) // a bag @@ -469,4 +469,4 @@ namespace Server.Engines.Quests.Haven public override bool Logged => false; } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Items/SchmendrickApprenticeCorpse.cs b/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Items/SchmendrickApprenticeCorpse.cs index 0f0904646..8847c6609 100644 --- a/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Items/SchmendrickApprenticeCorpse.cs +++ b/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Items/SchmendrickApprenticeCorpse.cs @@ -28,15 +28,14 @@ namespace Server.Engines.Quests.Haven { } - // TODO: What is this? Why are we creating and deleting a mobile? + // TODO: Should be a better way than making/deleting a mob. private static Mobile GetOwner() { - Mobile apprentice = new Mobile(); + Mobile apprentice = new Mobile + { + Hue = Race.Human.RandomSkinHue(), Female = false, Body = 0x190, Name = NameList.RandomName("male") + }; - apprentice.Hue = Race.Human.RandomSkinHue(); - apprentice.Female = false; - apprentice.Body = 0x190; - apprentice.Name = NameList.RandomName("male"); apprentice.Delete(); @@ -45,12 +44,14 @@ namespace Server.Engines.Quests.Haven private static List GetEquipment() { - List list = new List(); + List list = new List + { + new Robe(QuestSystem.RandomBrightHue()), + new WizardsHat(Utility.RandomNeutralHue()), + new Shoes(Utility.RandomNeutralHue()), + new Spellbook() + }; - list.Add(new Robe(QuestSystem.RandomBrightHue())); - list.Add(new WizardsHat(Utility.RandomNeutralHue())); - list.Add(new Shoes(Utility.RandomNeutralHue())); - list.Add(new Spellbook()); return list; } @@ -86,11 +87,10 @@ namespace Server.Engines.Quests.Haven int hue = Notoriety.GetHue(NotorietyHandlers.CorpseNotoriety(from, this)); if (ItemID == 0x2006) // Corpse form - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Label, hue, 3, 1049144, "", - Name)); // the remains of ~1_NAME~ the apprentice + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, hue, 3, 1049144, "", + Name); // the remains of ~1_NAME~ the apprentice else - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Label, hue, 3, 1049145, "", - "")); // the remains of a wizard's apprentice + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, hue, 3, 1049145); // the remains of a wizard's apprentice } public override void Open(Mobile from, bool checkSelfLoot) diff --git a/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Mobiles/MilitiaFighter.cs b/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Mobiles/MilitiaFighter.cs index 28a4e6619..155c0a5a2 100644 --- a/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Mobiles/MilitiaFighter.cs +++ b/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Mobiles/MilitiaFighter.cs @@ -118,11 +118,10 @@ namespace Server.Engines.Quests.Haven int hue = Notoriety.GetHue(NotorietyHandlers.CorpseNotoriety(from, this)); if (ItemID == 0x2006) // Corpse form - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Label, hue, 3, 1049318, "", - Name)); // the remains of ~1_NAME~ the militia fighter + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, hue, 3, 1049318, "", + Name); // the remains of ~1_NAME~ the militia fighter else - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Label, hue, 3, 1049319, "", - "")); // the remains of a militia fighter + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, hue, 3, 1049318); // the remains of a militia fighters } public override void Open(Mobile from, bool checkSelfLoot) @@ -146,4 +145,4 @@ namespace Server.Engines.Quests.Haven int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Objectives.cs b/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Objectives.cs index b023c610f..a4e34843f 100644 --- a/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Objectives.cs +++ b/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/Objectives.cs @@ -72,9 +72,8 @@ namespace Server.Engines.Quests.Haven public KillHordeMinionsStep Step{ get; private set; } - public override object Message - { - get + public override object Message => + Step switch { return Step switch { @@ -108,19 +107,7 @@ namespace Server.Engines.Quests.Haven _ => 5 }; - return 5; - } - } - - public override bool Completed - { - get - { - if (Step == KillHordeMinionsStep.LearnKarma && HasBeenRead) - return true; - return base.Completed; - } - } + public override bool Completed => Step == KillHordeMinionsStep.LearnKarma && HasBeenRead || base.Completed; public override void RenderProgress(BaseQuestGump gump) { @@ -140,23 +127,15 @@ namespace Server.Engines.Quests.Haven CheckCompletionStatus(); } - public override bool IgnoreYoungProtection(Mobile from) - { - // This restriction continues until the quest is ended - if (from is HordeMinion && from.Map == Map.Trammel && from.X >= 3314 && from.X <= 3814 && from.Y >= 2345 && - from.Y <= 3095) // Haven island - return true; - - return false; - } + public override bool IgnoreYoungProtection(Mobile from) => + from is HordeMinion && from.Map == Map.Trammel && TreasureMap.IsInHavenIsland(from); public override void OnKill(BaseCreature creature, Container corpse) { - if (creature is HordeMinion && corpse.Map == Map.Trammel && corpse.X >= 3314 && corpse.X <= 3814 && - corpse.Y >= 2345 && corpse.Y <= 3095) // Haven island + if (creature is HordeMinion && corpse.Map == Map.Trammel && TreasureMap.IsInHavenIsland(corpse)) { if (CurProgress == 0) - System.From.Send(new DisplayHelpTopic(29, false)); // HEALING + ContentPackets.SendDisplayHelpTopic(System.From.NetState, 29, false); // HEALING CurProgress++; } @@ -340,49 +319,26 @@ namespace Server.Engines.Quests.Haven { public Container CorpseWithBone{ get; set; } - public override object Message - { - get - { - if (System.From.Profession == 5) return 1060755; - - /* Use Uzeraan's teleporter to get to the Haunted graveyard. - * - * Slay the undead until you find a Daemon Bone. - */ - return 1049362; - } - } + public override object Message => System.From.Profession == 5 ? 1060755 : 1049362; public override void OnComplete() { System.AddObjective(new ReturnDaemonBoneObjective()); } - public override bool IgnoreYoungProtection(Mobile from) - { - // This restriction continues until the end of the quest - if ((from is Zombie || from is Skeleton) && from.Map == Map.Trammel && from.X >= 3391 && from.X <= 3424 && - from.Y >= 2639 && from.Y <= 2664) // Haven graveyard - return true; + private static bool IsInHavenGraveyard(IPoint2D p) => p.X >= 3391 && p.X <= 3424 && + p.Y >= 2639 && p.Y <= 2664; - return false; - } + public override bool IgnoreYoungProtection(Mobile from) => + (from is Zombie || from is Skeleton) && from.Map == Map.Trammel && IsInHavenGraveyard(from); - public override bool GetKillEvent(BaseCreature creature, Container corpse) - { - if (base.GetKillEvent(creature, corpse)) - return true; - - return UzeraanTurmoilQuest.HasLostDaemonBone(System.From); - } + public override bool GetKillEvent(BaseCreature creature, Container corpse) => + base.GetKillEvent(creature, corpse) || UzeraanTurmoilQuest.HasLostDaemonBone(System.From); public override void OnKill(BaseCreature creature, Container corpse) { - if ((creature is Zombie || creature is Skeleton) && corpse.Map == Map.Trammel && corpse.X >= 3391 && - corpse.X <= 3424 && corpse.Y >= 2639 && corpse.Y <= 2664) // Haven graveyard - if (Utility.RandomDouble() < 0.25) - CorpseWithBone = corpse; + if ((creature is Zombie || creature is Skeleton) && corpse.Map == Map.Trammel && IsInHavenGraveyard(corpse) && Utility.RandomDouble() < 0.25) + CorpseWithBone = corpse; } public override void ChildDeserialize(GenericReader reader) diff --git a/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/UzeraanTurmoilQuest.cs b/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/UzeraanTurmoilQuest.cs index e19696888..55f19b5ea 100644 --- a/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/UzeraanTurmoilQuest.cs +++ b/Projects/Scripts/Engines/Quests/Uzeraan Turmoil/UzeraanTurmoilQuest.cs @@ -62,9 +62,8 @@ namespace Server.Engines.Quests.Haven public override TimeSpan RestartDelay => TimeSpan.MaxValue; public override bool IsTutorial => true; - public override int Picture - { - get + public override int Picture => + From.Profession switch { return From.Profession switch { diff --git a/Projects/Scripts/Engines/Quests/Witch Apprentice/Ingredient.cs b/Projects/Scripts/Engines/Quests/Witch Apprentice/Ingredient.cs index 5589c845d..807b5d3ee 100644 --- a/Projects/Scripts/Engines/Quests/Witch Apprentice/Ingredient.cs +++ b/Projects/Scripts/Engines/Quests/Witch Apprentice/Ingredient.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using Server.Mobiles; namespace Server.Engines.Quests.Hag @@ -89,12 +90,7 @@ namespace Server.Engines.Quests.Hag { Ingredient currIngredient = (Ingredient)i; - bool found = false; - for (int j = 0; !found && j < oldIngredients.Length; j++) - if (oldIngredients[j] == currIngredient) - found = true; - - if (!found) + if (oldIngredients.All(ingredient => ingredient != currIngredient)) ingredients[n++] = currIngredient; } @@ -103,4 +99,4 @@ namespace Server.Engines.Quests.Hag return ingredients[index]; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Quests/Witch Apprentice/Items/HagApprenticeCorpse.cs b/Projects/Scripts/Engines/Quests/Witch Apprentice/Items/HagApprenticeCorpse.cs index 66e7fba84..39d9d29ad 100644 --- a/Projects/Scripts/Engines/Quests/Witch Apprentice/Items/HagApprenticeCorpse.cs +++ b/Projects/Scripts/Engines/Quests/Witch Apprentice/Items/HagApprenticeCorpse.cs @@ -46,7 +46,7 @@ namespace Server.Engines.Quests.Hag { int hue = Notoriety.GetHue(NotorietyHandlers.CorpseNotoriety(from, this)); - from.Send(new AsciiMessage(Serial, ItemID, MessageType.Label, hue, 3, "", "a charred corpse")); + Packets.SendAsciiMessage(from.NetState, Serial, ItemID, MessageType.Label, hue, 3, "", "a charred corpse"); } public override void Open(Mobile from, bool checkSelfLoot) @@ -96,4 +96,4 @@ namespace Server.Engines.Quests.Hag int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/Quests/Witch Apprentice/Objectives.cs b/Projects/Scripts/Engines/Quests/Witch Apprentice/Objectives.cs index 777ab0fa8..e715ac8b1 100644 --- a/Projects/Scripts/Engines/Quests/Witch Apprentice/Objectives.cs +++ b/Projects/Scripts/Engines/Quests/Witch Apprentice/Objectives.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using Server.Items; using Server.Mobiles; @@ -50,7 +51,7 @@ namespace Server.Engines.Quests.Hag Corpse = new HagApprenticeCorpse(); Corpse.MoveToWorld(m_CorpseLocation, map); - Effects.SendLocationEffect(m_CorpseLocation, map, 0x3728, 10, 10); + Effects.SendLocationEffect(m_CorpseLocation, map, 0x3728, 10); Effects.PlaySound(m_CorpseLocation, map, 0x1FE); Mobile imp = new Zeefzorpul(); @@ -66,7 +67,7 @@ namespace Server.Engines.Quests.Hag { if (m?.Deleted == false) { - Effects.SendLocationEffect(m.Location, m.Map, 0x3728, 10, 10); + Effects.SendLocationEffect(m.Location, m.Map, 0x3728, 10); Effects.PlaySound(m.Location, m.Map, 0x1FE); m.Delete(); @@ -204,7 +205,7 @@ namespace Server.Engines.Quests.Hag Mobile from = System.From; Map map = from.Map; - Effects.SendLocationEffect(ImpLocation, map, 0x3728, 10, 10); + Effects.SendLocationEffect(ImpLocation, map, 0x3728, 10); Effects.PlaySound(ImpLocation, map, 0x1FE); Mobile imp = new Zeefzorpul(); @@ -219,7 +220,7 @@ namespace Server.Engines.Quests.Hag { if (imp is Mobile m && !m.Deleted) { - Effects.SendLocationEffect(m.Location, m.Map, 0x3728, 10, 10); + Effects.SendLocationEffect(m.Location, m.Map, 0x3728, 10); Effects.PlaySound(m.Location, m.Map, 0x1FE); m.Delete(); @@ -266,7 +267,7 @@ namespace Server.Engines.Quests.Hag for (int i = 0; i < oldIngredients.Length; i++) Ingredients[i] = oldIngredients[i]; - Ingredients[Ingredients.Length - 1] = IngredientInfo.RandomIngredient(oldIngredients); + Ingredients[^1] = IngredientInfo.RandomIngredient(oldIngredients); } else { @@ -279,13 +280,8 @@ namespace Server.Engines.Quests.Hag BlackheartMet = blackheartMet; } - public FindIngredientObjective() - { - } - - public override object Message - { - get + public override object Message => + !BlackheartMet ? Step switch { if (!BlackheartMet) return Step switch @@ -310,21 +306,13 @@ namespace Server.Engines.Quests.Hag */ return 1055055; } - } + : 1055055; - public override int MaxProgress - { - get - { - IngredientInfo info = IngredientInfo.Get(Ingredient); - - return info.Quantity; - } - } + public override int MaxProgress => IngredientInfo.Get(Ingredient).Quantity; public Ingredient[] Ingredients{ get; private set; } - public Ingredient Ingredient => Ingredients[Ingredients.Length - 1]; + public Ingredient Ingredient => Ingredients[^1]; public int Step => Ingredients.Length; public bool BlackheartMet{ get; private set; } @@ -345,26 +333,14 @@ namespace Server.Engines.Quests.Hag } } - public override bool IgnoreYoungProtection(Mobile from) - { - if (Completed) - return false; - - IngredientInfo info = IngredientInfo.Get(Ingredient); - Type fromType = from.GetType(); - - for (int i = 0; i < info.Creatures.Length; i++) - if (fromType == info.Creatures[i]) - return true; - - return false; - } + public override bool IgnoreYoungProtection(Mobile from) => + !Completed && IngredientInfo.Get(Ingredient).Creatures.Any(t => from.GetType() == t); public override void OnKill(BaseCreature creature, Container corpse) { IngredientInfo info = IngredientInfo.Get(Ingredient); - for (int i = 0; i < info.Creatures.Length; i++) + if (info.Creatures.Any(type => creature.GetType() == type)) { Type type = info.Creatures[i]; @@ -375,8 +351,7 @@ namespace Server.Engines.Quests.Hag CurProgress++; - break; - } + CurProgress++; } } diff --git a/Projects/Scripts/Engines/Spawner/Spawner.cs b/Projects/Scripts/Engines/Spawner/Spawner.cs index e6c0d77e1..2f2326944 100644 --- a/Projects/Scripts/Engines/Spawner/Spawner.cs +++ b/Projects/Scripts/Engines/Spawner/Spawner.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Reflection; using Server.Commands; using Server.Items; @@ -22,26 +23,24 @@ namespace Server.Mobiles private InternalTimer m_Timer; private int m_WalkingRange = -1; -// [Constructible] + [Constructible(AccessLevel.Developer)] + public Spawner() : base(0x1f13) + { + InitSpawn(1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10), 0, 4); + } + public Spawner(int amount, int minDelay, int maxDelay, int team, int homeRange, string spawnedNames) : base(0x1f13) { InitSpawn(amount, TimeSpan.FromMinutes(minDelay), TimeSpan.FromMinutes(maxDelay), team, homeRange); AddEntry(spawnedNames, 100, amount, false); } -// [Constructible] public Spawner(string spawnedName) : base(0x1f13) { InitSpawn(1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10), 0, 4); AddEntry(spawnedName, 100, 1, false); } - [Constructible(AccessLevel.Developer)] - public Spawner() : base(0x1f13) - { - InitSpawn(1, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(10), 0, 4); - } - public Spawner(int amount, TimeSpan minDelay, TimeSpan maxDelay, int team, int homeRange, params string[] spawnedNames) : base(0x1f13) { @@ -71,9 +70,8 @@ namespace Server.Mobiles { m_Count = value; - if (m_Timer != null) - if (!IsFull && !m_Timer.Running || IsFull && m_Timer.Running) - DoTimer(); + if (m_Timer != null && IsFull == m_Timer.Running) + DoTimer(); InvalidateProperties(); } @@ -266,20 +264,16 @@ namespace Server.Mobiles { base.OnSingleClick(from); - if (m_Running) - LabelTo(from, "[Running]"); - else - LabelTo(from, "[Off]"); + LabelTo(from, m_Running ? "[Running]" : "[Off]"); } public void Start() { - if (!m_Running) - if (Entries.Count > 0) - { - m_Running = true; - DoTimer(); - } + if (!m_Running && Entries.Count > 0) + { + m_Running = true; + DoTimer(); + } } public void Stop() @@ -293,8 +287,7 @@ namespace Server.Mobiles public void Defrag() { - if (Entries == null) - Entries = new List(); + Entries ??= new List(); for (int i = 0; i < Entries.Count; ++i) Entries[i].Defrag(this); @@ -302,8 +295,6 @@ namespace Server.Mobiles public void OnTick() { -// DoTimer( m_Spawned.Count >= m_Count ); - if (m_Group) { Defrag(); @@ -314,19 +305,8 @@ namespace Server.Mobiles Respawn(); } else - { Spawn(); - } -/* - if ( m_Running && m_Timer != null ) - { - if ( m_Spawned.Count >= m_Count && m_Timer.Running ) - DoTimer( true ); - else if ( m_Spawned.Count < m_Count && !m_Timer.Running ) - DoTimer( false ); - } -*/ DoTimer(); } @@ -347,11 +327,7 @@ namespace Server.Mobiles if (Entries.Count <= 0 || IsFull) return; - int probsum = 0; - - for (int i = 0; i < Entries.Count; i++) - if (!Entries[i].IsFull) - probsum += Entries[i].SpawnedProbability; + int probsum = Entries.Where(t => !t.IsFull).Sum(t => t.SpawnedProbability); if (probsum <= 0) return; @@ -394,9 +370,7 @@ namespace Server.Mobiles } } else - { props = new string[0, 0]; - } return props; } @@ -461,13 +435,8 @@ namespace Server.Mobiles try { object o = null; - string[] paramargs; - string[] propargs; - if (string.IsNullOrEmpty(entry.Properties)) - propargs = new string[0]; - else - propargs = CommandSystem.Split(entry.Properties.Trim()); + string[] propargs = string.IsNullOrEmpty(entry.Properties) ? new string[0] : CommandSystem.Split(entry.Properties.Trim()); string[,] props = FormatProperties(propargs); @@ -479,10 +448,7 @@ namespace Server.Mobiles return false; } - if (string.IsNullOrEmpty(entry.Parameters)) - paramargs = new string[0]; - else - paramargs = entry.Parameters.Trim().Split(' '); + string[] paramargs = string.IsNullOrEmpty(entry.Parameters) ? new string[0] : entry.Parameters.Trim().Split(' '); ConstructorInfo[] ctors = type.GetConstructors(); @@ -648,21 +614,9 @@ namespace Server.Mobiles LandTile landTile = map.Tiles.GetLandTile(x, y); - if (landTile.Z == z && (TileData.LandTable[landTile.ID & TileData.MaxLandValue].Flags & TileFlag.Wet) != 0) - return true; - - StaticTile[] staticTiles = map.Tiles.GetStaticTiles(x, y, true); - - for (int i = 0; i < staticTiles.Length; ++i) - { - StaticTile staticTile = staticTiles[i]; - - if (staticTile.Z == z && - (TileData.ItemTable[staticTile.ID & TileData.MaxItemValue].Flags & TileFlag.Wet) != 0) - return true; - } - - return false; + return landTile.Z == z && (TileData.LandTable[landTile.ID & TileData.MaxLandValue].Flags & TileFlag.Wet) != 0 || + map.Tiles.GetStaticTiles(x, y, true).Any(staticTile => + staticTile.Z == z && (TileData.ItemTable[staticTile.ID & TileData.MaxItemValue].Flags & TileFlag.Wet) != 0); } public virtual Map GetSpawnMap() => Map; @@ -977,11 +931,7 @@ namespace Server.Mobiles public InternalTimer(Spawner spawner, TimeSpan delay) : base(delay) { - if (spawner.IsFull) - Priority = TimerPriority.FiveSeconds; - else - Priority = TimerPriority.OneSecond; - + Priority = spawner.IsFull ? TimerPriority.FiveSeconds : TimerPriority.OneSecond; m_Spawner = spawner; } @@ -1150,41 +1100,11 @@ namespace Server.Mobiles bool remove = false; if (e is Item item) - { - if (item.Deleted || item.RootParent is Mobile || item.IsLockedDown || item.IsSecure || - item.Spawner == null) - remove = true; - } + remove |= item.Deleted || item.RootParent is Mobile || item.IsLockedDown || item.IsSecure || item.Spawner == null; else if (e is Mobile m) - { - if (m.Deleted) - { - remove = true; - } - else if (m is BaseCreature c) - { - if (c.Controlled || c.IsStabled) - remove = true; -/* - else if ( c.Combatant == null && ( c.GetDistanceToSqrt( Location ) > (c.RangeHome * 4) ) ) - { - //m_Spawned[i].Delete(); - m_Spawned.RemoveAt( i ); - --i; - c.Delete(); - remove = true; - } -*/ - } - else if (m.Spawner == null) - { - remove = true; - } - } + remove |= m.Deleted || m.Spawner == null || m is BaseCreature c && (c.Controlled || c.IsStabled); else - { remove = true; - } if (remove) { diff --git a/Projects/Scripts/Engines/Spawner/SpawnerGump.cs b/Projects/Scripts/Engines/Spawner/SpawnerGump.cs index 7be5f298d..18852a81f 100644 --- a/Projects/Scripts/Engines/Spawner/SpawnerGump.cs +++ b/Projects/Scripts/Engines/Spawner/SpawnerGump.cs @@ -203,7 +203,7 @@ namespace Server.Mobiles spawner.Start(); } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (m_Spawner.Deleted) return; @@ -246,7 +246,7 @@ namespace Server.Mobiles } case 2: //Okay { - CreateArray(info, state.Mobile, m_Spawner); + CreateArray(info, sender.Mobile, m_Spawner); return; } case 3: @@ -261,7 +261,7 @@ namespace Server.Mobiles } case 5: { - CreateArray(info, state.Mobile, m_Spawner); + CreateArray(info, sender.Mobile, m_Spawner); break; } } @@ -282,15 +282,15 @@ namespace Server.Mobiles m_Spawner.RemoveSpawn(entryindex); } - CreateArray(info, state.Mobile, m_Spawner); + CreateArray(info, sender.Mobile, m_Spawner); break; } } if (m_Entry != null && m_Spawner.Entries?.Contains(m_Entry) == true) - state.Mobile.SendGump(new SpawnerGump(m_Spawner, m_Entry, m_Page)); + sender.Mobile.SendGump(new SpawnerGump(m_Spawner, m_Entry, m_Page)); else - state.Mobile.SendGump(new SpawnerGump(m_Spawner, null, m_Page)); + sender.Mobile.SendGump(new SpawnerGump(m_Spawner, null, m_Page)); } } } diff --git a/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/CharacterStatue.cs b/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/CharacterStatue.cs index 98650495c..840eb354f 100644 --- a/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/CharacterStatue.cs +++ b/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/CharacterStatue.cs @@ -185,7 +185,7 @@ namespace Server.Mobiles public void OnRequestedAnimation(Mobile from) { - from.Send(new UpdateStatueAnimation(this, 1, m_Animation, m_Frames)); + StatuePackets.SendUpdateStatueAnimation(from.NetState, Serial, 1, m_Animation, m_Frames); } public override void OnAosSingleClick(Mobile from) @@ -364,22 +364,14 @@ namespace Server.Mobiles { ProcessDelta(); - Packet p = null; - IPooledEnumerable eable = Map.GetClientsInRange(Location); foreach (NetState state in eable) { state.Mobile.ProcessDelta(); - - if (p == null) - p = Packet.Acquire(new UpdateStatueAnimation(this, 1, m_Animation, m_Frames)); - - state.Send(p); + StatuePackets.SendUpdateStatueAnimation(state, Serial, 1, m_Animation, m_Frames); } - Packet.Release(p); - eable.Free(); } } @@ -424,9 +416,8 @@ namespace Server.Mobiles { } - public override int LabelNumber - { - get + public override int LabelNumber => + (Statue?.StatueType ?? m_Type) switch { StatueType t = m_Type; @@ -448,13 +439,7 @@ namespace Server.Mobiles [CommandProperty(AccessLevel.GameMaster)] public StatueType StatueType { - get - { - if (Statue != null) - return Statue.StatueType; - - return m_Type; - } + get => Statue?.StatueType ?? m_Type; set => m_Type = value; } @@ -611,18 +596,11 @@ namespace Server.Mobiles from.SendGump(new CharacterStatueGump(m_Maker, statue, from)); } else if (result == AddonFitResult.Blocked) - { from.SendLocalizedMessage(500269); // You cannot build that there. - } else if (result == AddonFitResult.NotInHouse) - { from.SendLocalizedMessage( 1076192); // Statues can only be placed in houses where you are the owner or co-owner. - } - else if (result == AddonFitResult.DoorTooClose) - { - from.SendLocalizedMessage(500271); // You cannot build near the door. - } + else if (result == AddonFitResult.DoorTooClose) from.SendLocalizedMessage(500271); // You cannot build near the door. } else { @@ -630,15 +608,9 @@ namespace Server.Mobiles } } - public static AddonFitResult CouldFit(Point3D p, Map map, Mobile from, ref BaseHouse house) - { - if (!map.CanFit(p.X, p.Y, p.Z, 20, true)) - return AddonFitResult.Blocked; - if (!BaseAddon.CheckHouse(from, p, map, 20, ref house)) - return AddonFitResult.NotInHouse; - - return CheckDoors(p, 20, house); - } + public static AddonFitResult CouldFit(Point3D p, Map map, Mobile from, ref BaseHouse house) => + !map.CanFit(p.X, p.Y, p.Z, 20, true) ? AddonFitResult.Blocked : + !BaseAddon.CheckHouse(from, p, map, 20, ref house) ? AddonFitResult.NotInHouse : CheckDoors(p, 20, house); public static AddonFitResult CheckDoors(Point3D p, int height, BaseHouse house) { diff --git a/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/Gumps/CharacterStatueGump.cs b/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/Gumps/CharacterStatueGump.cs index 48e429d14..60459b340 100644 --- a/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/Gumps/CharacterStatueGump.cs +++ b/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/Gumps/CharacterStatueGump.cs @@ -66,9 +66,8 @@ namespace Server.Gumps } } - private int GetMaterialNumber(StatueType type, StatueMaterial material) - { - switch (material) + private int GetMaterialNumber(StatueType type, StatueMaterial material) => + material switch { case StatueMaterial.Antique: @@ -126,7 +125,7 @@ namespace Server.Gumps m_Maker?.Delete(); - m_Statue.Sculpt(state.Mobile); + m_Statue.Sculpt(sender.Mobile); } else if (info.ButtonID == (int)Buttons.PosePrev) { @@ -174,11 +173,11 @@ namespace Server.Gumps } else // Close { - sendGump = !m_Statue.Demolish(state.Mobile); + sendGump = !m_Statue.Demolish(sender.Mobile); } if (sendGump) - state.Mobile.SendGump(new CharacterStatueGump(m_Maker, m_Statue, m_Owner)); + sender.Mobile.SendGump(new CharacterStatueGump(m_Maker, m_Statue, m_Owner)); } private enum Buttons diff --git a/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/Packets.cs b/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/Packets.cs index b13fd47b9..af457b1d9 100644 --- a/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/Packets.cs +++ b/Projects/Scripts/Engines/VeteranRewards/Character Statue Maker/Packets.cs @@ -1,20 +1,25 @@ +using Server.Buffers; + namespace Server.Network { - public class UpdateStatueAnimation : Packet + public static class StatuePackets { - public UpdateStatueAnimation(Mobile m, int status, int animation, int frame) : base(0xBF, 17) + public static void SendUpdateStatueAnimation(NetState ns, Serial m, int status, int animation, int frame) { - m_Stream.Write((short)0x11); - m_Stream.Write((short)0x19); - m_Stream.Write((byte)0x5); - m_Stream.Write(m.Serial); - m_Stream.Write((byte)0); - m_Stream.Write((byte)0xFF); - m_Stream.Write((byte)status); - m_Stream.Write((byte)0); - m_Stream.Write((byte)animation); - m_Stream.Write((byte)0); - m_Stream.Write((byte)frame); + if (ns == null) + return; + + SpanWriter writer = new SpanWriter(stackalloc byte[17]); + writer.Write((byte)0xBF); // Extended Packet ID + writer.Write((short)17); // Dynamic Length + + writer.Write((short)0x19); + writer.Write((byte)0x5); + writer.Write(m); + writer.Write((short)0xFF); + writer.Write((byte)status); + writer.Write((short)animation); + writer.Write((short)frame); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Engines/VeteranRewards/RewardOptionGump.cs b/Projects/Scripts/Engines/VeteranRewards/RewardOptionGump.cs index 4bdd1b2c9..7c10fd811 100644 --- a/Projects/Scripts/Engines/VeteranRewards/RewardOptionGump.cs +++ b/Projects/Scripts/Engines/VeteranRewards/RewardOptionGump.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using Server.Network; namespace Server.Gumps @@ -51,17 +52,7 @@ namespace Server.Gumps m_Option.OnOptionSelected(sender.Mobile, info.ButtonID); } - private bool Contains(int chosen) - { - if (m_Options == null) - return false; - - foreach (RewardOption option in m_Options) - if (option.ID == chosen) - return true; - - return false; - } + private bool Contains(int chosen) => m_Options?.Any(option => option.ID == chosen) == true; } public class RewardOption diff --git a/Projects/Scripts/Engines/Virtues/Honor.cs b/Projects/Scripts/Engines/Virtues/Honor.cs index 576d0d42d..b84c10510 100644 --- a/Projects/Scripts/Engines/Virtues/Honor.cs +++ b/Projects/Scripts/Engines/Virtues/Honor.cs @@ -342,9 +342,9 @@ namespace Server targetFame / 100.0 * (m_HonorDamage / m_TotalDamage); //Initial honor gain is 100th of the monsters honor if (m_HonorDamage == m_TotalDamage && m_FirstHit == FirstHit.Granted) - dGain = dGain * 1.5; //honor gain is increased alot more if the combat was fully honorable + dGain *= 1.5; //honor gain is increased alot more if the combat was fully honorable else - dGain = dGain * 0.9; + dGain *= 0.9; int gain = Math.Min((int)dGain, 200); diff --git a/Projects/Scripts/Engines/Virtues/VirtueGump.cs b/Projects/Scripts/Engines/Virtues/VirtueGump.cs index 9f9780989..3338479cb 100644 --- a/Projects/Scripts/Engines/Virtues/VirtueGump.cs +++ b/Projects/Scripts/Engines/Virtues/VirtueGump.cs @@ -36,14 +36,14 @@ namespace Server AddPage(1); - Add(new InternalEntry(61, 71, 108, GetHueFor(0))); // Humility - Add(new InternalEntry(123, 46, 112, GetHueFor(4))); // Valor - Add(new InternalEntry(187, 70, 107, GetHueFor(5))); // Honor - Add(new InternalEntry(35, 135, 110, GetHueFor(1))); // Sacrifice - Add(new InternalEntry(211, 133, 105, GetHueFor(2))); // Compassion - Add(new InternalEntry(61, 195, 111, GetHueFor(3))); // Spiritulaity - Add(new InternalEntry(186, 195, 109, GetHueFor(6))); // Justice - Add(new InternalEntry(121, 221, 106, GetHueFor(7))); // Honesty + Add(new GumpImage(61, 71, 108, GetHueFor(0), "VirtueGumpItem")); // Humility + Add(new GumpImage(123, 46, 112, GetHueFor(4), "VirtueGumpItem")); // Valor + Add(new GumpImage(187, 70, 107, GetHueFor(5), "VirtueGumpItem")); // Honor + Add(new GumpImage(35, 135, 110, GetHueFor(1), "VirtueGumpItem")); // Sacrifice + Add(new GumpImage(211, 133, 105, GetHueFor(2), "VirtueGumpItem")); // Compassion + Add(new GumpImage(61, 195, 111, GetHueFor(3), "VirtueGumpItem")); // Spiritulaity + Add(new GumpImage(186, 195, 109, GetHueFor(6), "VirtueGumpItem")); // Justice + Add(new GumpImage(121, 221, 106, GetHueFor(7), "VirtueGumpItem")); // Honesty if (m_Beholder == m_Beheld) { @@ -147,7 +147,7 @@ namespace Server return m_Table[index * 3 + vl]; } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID == 1 && m_Beholder == m_Beheld) m_Beholder.SendGump(new VirtueStatusGump(m_Beholder)); diff --git a/Projects/Scripts/Engines/Virtues/VirtueInfoGump.cs b/Projects/Scripts/Engines/Virtues/VirtueInfoGump.cs index f642321a9..71aa4e4ab 100644 --- a/Projects/Scripts/Engines/Virtues/VirtueInfoGump.cs +++ b/Projects/Scripts/Engines/Virtues/VirtueInfoGump.cs @@ -79,7 +79,7 @@ namespace Server AddHtmlLocalized(83, 275, 400, 40, webPage == null ? 1052055 : 1052052); // This virtue is not yet defined. OR -click to learn more (opens webpage) } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { switch (info.ButtonID) { @@ -88,7 +88,7 @@ namespace Server m_Beholder.SendGump(new VirtueInfoGump(m_Beholder, m_Virtue, m_Desc, m_Page)); if (m_Page != null) - state.Send(new LaunchBrowser(m_Page)); //No message about web browser starting on OSI + Packets.SendLaunchBrowser(sender, m_Page); break; } case 2: diff --git a/Projects/Scripts/Engines/Virtues/VirtueStatusGump.cs b/Projects/Scripts/Engines/Virtues/VirtueStatusGump.cs index 911cc7774..f1de0b00e 100644 --- a/Projects/Scripts/Engines/Virtues/VirtueStatusGump.cs +++ b/Projects/Scripts/Engines/Virtues/VirtueStatusGump.cs @@ -47,7 +47,7 @@ namespace Server AddButton(280, 43, 4014, 4014, 9); } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { switch (info.ButtonID) { diff --git a/Projects/Scripts/Gumps/AdminGump.cs b/Projects/Scripts/Gumps/AdminGump.cs index fbc3db4b3..81deef6ad 100644 --- a/Projects/Scripts/Gumps/AdminGump.cs +++ b/Projects/Scripts/Gumps/AdminGump.cs @@ -16,7 +16,7 @@ namespace Server.Gumps { public enum AdminGumpPage { - Information_General, + Information_General = 0, Information_Perf, Administer, Clients, @@ -39,7 +39,8 @@ namespace Server.Gumps AccountDetails_Tags, AccountDetails_ChangePassword, AccountDetails_ChangeAccess, - FirewallInfo + FirewallInfo, + Invalid = -1 } public class AdminGump : Gump @@ -587,8 +588,7 @@ namespace Server.Gumps } case AdminGumpPage.Accounts: { - if (m_List == null) - m_List = new List(); + m_List ??= new List(); List rads = state as List; @@ -1182,11 +1182,10 @@ namespace Server.Gumps if (totalBytes > 1000000) return $"{(double)totalBytes / 1048576:F1} MB"; - if (totalBytes > 1000) - return $"{(double)totalBytes / 1024:F1} KB"; - - return $"{totalBytes} Bytes"; - } + public static string FormatByteAmount(long totalBytes) => + totalBytes > 1000000000 ? $"{(double)totalBytes / 1073741824:F1} GB" : + totalBytes > 1000000 ? $"{(double)totalBytes / 1048576:F1} MB" : + totalBytes > 1000 ? $"{(double)totalBytes / 1024:F1} KB" : $"{totalBytes} Bytes"; public static void Initialize() { @@ -1525,7 +1524,7 @@ namespace Server.Gumps { IPAddress[] ips = a.LoginIPs; - if (ips.Length != 0 && ip == ips[0] && AccountHandler.IPTable.ContainsKey(ips[0])) + if (ips.Length != 0 && ip.Equals(ips[0]) && AccountHandler.IPTable.ContainsKey(ips[0])) --AccountHandler.IPTable[ip]; List newList = new List(ips); @@ -1608,30 +1607,19 @@ namespace Server.Gumps { case 0: { - AdminGumpPage page; - - switch (index) + AdminGumpPage page = index switch { - case 0: - page = AdminGumpPage.Information_General; - break; - case 1: - page = AdminGumpPage.Administer; - break; - case 2: - page = AdminGumpPage.Clients; - break; - case 3: - page = AdminGumpPage.Accounts; - break; - case 4: - page = AdminGumpPage.Firewall; - break; - case 5: - page = AdminGumpPage.Information_Perf; - break; - default: return; - } + 0 => AdminGumpPage.Information_General, + 1 => AdminGumpPage.Administer, + 2 => AdminGumpPage.Clients, + 3 => AdminGumpPage.Accounts, + 4 => AdminGumpPage.Firewall, + 5 => AdminGumpPage.Information_Perf, + _ => AdminGumpPage.Invalid, + }; + + if (page == AdminGumpPage.Invalid) + return; from.SendGump(new AdminGump(from, page)); break; @@ -1951,12 +1939,7 @@ namespace Server.Gumps hasAccess = true; else for (int j = 0; !hasAccess && j < a.Length; ++j) - { - Mobile m = a[j]; - - if (m?.AccessLevel >= level) - hasAccess = true; - } + hasAccess |= a[j]?.AccessLevel >= level; if (!hasAccess) { @@ -2500,11 +2483,7 @@ namespace Server.Gumps } case 31: // View all inactive accounts { - List results = new List(); - - foreach (Account acct in Accounts.GetAccounts()) - if (acct.Inactive) - results.Add(acct); + List results = Accounts.GetAccounts().Cast().Where(acct => acct.Inactive).Cast().ToList(); if (results.Count == 1) from.SendGump(new AdminGump(from, AdminGumpPage.AccountDetails_Information, 0, null, @@ -2517,11 +2496,7 @@ namespace Server.Gumps } case 32: // View all banned accounts { - List results = new List(); - - foreach (Account acct in Accounts.GetAccounts()) - if (acct.Banned) - results.Add(acct); + List results = Accounts.GetAccounts().Cast().Where(acct => acct.Banned).Cast().ToList(); if (results.Count == 1) from.SendGump(new AdminGump(from, AdminGumpPage.AccountDetails_Information, 0, null, @@ -2552,8 +2527,7 @@ namespace Server.Gumps bool hasHouse = false; for (int i = 0; i < acct.Length && !hasHouse; ++i) - if (acct[i] != null && BaseHouse.HasHouse(acct[i])) - hasHouse = true; + hasHouse |= acct[i] != null && BaseHouse.HasHouse(acct[i]); if (!hasHouse) newRads.Add(acct); @@ -2972,8 +2946,7 @@ namespace Server.Gumps if (check.AccessLevel > accessLevel) accessLevel = check.AccessLevel; - if (check.NetState != null) - online = true; + online |= check.NetState != null; } } diff --git a/Projects/Scripts/Gumps/BaseConfirmGump.cs b/Projects/Scripts/Gumps/BaseConfirmGump.cs index eeb878c96..f0825c745 100644 --- a/Projects/Scripts/Gumps/BaseConfirmGump.cs +++ b/Projects/Scripts/Gumps/BaseConfirmGump.cs @@ -50,14 +50,14 @@ namespace Server.Gumps public virtual int LabelNumber // Are you sure you wish to select this? => 1074975; - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID == (int)Buttons.Confirm) { if (info.IsSwitched((int)Buttons.Break)) - Confirm(state.Mobile); + Confirm(sender.Mobile); else - Refuse(state.Mobile); + Refuse(sender.Mobile); } } diff --git a/Projects/Scripts/Gumps/CategorizedAddGump.cs b/Projects/Scripts/Gumps/CategorizedAddGump.cs index f3e49ed66..cd796494c 100644 --- a/Projects/Scripts/Gumps/CategorizedAddGump.cs +++ b/Projects/Scripts/Gumps/CategorizedAddGump.cs @@ -110,7 +110,7 @@ namespace Server.Gumps public override string Caption => Title; - public static CAGCategory Root => m_Root ?? (m_Root = Load("Data/objects.xml")); + public static CAGCategory Root => m_Root ??= Load("Data/objects.xml"); public override void OnClick(Mobile from, int page) { @@ -184,7 +184,8 @@ namespace Server.Gumps public static readonly int NextButtonID1 = PropsConfig.NextButtonID1; public static readonly int NextButtonID2 = PropsConfig.NextButtonID2; - private static bool PrevLabel = false, NextLabel = false; + private static bool PrevLabel = false; + private static bool NextLabel = false; private static readonly int PrevLabelOffsetX = PrevWidth + 1; private static readonly int PrevLabelOffsetY = 0; @@ -333,7 +334,7 @@ namespace Server.Gumps } } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { Mobile from = m_Owner; diff --git a/Projects/Scripts/Gumps/ClientGump.cs b/Projects/Scripts/Gumps/ClientGump.cs index 357851480..df05ab3b9 100644 --- a/Projects/Scripts/Gumps/ClientGump.cs +++ b/Projects/Scripts/Gumps/ClientGump.cs @@ -128,13 +128,13 @@ namespace Server.Gumps to.SendGump(new ClientGump(to, m_State, te == null ? "" : te.Text)); } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (m_State == null) return; Mobile focus = m_State.Mobile; - Mobile from = state.Mobile; + Mobile from = sender.Mobile; if (focus == null) { diff --git a/Projects/Scripts/Gumps/CommentsGump.cs b/Projects/Scripts/Gumps/CommentsGump.cs index f884de9b6..3c7928d89 100644 --- a/Projects/Scripts/Gumps/CommentsGump.cs +++ b/Projects/Scripts/Gumps/CommentsGump.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using Server.Accounting; using Server.Network; -using Server.Prompts; using Server.Targeting; namespace Server.Gumps @@ -78,12 +77,12 @@ namespace Server.Gumps from.SendGump(new CommentsGump((Account)m.Account)); } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID == 0x7F) { - state.Mobile.SendMessage("Enter the text for the account comment (or press [Esc] to cancel):"); - state.Mobile.Prompt = new CommentPrompt(m_Acct); + sender.Mobile.SendMessage("Enter the text for the account comment (or press [Esc] to cancel):"); + sender.Mobile.Prompt = new CommentPrompt(m_Acct); } } diff --git a/Projects/Scripts/Gumps/ConfirmHouseResize.cs b/Projects/Scripts/Gumps/ConfirmHouseResize.cs index c572e08e6..a3fc0fd20 100644 --- a/Projects/Scripts/Gumps/ConfirmHouseResize.cs +++ b/Projects/Scripts/Gumps/ConfirmHouseResize.cs @@ -46,7 +46,7 @@ namespace Server.Gumps AddHtmlLocalized(240, 250, 170, 20, 1011012, 0x7FFF); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID == 1 && !m_House.Deleted) { @@ -100,7 +100,7 @@ namespace Server.Gumps } else { - Item toGive = null; + Item toGive; if (m_House.IsAosRules) { diff --git a/Projects/Scripts/Gumps/Go/GoGump.cs b/Projects/Scripts/Gumps/Go/GoGump.cs index ec26774c9..3ef2fff1f 100644 --- a/Projects/Scripts/Gumps/Go/GoGump.cs +++ b/Projects/Scripts/Gumps/Go/GoGump.cs @@ -187,9 +187,9 @@ namespace Server.Gumps from.SendGump(new GoGump(0, from, tree, branch)); } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { - Mobile from = state.Mobile; + Mobile from = sender.Mobile; switch (info.ButtonID) { diff --git a/Projects/Scripts/Gumps/Guilds/DeclareFealtyGump.cs b/Projects/Scripts/Gumps/Guilds/DeclareFealtyGump.cs index b6ade1cfa..f20bc3225 100644 --- a/Projects/Scripts/Gumps/Guilds/DeclareFealtyGump.cs +++ b/Projects/Scripts/Gumps/Guilds/DeclareFealtyGump.cs @@ -20,7 +20,7 @@ namespace Server.Gumps AddHtmlLocalized(335, 400, 100, 35, 1011012); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadMember(m_Mobile, m_Guild)) return; @@ -38,7 +38,7 @@ namespace Server.Gumps Mobile m = m_List[index]; if (m?.Deleted == false) - state.Mobile.GuildFealty = m; + sender.Mobile.GuildFealty = m; } } } diff --git a/Projects/Scripts/Gumps/Guilds/GrantGuildTitleGump.cs b/Projects/Scripts/Gumps/Guilds/GrantGuildTitleGump.cs index 1af757d3b..c49d5123a 100644 --- a/Projects/Scripts/Gumps/Guilds/GrantGuildTitleGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GrantGuildTitleGump.cs @@ -20,7 +20,7 @@ namespace Server.Gumps AddHtmlLocalized(335, 400, 100, 35, 1011012); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadLeader(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildAbbrvPrompt.cs b/Projects/Scripts/Gumps/Guilds/GuildAbbrvPrompt.cs index f0f94a1c0..24c5cdda1 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildAbbrvPrompt.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildAbbrvPrompt.cs @@ -1,5 +1,4 @@ using Server.Guilds; -using Server.Prompts; namespace Server.Gumps { diff --git a/Projects/Scripts/Gumps/Guilds/GuildAcceptWarGump.cs b/Projects/Scripts/Gumps/Guilds/GuildAcceptWarGump.cs index 021acd651..61a26ce31 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildAcceptWarGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildAcceptWarGump.cs @@ -20,7 +20,7 @@ namespace Server.Gumps AddHtmlLocalized(335, 400, 100, 35, 1011012); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadLeader(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildAdminCandidatesGump.cs b/Projects/Scripts/Gumps/Guilds/GuildAdminCandidatesGump.cs index 018f390ef..402f4b0fc 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildAdminCandidatesGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildAdminCandidatesGump.cs @@ -21,7 +21,7 @@ namespace Server.Gumps AddHtmlLocalized(335, 400, 100, 35, 1013077); // Refuse } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadLeader(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildCandidatesGump.cs b/Projects/Scripts/Gumps/Guilds/GuildCandidatesGump.cs index 60ce45109..f5a032390 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildCandidatesGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildCandidatesGump.cs @@ -17,7 +17,7 @@ namespace Server.Gumps AddHtmlLocalized(55, 400, 300, 35, 1011120); // Return to the main menu. } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadMember(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildChangeTypeGump.cs b/Projects/Scripts/Gumps/Guilds/GuildChangeTypeGump.cs index c5eb72a9a..54d5df27b 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildChangeTypeGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildChangeTypeGump.cs @@ -41,7 +41,7 @@ namespace Server.Gumps AddHtmlLocalized(335, 360, 150, 30, 1011012); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (Guild.NewGuildSystem && !BaseGuildGump.IsLeader(m_Mobile, m_Guild) || !Guild.NewGuildSystem && GuildGump.BadLeader(m_Mobile, m_Guild)) diff --git a/Projects/Scripts/Gumps/Guilds/GuildCharterGump.cs b/Projects/Scripts/Gumps/Guilds/GuildCharterGump.cs index 16662a04f..a5fe1e55c 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildCharterGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildCharterGump.cs @@ -41,7 +41,7 @@ namespace Server.Gumps AddHtml(55, 220, 300, 20, website); } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadMember(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildCharterPrompt.cs b/Projects/Scripts/Gumps/Guilds/GuildCharterPrompt.cs index e3f265ba1..e158e8b60 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildCharterPrompt.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildCharterPrompt.cs @@ -1,5 +1,4 @@ using Server.Guilds; -using Server.Prompts; namespace Server.Gumps { diff --git a/Projects/Scripts/Gumps/Guilds/GuildDeclarePeaceGump.cs b/Projects/Scripts/Gumps/Guilds/GuildDeclarePeaceGump.cs index 00370e69d..fc18d39ac 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildDeclarePeaceGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildDeclarePeaceGump.cs @@ -20,7 +20,7 @@ namespace Server.Gumps AddHtmlLocalized(335, 400, 100, 35, 1011012); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadLeader(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildDeclareWarGump.cs b/Projects/Scripts/Gumps/Guilds/GuildDeclareWarGump.cs index c60b6096c..3bb53678a 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildDeclareWarGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildDeclareWarGump.cs @@ -23,7 +23,7 @@ namespace Server.Gumps AddHtmlLocalized(335, 400, 100, 35, 1011012); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadLeader(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildDeclareWarPrompt.cs b/Projects/Scripts/Gumps/Guilds/GuildDeclareWarPrompt.cs index 9b17dbaa0..8a18d46c6 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildDeclareWarPrompt.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildDeclareWarPrompt.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using Server.Guilds; -using Server.Prompts; namespace Server.Gumps { diff --git a/Projects/Scripts/Gumps/Guilds/GuildDismissGump.cs b/Projects/Scripts/Gumps/Guilds/GuildDismissGump.cs index f86a03209..5ff961a47 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildDismissGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildDismissGump.cs @@ -20,7 +20,7 @@ namespace Server.Gumps AddHtmlLocalized(335, 400, 100, 35, 1011012); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadLeader(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildNamePrompt.cs b/Projects/Scripts/Gumps/Guilds/GuildNamePrompt.cs index 292a23b72..59a5ddddd 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildNamePrompt.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildNamePrompt.cs @@ -1,5 +1,4 @@ using Server.Guilds; -using Server.Prompts; namespace Server.Gumps { diff --git a/Projects/Scripts/Gumps/Guilds/GuildRejectWarGump.cs b/Projects/Scripts/Gumps/Guilds/GuildRejectWarGump.cs index 16761e975..5a15e9c85 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildRejectWarGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildRejectWarGump.cs @@ -20,7 +20,7 @@ namespace Server.Gumps AddHtmlLocalized(335, 400, 100, 35, 1011012); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadLeader(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildRescindDeclarationGump.cs b/Projects/Scripts/Gumps/Guilds/GuildRescindDeclarationGump.cs index 2a648b5d4..866cb889e 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildRescindDeclarationGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildRescindDeclarationGump.cs @@ -20,7 +20,7 @@ namespace Server.Gumps AddHtmlLocalized(335, 400, 100, 35, 1011012); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadLeader(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildRosterGump.cs b/Projects/Scripts/Gumps/Guilds/GuildRosterGump.cs index 5588678a3..36aa21b66 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildRosterGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildRosterGump.cs @@ -17,7 +17,7 @@ namespace Server.Gumps AddHtmlLocalized(55, 400, 300, 35, 1011120); // Return to the main menu. } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadMember(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildTitlePrompt.cs b/Projects/Scripts/Gumps/Guilds/GuildTitlePrompt.cs index 35e4655d0..a098d9eeb 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildTitlePrompt.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildTitlePrompt.cs @@ -1,5 +1,4 @@ using Server.Guilds; -using Server.Prompts; namespace Server.Gumps { diff --git a/Projects/Scripts/Gumps/Guilds/GuildWarAdminGump.cs b/Projects/Scripts/Gumps/Guilds/GuildWarAdminGump.cs index 64d284013..9b0dcba48 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildWarAdminGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildWarAdminGump.cs @@ -63,7 +63,7 @@ namespace Server.Gumps AddHtmlLocalized(55, 400, 400, 35, 1011104); // Return to the previous menu. } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadLeader(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildWarGump.cs b/Projects/Scripts/Gumps/Guilds/GuildWarGump.cs index d2304dc45..a56f1f1aa 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildWarGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildWarGump.cs @@ -86,7 +86,7 @@ namespace Server.Gumps } } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadMember(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/GuildWebsitePrompt.cs b/Projects/Scripts/Gumps/Guilds/GuildWebsitePrompt.cs index 16aae7a12..487901fc9 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildWebsitePrompt.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildWebsitePrompt.cs @@ -1,5 +1,4 @@ using Server.Guilds; -using Server.Prompts; namespace Server.Gumps { diff --git a/Projects/Scripts/Gumps/Guilds/GuildmasterGump.cs b/Projects/Scripts/Gumps/Guilds/GuildmasterGump.cs index 29a7be63a..ff183da60 100644 --- a/Projects/Scripts/Gumps/Guilds/GuildmasterGump.cs +++ b/Projects/Scripts/Gumps/Guilds/GuildmasterGump.cs @@ -82,7 +82,7 @@ namespace Server.Gumps AddHtmlLocalized(335, 360, 100, 30, 1011441); // EXIT } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (GuildGump.BadLeader(m_Mobile, m_Guild)) return; diff --git a/Projects/Scripts/Gumps/Guilds/New Guild System/BaseGuildGump.cs b/Projects/Scripts/Gumps/Guilds/New Guild System/BaseGuildGump.cs index bab0308bf..408630817 100644 --- a/Projects/Scripts/Gumps/Guilds/New Guild System/BaseGuildGump.cs +++ b/Projects/Scripts/Gumps/Guilds/New Guild System/BaseGuildGump.cs @@ -1,3 +1,4 @@ +using System.Linq; using Server.Gumps; using Server.Misc; using Server.Mobiles; @@ -40,9 +41,7 @@ namespace Server.Guilds public override void OnResponse(NetState sender, RelayInfo info) { - PlayerMobile pm = sender.Mobile as PlayerMobile; - - if (!IsMember(pm, guild)) + if (!(sender.Mobile is PlayerMobile pm &&IsMember(pm, guild))) return; switch (info.ButtonID) @@ -85,30 +84,12 @@ namespace Server.Guilds s = s.ToLower(); - for (int i = 0; i < s.Length; ++i) - { - char c = s[i]; - - if ((c < 'a' || c > 'z') && (c < '0' || c > '9')) - { - bool except = false; - - for (int j = 0; !except && j < exceptions.Length; j++) - if (c == exceptions[j]) - except = true; - - if (!except) - return false; - } - } + if (s.Any(c => (c < 'a' || c > 'z') && (c < '0' || c > '9') && exceptions.All(exception => exception != c))) + return false; string[] disallowed = ProfanityProtection.Disallowed; - for (int i = 0; i < disallowed.Length; i++) - if (s.IndexOf(disallowed[i]) != -1) - return false; - - return true; + return disallowed.All(t => s.IndexOf(t) == -1); } public void AddHtmlText(int x, int y, int width, int height, TextDefinition text, bool back, bool scroll) diff --git a/Projects/Scripts/Gumps/Guilds/New Guild System/OtherGuildInfo.cs b/Projects/Scripts/Gumps/Guilds/New Guild System/OtherGuildInfo.cs index 6ae8e735d..1bea09ecc 100644 --- a/Projects/Scripts/Gumps/Guilds/New Guild System/OtherGuildInfo.cs +++ b/Projects/Scripts/Gumps/Guilds/New Guild System/OtherGuildInfo.cs @@ -108,9 +108,7 @@ namespace Server.Guilds if (PendingWar) { if (war.WarRequester) - { number = 1063027; // You have challenged this guild to war! - } else { number = 1062969; // This guild has challenged you to war! @@ -211,9 +209,7 @@ namespace Server.Guilds if (war?.WarRequester == false && activeWar == null) { if (!playerRank.GetFlag(RankFlags.ControlWarStatus)) - { pm.SendLocalizedMessage(1063440); // You don't have permission to negotiate wars. - } else if (alliance != null && alliance.Leader != guild) { pm.SendLocalizedMessage(1063239, @@ -276,9 +272,7 @@ namespace Server.Guilds if (war?.WarRequester == false && activeWar == null) { if (!playerRank.GetFlag(RankFlags.ControlWarStatus)) - { pm.SendLocalizedMessage(1063440); // You don't have permission to negotiate wars. - } else if (alliance != null && alliance.Leader != guild) { pm.SendLocalizedMessage(1063239, @@ -287,9 +281,7 @@ namespace Server.Guilds alliance.Leader.Name); // You need to negotiate via ~1_val~ instead. } else - { pm.SendGump(new WarDeclarationGump(pm, guild, otherGuild)); - } } break; @@ -299,9 +291,7 @@ namespace Server.Guilds if (war != null) { if (!playerRank.GetFlag(RankFlags.ControlWarStatus)) - { pm.SendLocalizedMessage(1063440); // You don't have permission to negotiate wars. - } else if (alliance != null && alliance.Leader != guild) { pm.SendLocalizedMessage(1063239, @@ -324,9 +314,7 @@ namespace Server.Guilds case 8: //Surrender { if (!playerRank.GetFlag(RankFlags.ControlWarStatus)) - { pm.SendLocalizedMessage(1063440); // You don't have permission to negotiate wars. - } else if (alliance != null && alliance.Leader != guild) { pm.SendLocalizedMessage(1063239, @@ -384,9 +372,7 @@ namespace Server.Guilds if (war == null && activeWar == null) { if (!playerRank.GetFlag(RankFlags.ControlWarStatus)) - { pm.SendLocalizedMessage(1063440); // You don't have permission to negotiate wars. - } else if (alliance != null && alliance.Leader != guild) { pm.SendLocalizedMessage(1063239, @@ -402,9 +388,7 @@ namespace Server.Guilds otherAlliance.Leader.Name); // You need to negotiate via ~1_val~ instead. } else - { pm.SendGump(new WarDeclarationGump(pm, guild, m_Other)); - } } break; @@ -419,14 +403,10 @@ namespace Server.Guilds if (alliance == null) { if (!playerRank.GetFlag(RankFlags.AllianceControl)) - { pm.SendLocalizedMessage(1070747); // You don't have permission to create an alliance. - } else if (Faction.Find(guild.Leader) != Faction.Find(m_Other.Leader)) - { pm.SendLocalizedMessage( 1070758); // You cannot propose an alliance to a guild with a different faction allegiance. - } else if (otherAlliance != null) { if (otherAlliance.IsPendingMember(m_Other)) @@ -436,13 +416,9 @@ namespace Server.Guilds pm.SendLocalizedMessage(1063426, m_Other.Name); // ~1_val~ already belongs to an alliance. } else if (m_Other.AcceptedWars.Count > 0 || m_Other.PendingWars.Count > 0) - { pm.SendLocalizedMessage(1063427, m_Other.Name); // ~1_val~ is currently involved in a guild war. - } else if (guild.AcceptedWars.Count > 0 || guild.PendingWars.Count > 0) - { pm.SendLocalizedMessage(1063427, guild.Name); // ~1_val~ is currently involved in a guild war. - } else { pm.SendLocalizedMessage(1063439); // Enter a name for the new alliance: @@ -457,14 +433,10 @@ namespace Server.Guilds else { if (!playerRank.GetFlag(RankFlags.AllianceControl)) - { pm.SendLocalizedMessage(1063436); // You don't have permission to negotiate an alliance. - } else if (alliance.Leader != guild) - { pm.SendLocalizedMessage(1063239, $"{guild.Name}\t{alliance.Name}"); // ~1_val~ is not the leader of the ~2_val~ alliance. - } else if (otherAlliance != null) { if (otherAlliance.IsPendingMember(m_Other)) @@ -474,23 +446,15 @@ namespace Server.Guilds pm.SendLocalizedMessage(1063426, m_Other.Name); // ~1_val~ already belongs to an alliance. } else if (alliance.IsPendingMember(guild)) - { pm.SendLocalizedMessage(1063416, guild.Name); // ~1_val~ is currently considering another alliance proposal. - } else if (m_Other.AcceptedWars.Count > 0 || m_Other.PendingWars.Count > 0) - { pm.SendLocalizedMessage(1063427, m_Other.Name); // ~1_val~ is currently involved in a guild war. - } else if (guild.AcceptedWars.Count > 0 || guild.PendingWars.Count > 0) - { pm.SendLocalizedMessage(1063427, guild.Name); // ~1_val~ is currently involved in a guild war. - } else if (Faction.Find(guild.Leader) != Faction.Find(m_Other.Leader)) - { pm.SendLocalizedMessage( 1070758); // You cannot propose an alliance to a guild with a different faction allegiance. - } else { pm.SendLocalizedMessage(1070750, @@ -517,9 +481,7 @@ namespace Server.Guilds case 11: //Leave Alliance { if (!playerRank.GetFlag(RankFlags.AllianceControl)) - { pm.SendLocalizedMessage(1063436); // You don't have permission to negotiate an alliance. - } else if (alliance?.IsMember(guild) == true) { guild.Alliance = null; //Calls alliance.Removeguild @@ -535,14 +497,10 @@ namespace Server.Guilds case 12: //Remove Guild from alliance { if (!playerRank.GetFlag(RankFlags.AllianceControl)) - { pm.SendLocalizedMessage(1063436); // You don't have permission to negotiate an alliance. - } else if (alliance != null && alliance.Leader != guild) - { pm.SendLocalizedMessage(1063239, $"{guild.Name}\t{alliance.Name}"); // ~1_val~ is not the leader of the ~2_val~ alliance. - } else if (alliance?.IsMember(guild) == true && alliance.IsMember(m_Other)) { m_Other.Alliance = null; @@ -557,14 +515,10 @@ namespace Server.Guilds case 13: //Promote to Alliance leader { if (!playerRank.GetFlag(RankFlags.AllianceControl)) - { pm.SendLocalizedMessage(1063436); // You don't have permission to negotiate an alliance. - } else if (alliance != null && alliance.Leader != guild) - { pm.SendLocalizedMessage(1063239, $"{guild.Name}\t{alliance.Name}"); // ~1_val~ is not the leader of the ~2_val~ alliance. - } else if (alliance?.IsMember(guild) == true && alliance.IsMember(m_Other)) { pm.SendLocalizedMessage(1063434, @@ -578,9 +532,7 @@ namespace Server.Guilds case 14: //Withdraw Request { if (!playerRank.GetFlag(RankFlags.AllianceControl)) - { pm.SendLocalizedMessage(1063436); // You don't have permission to negotiate an alliance. - } else if (alliance != null && alliance.Leader == guild && alliance.IsPendingMember(m_Other)) { m_Other.Alliance = null; @@ -592,9 +544,7 @@ namespace Server.Guilds case 15: //Deny Alliance Request { if (!playerRank.GetFlag(RankFlags.AllianceControl)) - { pm.SendLocalizedMessage(1063436); // You don't have permission to negotiate an alliance. - } else if (alliance != null && otherAlliance != null && alliance.Leader == m_Other && otherAlliance.IsPendingMember(guild)) { @@ -609,9 +559,7 @@ namespace Server.Guilds case 16: //Accept Alliance Request { if (!playerRank.GetFlag(RankFlags.AllianceControl)) - { pm.SendLocalizedMessage(1063436); // You don't have permission to negotiate an alliance. - } else if (otherAlliance != null && otherAlliance.Leader == m_Other && otherAlliance.IsPendingMember(guild)) { @@ -640,20 +588,15 @@ namespace Server.Guilds if (!IsMember(from, guild) || alliance != null) return; - RankDefinition playerRank = pm.GuildRank; if (!playerRank.GetFlag(RankFlags.AllianceControl)) - { pm.SendLocalizedMessage(1070747); // You don't have permission to create an alliance. - } else if (Faction.Find(guild.Leader) != Faction.Find(m_Other.Leader)) - { //Notes about this: OSI only cares/checks when proposing, you can change your faction all you want later. pm.SendLocalizedMessage( 1070758); // You cannot propose an alliance to a guild with a different faction allegiance. - } else if (otherAlliance != null) { if (otherAlliance.IsPendingMember(m_Other)) @@ -663,30 +606,20 @@ namespace Server.Guilds pm.SendLocalizedMessage(1063426, m_Other.Name); // ~1_val~ already belongs to an alliance. } else if (m_Other.AcceptedWars.Count > 0 || m_Other.PendingWars.Count > 0) - { pm.SendLocalizedMessage(1063427, m_Other.Name); // ~1_val~ is currently involved in a guild war. - } else if (guild.AcceptedWars.Count > 0 || guild.PendingWars.Count > 0) - { pm.SendLocalizedMessage(1063427, guild.Name); // ~1_val~ is currently involved in a guild war. - } else { string name = Utility.FixHtml(text.Trim()); if (!CheckProfanity(name)) - { pm.SendLocalizedMessage(1070886); // That alliance name is not allowed. - } else if (name.Length > Guild.NameLimit) - { pm.SendLocalizedMessage(1070887, Guild.NameLimit.ToString()); // An alliance name cannot exceed ~1_val~ characters in length. - } else if (AllianceInfo.Alliances.ContainsKey(name.ToLower())) - { pm.SendLocalizedMessage(1063428); // That alliance name is not available. - } else { pm.SendLocalizedMessage(1070750, diff --git a/Projects/Scripts/Gumps/HouseDemolishGump.cs b/Projects/Scripts/Gumps/HouseDemolishGump.cs index 1ec189cff..5a2e11f5a 100644 --- a/Projects/Scripts/Gumps/HouseDemolishGump.cs +++ b/Projects/Scripts/Gumps/HouseDemolishGump.cs @@ -1,4 +1,3 @@ -using Server.Accounting; using Server.Guilds; using Server.Items; using Server.Multis; @@ -32,13 +31,14 @@ namespace Server.Gumps AddImageTiled(10, 40, 400, 200, 2624); AddAlphaRegion(10, 40, 400, 200); - AddHtmlLocalized(10, 40, 400, 200, 1061795, 32512, false, true); /* You are about to demolish your house. - * You will be refunded the house's value directly to your bank box. - * All items in the house will remain behind and can be freely picked up by anyone. - * Once the house is demolished, anyone can attempt to place a new house on the vacant land. - * This action will not un-condemn any other houses on your account, nor will it end your 7-day waiting period (if it applies to you). - * Are you sure you wish to continue? - */ + AddHtmlLocalized(10, 40, 400, 200, 1061795, 32512, false, true); + /* You are about to demolish your house. + * You will be refunded the house's value directly to your bank box. + * All items in the house will remain behind and can be freely picked up by anyone. + * Once the house is demolished, anyone can attempt to place a new house on the vacant land. + * This action will not un-condemn any other houses on your account, nor will it end your 7-day waiting period (if it applies to you). + * Are you sure you wish to continue? + */ AddImageTiled(10, 250, 400, 20, 2624); AddAlphaRegion(10, 250, 400, 20); @@ -50,7 +50,7 @@ namespace Server.Gumps AddHtmlLocalized(240, 250, 170, 20, 1011012, 32767); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID == 1 && !m_House.Deleted) { diff --git a/Projects/Scripts/Gumps/HouseGump.cs b/Projects/Scripts/Gumps/HouseGump.cs index c3a65e70a..c940627bd 100644 --- a/Projects/Scripts/Gumps/HouseGump.cs +++ b/Projects/Scripts/Gumps/HouseGump.cs @@ -54,12 +54,12 @@ namespace Server.Gumps } } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (m_House.Deleted) return; - Mobile from = state.Mobile; + Mobile from = sender.Mobile; from.SendGump(new HouseGump(from, m_House)); } @@ -125,12 +125,12 @@ namespace Server.Gumps } } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (m_House.Deleted) return; - Mobile from = state.Mobile; + Mobile from = sender.Mobile; if (m_List != null && info.ButtonID == 1) // Remove now { diff --git a/Projects/Scripts/Gumps/HouseGumpAOS.cs b/Projects/Scripts/Gumps/HouseGumpAOS.cs index a29c9454e..22800fd7f 100644 --- a/Projects/Scripts/Gumps/HouseGumpAOS.cs +++ b/Projects/Scripts/Gumps/HouseGumpAOS.cs @@ -672,92 +672,92 @@ namespace Server.Gumps if (e == null) return; - int cost = e.Cost - house.Price; + int cost = e.Cost - house.Price; - if (cost > 0) + if (cost > 0) + { + if (Banker.Withdraw(from, cost)) { - if (Banker.Withdraw(from, cost)) - { - from.SendLocalizedMessage(1060398, - cost.ToString()); // ~1_AMOUNT~ gold has been withdrawn from your bank box. - } - else - { - from.SendLocalizedMessage( - 1061624); // You do not have enough funds in your bank to cover the difference between your old house and your new one. - return; - } + from.SendLocalizedMessage(1060398, + cost.ToString()); // ~1_AMOUNT~ gold has been withdrawn from your bank box. } - else if (cost < 0) + else { - if (Banker.Deposit(from, -cost)) - from.SendLocalizedMessage(1060397, - (-cost).ToString()); // ~1_AMOUNT~ gold has been deposited into your bank box. - else - return; - } - - BaseHouse newHouse = e.ConstructHouse(from); - - if (newHouse != null) - { - newHouse.Price = e.Cost; - - house.MoveAllToCrate(); - - newHouse.Friends = new List(house.Friends); - newHouse.CoOwners = new List(house.CoOwners); - newHouse.Bans = new List(house.Bans); - newHouse.Access = new List(house.Access); - newHouse.BuiltOn = house.BuiltOn; - newHouse.LastTraded = house.LastTraded; - newHouse.Public = house.Public; - - newHouse.VendorInventories.AddRange(house.VendorInventories); - house.VendorInventories.Clear(); - - foreach (VendorInventory inventory in newHouse.VendorInventories) inventory.House = newHouse; - - newHouse.InternalizedVendors.AddRange(house.InternalizedVendors); - house.InternalizedVendors.Clear(); - - foreach (Mobile mobile in newHouse.InternalizedVendors) - if (mobile is PlayerVendor vendor) - vendor.House = newHouse; - else if (mobile is PlayerBarkeeper barkeeper) - barkeeper.House = newHouse; - - if (house.MovingCrate != null) - { - newHouse.MovingCrate = house.MovingCrate; - newHouse.MovingCrate.House = newHouse; - house.MovingCrate = null; - } - - List items = house.GetItems(); - List mobiles = house.GetMobiles(); - - newHouse.MoveToWorld( - new Point3D(house.X + house.ConvertOffsetX, house.Y + house.ConvertOffsetY, - house.Z + house.ConvertOffsetZ), house.Map); - house.Delete(); - - foreach (Item item in items) item.Location = newHouse.BanLocation; - - foreach (Mobile mobile in mobiles) mobile.Location = newHouse.BanLocation; - - /* You have successfully replaced your original house with a new house. - * The value of the replaced house has been deposited into your bank box. - * All of the items in your original house have been relocated to a Moving Crate in the new house. - * Any deed-based house add-ons have been converted back into deeds. - * Vendors and barkeeps in the house, if any, have been stored in the Moving Crate as well. - * Use the Get Vendor context-sensitive menu option on your character to retrieve them. - * These containers can be used to re-create the vendor in a new location. - * Any barkeepers have been converted into deeds. - */ - from.SendGump(new NoticeGump(1060637, 30720, 1060012, 32512, 420, 280)); + from.SendLocalizedMessage( + 1061624); // You do not have enough funds in your bank to cover the difference between your old house and your new one. return; } + } + else if (cost < 0) + { + if (Banker.Deposit(from, -cost)) + from.SendLocalizedMessage(1060397, + (-cost).ToString()); // ~1_AMOUNT~ gold has been deposited into your bank box. + else + return; + } + + BaseHouse newHouse = e.ConstructHouse(from); + + if (newHouse != null) + { + newHouse.Price = e.Cost; + + house.MoveAllToCrate(); + + newHouse.Friends = new List(house.Friends); + newHouse.CoOwners = new List(house.CoOwners); + newHouse.Bans = new List(house.Bans); + newHouse.Access = new List(house.Access); + newHouse.BuiltOn = house.BuiltOn; + newHouse.LastTraded = house.LastTraded; + newHouse.Public = house.Public; + + newHouse.VendorInventories.AddRange(house.VendorInventories); + house.VendorInventories.Clear(); + + foreach (VendorInventory inventory in newHouse.VendorInventories) inventory.House = newHouse; + + newHouse.InternalizedVendors.AddRange(house.InternalizedVendors); + house.InternalizedVendors.Clear(); + + foreach (Mobile mobile in newHouse.InternalizedVendors) + if (mobile is PlayerVendor vendor) + vendor.House = newHouse; + else if (mobile is PlayerBarkeeper barkeeper) + barkeeper.House = newHouse; + + if (house.MovingCrate != null) + { + newHouse.MovingCrate = house.MovingCrate; + newHouse.MovingCrate.House = newHouse; + house.MovingCrate = null; + } + + List items = house.GetItems(); + List mobiles = house.GetMobiles(); + + newHouse.MoveToWorld( + new Point3D(house.X + house.ConvertOffsetX, house.Y + house.ConvertOffsetY, + house.Z + house.ConvertOffsetZ), house.Map); + house.Delete(); + + foreach (Item item in items) item.Location = newHouse.BanLocation; + + foreach (Mobile mobile in mobiles) mobile.Location = newHouse.BanLocation; + + /* You have successfully replaced your original house with a new house. + * The value of the replaced house has been deposited into your bank box. + * All of the items in your original house have been relocated to a Moving Crate in the new house. + * Any deed-based house add-ons have been converted back into deeds. + * Vendors and barkeeps in the house, if any, have been stored in the Moving Crate as well. + * Use the Get Vendor context-sensitive menu option on your character to retrieve them. + * These containers can be used to re-create the vendor in a new location. + * Any barkeepers have been converted into deeds. + */ + from.SendGump(new NoticeGump(1060637, 30720, 1060012, 32512, 420, 280)); + return; + } } from.SendGump(new HouseGumpAOS(HouseGumpPageAOS.Security, from, house)); diff --git a/Projects/Scripts/Gumps/HouseTransferGump.cs b/Projects/Scripts/Gumps/HouseTransferGump.cs index fc3926804..4dce5b90d 100644 --- a/Projects/Scripts/Gumps/HouseTransferGump.cs +++ b/Projects/Scripts/Gumps/HouseTransferGump.cs @@ -53,7 +53,7 @@ namespace Server.Gumps AddHtmlLocalized(240, 250, 170, 20, 1011012, 32767); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID == 1 && !m_House.Deleted) m_House.EndConfirmTransfer(m_From, m_To); diff --git a/Projects/Scripts/Gumps/PetResurrectGump.cs b/Projects/Scripts/Gumps/PetResurrectGump.cs index 494505e9e..87e53b6df 100644 --- a/Projects/Scripts/Gumps/PetResurrectGump.cs +++ b/Projects/Scripts/Gumps/PetResurrectGump.cs @@ -33,12 +33,12 @@ namespace Server.Gumps AddButton(110, 105, 0x819, 0x818, 0x2); // Cancel } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (m_Pet.Deleted || !m_Pet.IsBonded || !m_Pet.IsDeadPet) return; - Mobile from = state.Mobile; + Mobile from = sender.Mobile; if (info.ButtonID == 1) { diff --git a/Projects/Scripts/Gumps/PlayerVendorGumps.cs b/Projects/Scripts/Gumps/PlayerVendorGumps.cs index 93c2e375b..86ce1c962 100644 --- a/Projects/Scripts/Gumps/PlayerVendorGumps.cs +++ b/Projects/Scripts/Gumps/PlayerVendorGumps.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Reflection; -using Server.HuePickers; using Server.Items; using Server.Mobiles; using Server.Network; @@ -37,9 +36,9 @@ namespace Server.Gumps AddHtmlLocalized(152, 130, 100, 24, 1011036); // OKAY } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { - Mobile from = state.Mobile; + Mobile from = sender.Mobile; if (!m_Vendor.CanInteractWith(from, false)) return; @@ -135,9 +134,9 @@ namespace Server.Gumps AddLabel(300, 48, 0, ((int)(days / 12.0)).ToString()); } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { - Mobile from = state.Mobile; + Mobile from = sender.Mobile; if (!m_Vendor.CanInteractWith(from, true)) return; @@ -476,12 +475,12 @@ namespace Server.Gumps } } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (m_Vendor.Deleted) return; - Mobile from = state.Mobile; + Mobile from = sender.Mobile; if (m_Vendor is PlayerVendor vendor && !vendor.CanInteractWith(from, true)) return; @@ -581,11 +580,11 @@ namespace Server.Gumps if (category.Layer == Layer.Hair) { - new PVHairHuePicker(false, m_Vendor, from).SendTo(state); + new PVHairHuePicker(false, m_Vendor, from).SendTo(sender); } else if (category.Layer == Layer.FacialHair) { - new PVHairHuePicker(true, m_Vendor, from).SendTo(state); + new PVHairHuePicker(true, m_Vendor, from).SendTo(sender); } else { @@ -604,7 +603,7 @@ namespace Server.Gumps } if (item != null) - new PVHuePicker(item, m_Vendor, from).SendTo(state); + new PVHuePicker(item, m_Vendor, from).SendTo(sender); } } } diff --git a/Projects/Scripts/Gumps/PolymorphGump.cs b/Projects/Scripts/Gumps/PolymorphGump.cs index 4d6717b53..11a2e88d8 100644 --- a/Projects/Scripts/Gumps/PolymorphGump.cs +++ b/Projects/Scripts/Gumps/PolymorphGump.cs @@ -120,7 +120,7 @@ namespace Server.Gumps } } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID == 1 && info.Switches.Length > 0) { diff --git a/Projects/Scripts/Gumps/Props/PropsGump.cs b/Projects/Scripts/Gumps/Props/PropsGump.cs index 57b9acb48..e0f2baaf5 100644 --- a/Projects/Scripts/Gumps/Props/PropsGump.cs +++ b/Projects/Scripts/Gumps/Props/PropsGump.cs @@ -153,9 +153,7 @@ namespace Server.Gumps if (parent != null) { - if (m_Stack == null) - m_Stack = new Stack(); - + m_Stack ??= new Stack(); m_Stack.Push(parent); } @@ -281,9 +279,9 @@ namespace Server.Gumps } } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { - Mobile from = state.Mobile; + Mobile from = sender.Mobile; if (!BaseCommand.IsAccessible(from, m_Object)) { diff --git a/Projects/Scripts/Gumps/Props/SetBodyGump.cs b/Projects/Scripts/Gumps/Props/SetBodyGump.cs index 43f1ee237..dedc3082a 100644 --- a/Projects/Scripts/Gumps/Props/SetBodyGump.cs +++ b/Projects/Scripts/Gumps/Props/SetBodyGump.cs @@ -127,7 +127,6 @@ namespace Server.Gumps switch (index) { default: - case 0: type = ModelBodyType.Monsters; list = m_Monster; break; @@ -204,24 +203,17 @@ namespace Server.Gumps if (((Body)bodyID).IsEmpty) continue; - List list; - - switch (oldEntry.BodyType) + List list = oldEntry.BodyType switch { - default: continue; - case ModelBodyType.Monsters: - list = m_Monster; - break; - case ModelBodyType.Animals: - list = m_Animal; - break; - case ModelBodyType.Sea: - list = m_Sea; - break; - case ModelBodyType.Human: - list = m_Human; - break; - } + ModelBodyType.Monsters => m_Monster, + ModelBodyType.Animals => m_Animal, + ModelBodyType.Sea => m_Sea, + ModelBodyType.Human => m_Human, + _ => null + }; + + if (list == null) + return; int itemID = ShrinkTable.Lookup(bodyID, -1); @@ -287,7 +279,7 @@ namespace Server.Gumps int v = Name.CompareTo(comp.Name); if (v == 0) - Body.CompareTo(comp.Body); + v = Body.CompareTo(comp.Body); return v; } diff --git a/Projects/Scripts/Gumps/Props/SetGump.cs b/Projects/Scripts/Gumps/Props/SetGump.cs index 918eab063..4d0b11904 100644 --- a/Projects/Scripts/Gumps/Props/SetGump.cs +++ b/Projects/Scripts/Gumps/Props/SetGump.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Reflection; using Server.Commands; -using Server.HuePickers; using Server.Network; namespace Server.Gumps diff --git a/Projects/Scripts/Gumps/Props/SetObjectGump.cs b/Projects/Scripts/Gumps/Props/SetObjectGump.cs index 30d79a680..ef3895bbd 100644 --- a/Projects/Scripts/Gumps/Props/SetObjectGump.cs +++ b/Projects/Scripts/Gumps/Props/SetObjectGump.cs @@ -4,7 +4,6 @@ using System.Reflection; using Server.Commands; using Server.Commands.Generic; using Server.Network; -using Server.Prompts; namespace Server.Gumps { diff --git a/Projects/Scripts/Gumps/RunebookGump.cs b/Projects/Scripts/Gumps/RunebookGump.cs index 845ed5628..9f259ff9c 100644 --- a/Projects/Scripts/Gumps/RunebookGump.cs +++ b/Projects/Scripts/Gumps/RunebookGump.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using Server.Items; using Server.Multis; using Server.Network; -using Server.Prompts; using Server.Spells.Chivalry; using Server.Spells.Fourth; using Server.Spells.Seventh; @@ -203,9 +202,9 @@ namespace Server.Gumps public static bool HasSpell(Mobile from, int spellID) => Spellbook.Find(from, spellID)?.HasSpell(spellID) == true; - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { - Mobile from = state.Mobile; + Mobile from = sender.Mobile; if (Book.Deleted || !from.InRange(Book.GetWorldLocation(), Core.ML ? 3 : 1) || !DesignContext.Check(from)) { diff --git a/Projects/Scripts/Gumps/SetSecureLevelGump.cs b/Projects/Scripts/Gumps/SetSecureLevelGump.cs index 149491e73..a52c8667e 100644 --- a/Projects/Scripts/Gumps/SetSecureLevelGump.cs +++ b/Projects/Scripts/Gumps/SetSecureLevelGump.cs @@ -60,7 +60,7 @@ namespace Server.Gumps public int GetFirstID(SecureLevel level) => m_Info.Level == level ? 4006 : 4005; - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { var level = info.ButtonID switch { @@ -74,12 +74,12 @@ namespace Server.Gumps if (m_Info.Level == level) { - state.Mobile.SendLocalizedMessage(1061281); // Access level unchanged. + sender.Mobile.SendLocalizedMessage(1061281); // Access level unchanged. } else { m_Info.Level = level; - state.Mobile.SendLocalizedMessage(1061280); // New access level set. + sender.Mobile.SendLocalizedMessage(1061280); // New access level set. } } } diff --git a/Projects/Scripts/Gumps/SkillsGump.cs b/Projects/Scripts/Gumps/SkillsGump.cs index 31a4c881d..2d3543009 100644 --- a/Projects/Scripts/Gumps/SkillsGump.cs +++ b/Projects/Scripts/Gumps/SkillsGump.cs @@ -306,7 +306,6 @@ namespace Server.Gumps switch (sk.Lock) { default: - case SkillLock.Up: buttonID1 = 0x983; buttonID2 = 0x983; xOffset = 6; diff --git a/Projects/Scripts/Gumps/VendorRentalGumps.cs b/Projects/Scripts/Gumps/VendorRentalGumps.cs index 01c140d51..4a80fa64e 100644 --- a/Projects/Scripts/Gumps/VendorRentalGumps.cs +++ b/Projects/Scripts/Gumps/VendorRentalGumps.cs @@ -1,6 +1,5 @@ using Server.Items; using Server.Network; -using Server.Prompts; using Server.Mobiles; using Server.Targeting; using Server.Multis; diff --git a/Projects/Scripts/Holiday Stuff/Halloween/2006/Engines/TrickOrTreat.cs b/Projects/Scripts/Holiday Stuff/Halloween/2006/Engines/TrickOrTreat.cs index e93873910..39281307d 100644 --- a/Projects/Scripts/Holiday Stuff/Halloween/2006/Engines/TrickOrTreat.cs +++ b/Projects/Scripts/Holiday Stuff/Halloween/2006/Engines/TrickOrTreat.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Events.Halloween; using Server.Items; using Server.Mobiles; @@ -69,9 +70,7 @@ namespace Server.Engines.Events if (twin.Deleted) return; - foreach (Item item in m_From.Items) - if (item.Layer != Layer.Backpack && item.Layer != Layer.Mount && item.Layer != Layer.Bank) - m_Items.Add(item); + m_Items.AddRange(m_From.Items.Where(item => item.Layer != Layer.Backpack && item.Layer != Layer.Mount && item.Layer != Layer.Bank)); if (m_Items.Count > 0) { diff --git a/Projects/Scripts/Items/Addons/BallotBox.cs b/Projects/Scripts/Items/Addons/BallotBox.cs index 941e8037f..8888d0e93 100644 --- a/Projects/Scripts/Items/Addons/BallotBox.cs +++ b/Projects/Scripts/Items/Addons/BallotBox.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Server.Gumps; using Server.Multis; using Server.Network; -using Server.Prompts; namespace Server.Items { diff --git a/Projects/Scripts/Items/Addons/ElvenSpinningwheelEastAddon.cs b/Projects/Scripts/Items/Addons/ElvenSpinningwheelEastAddon.cs index 69945e6d2..4cbc53e4e 100644 --- a/Projects/Scripts/Items/Addons/ElvenSpinningwheelEastAddon.cs +++ b/Projects/Scripts/Items/Addons/ElvenSpinningwheelEastAddon.cs @@ -26,14 +26,8 @@ namespace Server.Items m_Timer.Start(); foreach (AddonComponent c in Components) - switch (c.ItemID) - { - case 0x2DD9: - case 0x101C: - case 0x10A4: - ++c.ItemID; - break; - } + if (c.ItemID == 0x2DD9 || c.ItemID == 0x101C || c.ItemID == 0x10A4) + ++c.ItemID; } public override void Serialize(GenericWriter writer) @@ -69,15 +63,8 @@ namespace Server.Items m_Timer = null; foreach (AddonComponent c in Components) - switch (c.ItemID) - { - case 0x1016: - case 0x101A: - case 0x101D: - case 0x10A5: - --c.ItemID; - break; - } + if (c.ItemID == 0x1016 || c.ItemID == 0x101A || c.ItemID == 0x101D || c.ItemID == 0x10A5) + --c.ItemID; callback?.Invoke(this, from, hue); } @@ -134,4 +121,4 @@ namespace Server.Items int version = reader.ReadEncodedInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Addons/ElvenSpinningwheelSouthAddon.cs b/Projects/Scripts/Items/Addons/ElvenSpinningwheelSouthAddon.cs index 39bd60ec8..8d5d5f2cb 100644 --- a/Projects/Scripts/Items/Addons/ElvenSpinningwheelSouthAddon.cs +++ b/Projects/Scripts/Items/Addons/ElvenSpinningwheelSouthAddon.cs @@ -26,15 +26,8 @@ namespace Server.Items m_Timer.Start(); foreach (AddonComponent c in Components) - switch (c.ItemID) - { - case 0x1015: - case 0x1019: - case 0x101C: - case 0x10A4: - ++c.ItemID; - break; - } + if (c.ItemID == 0x1015 || c.ItemID == 0x1019 || c.ItemID == 0x101C || c.ItemID == 0x10A4) + ++c.ItemID; } public override void Serialize(GenericWriter writer) @@ -71,15 +64,8 @@ namespace Server.Items m_Timer = null; foreach (AddonComponent c in Components) - switch (c.ItemID) - { - case 0x1016: - case 0x101A: - case 0x101D: - case 0x10A5: - --c.ItemID; - break; - } + if (c.ItemID == 0x1016 || c.ItemID == 0x101A || c.ItemID == 0x101D || c.ItemID == 0x10A5) + --c.ItemID; callback?.Invoke(this, from, hue); } @@ -136,4 +122,4 @@ namespace Server.Items int version = reader.ReadEncodedInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Addons/FlourMillEastAddon.cs b/Projects/Scripts/Items/Addons/FlourMillEastAddon.cs index e5c597386..2f9071dfc 100644 --- a/Projects/Scripts/Items/Addons/FlourMillEastAddon.cs +++ b/Projects/Scripts/Items/Addons/FlourMillEastAddon.cs @@ -130,11 +130,10 @@ namespace Server.Items { List components = Components; - int[][] stageTable = m_StageTable; - for (int i = 0; i < components.Count; ++i) { - if (!(components[i] is AddonComponent component)) + AddonComponent component = components[i]; + if (component == null) continue; int[] itemTable = FindItemTable(component.ItemID); @@ -210,4 +209,4 @@ namespace Server.Items int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Addons/FlourMillSouthAddon.cs b/Projects/Scripts/Items/Addons/FlourMillSouthAddon.cs index a158ec628..e3602112a 100644 --- a/Projects/Scripts/Items/Addons/FlourMillSouthAddon.cs +++ b/Projects/Scripts/Items/Addons/FlourMillSouthAddon.cs @@ -118,11 +118,10 @@ namespace Server.Items { List components = Components; - int[][] stageTable = m_StageTable; - for (int i = 0; i < components.Count; ++i) { - if (!(components[i] is AddonComponent component)) + AddonComponent component = components[i]; + if (component == null) continue; int[] itemTable = FindItemTable(component.ItemID); @@ -198,4 +197,4 @@ namespace Server.Items int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Addons/JackOLantern.cs b/Projects/Scripts/Items/Addons/JackOLantern.cs index d72b6383e..80d34f308 100644 --- a/Projects/Scripts/Items/Addons/JackOLantern.cs +++ b/Projects/Scripts/Items/Addons/JackOLantern.cs @@ -39,15 +39,7 @@ namespace Server.Items public override bool ShareHue => false; - private AddonComponent GetComponent(int itemID, int hue) - { - AddonComponent ac = new AddonComponent(itemID); - - ac.Hue = hue; - ac.Name = "jack-o-lantern"; - - return ac; - } + private AddonComponent GetComponent(int itemID, int hue) => new AddonComponent(itemID) {Hue = hue, Name = "jack-o-lantern"}; public override void Serialize(GenericWriter writer) { @@ -66,17 +58,23 @@ namespace Server.Items Timer.DelayCall(TimeSpan.Zero, delegate { for (int i = 0; i < Components.Count; ++i) - if (Components[i] is AddonComponent ac && ac.Hue == 2118) + { + AddonComponent ac = Components[i]; + if (ac?.Hue == 2118) ac.Hue = 1161; + } }); if (version <= 1) Timer.DelayCall(TimeSpan.Zero, delegate { for (int i = 0; i < Components.Count; ++i) - if (Components[i] is AddonComponent ac) + { + AddonComponent ac = Components[i]; + if (ac != null) ac.Name = "jack-o-lantern"; + } }); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Addons/SpinningwheelEastAddon.cs b/Projects/Scripts/Items/Addons/SpinningwheelEastAddon.cs index d85c4fd9b..e1dff197f 100644 --- a/Projects/Scripts/Items/Addons/SpinningwheelEastAddon.cs +++ b/Projects/Scripts/Items/Addons/SpinningwheelEastAddon.cs @@ -34,15 +34,8 @@ namespace Server.Items m_Timer.Start(); foreach (AddonComponent c in Components) - switch (c.ItemID) - { - case 0x1015: - case 0x1019: - case 0x101C: - case 0x10A4: - ++c.ItemID; - break; - } + if (c.ItemID == 0x1015 || c.ItemID == 0x1019 || c.ItemID == 0x101C || c.ItemID == 0x10A4) + ++c.ItemID; } public override void Serialize(GenericWriter writer) @@ -79,15 +72,8 @@ namespace Server.Items m_Timer = null; foreach (AddonComponent c in Components) - switch (c.ItemID) - { - case 0x1016: - case 0x101A: - case 0x101D: - case 0x10A5: - --c.ItemID; - break; - } + if (c.ItemID == 0x1016 || c.ItemID == 0x101A || c.ItemID == 0x101D || c.ItemID == 0x10A5) + --c.ItemID; callback?.Invoke(this, from, hue); } @@ -144,4 +130,4 @@ namespace Server.Items int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Addons/SpinningwheelSouthAddon.cs b/Projects/Scripts/Items/Addons/SpinningwheelSouthAddon.cs index a79769d39..1123fea2f 100644 --- a/Projects/Scripts/Items/Addons/SpinningwheelSouthAddon.cs +++ b/Projects/Scripts/Items/Addons/SpinningwheelSouthAddon.cs @@ -26,15 +26,8 @@ namespace Server.Items m_Timer.Start(); foreach (AddonComponent c in Components) - switch (c.ItemID) - { - case 0x1015: - case 0x1019: - case 0x101C: - case 0x10A4: - ++c.ItemID; - break; - } + if (c.ItemID == 0x1015 || c.ItemID == 0x1019 || c.ItemID == 0x101C || c.ItemID == 0x10A4) + ++c.ItemID; } public override void Serialize(GenericWriter writer) @@ -71,15 +64,8 @@ namespace Server.Items m_Timer = null; foreach (AddonComponent c in Components) - switch (c.ItemID) - { - case 0x1016: - case 0x101A: - case 0x101D: - case 0x10A5: - --c.ItemID; - break; - } + if (c.ItemID == 0x1016 || c.ItemID == 0x101A || c.ItemID == 0x101D || c.ItemID == 0x10A5) + --c.ItemID; callback?.Invoke(this, from, hue); } @@ -136,4 +122,4 @@ namespace Server.Items int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Aquarium/Aquarium.cs b/Projects/Scripts/Items/Aquarium/Aquarium.cs index c7247e0da..09e7fa1a7 100644 --- a/Projects/Scripts/Items/Aquarium/Aquarium.cs +++ b/Projects/Scripts/Items/Aquarium/Aquarium.cs @@ -597,8 +597,7 @@ namespace Server.Items UpdateWaterState(); // reward - if (LiveCreatures > 0) - m_RewardAvailable = true; + m_RewardAvailable |= LiveCreatures > 0; } else { @@ -606,12 +605,12 @@ namespace Server.Items if (OptimalState && LiveCreatures < MaxLiveCreatures) if (Utility.RandomDouble() < 0.005 * LiveCreatures) { - BaseFish fish = null; - int message = 0; + BaseFish fish; + int message; switch (Utility.Random(6)) { - case 0: + default: { message = 1074371; // Brine shrimp have hatched overnight in the tank. fish = new BrineShrimp(); diff --git a/Projects/Scripts/Items/Armor/BaseArmor.cs b/Projects/Scripts/Items/Armor/BaseArmor.cs index 59fd460df..81a69037c 100644 --- a/Projects/Scripts/Items/Armor/BaseArmor.cs +++ b/Projects/Scripts/Items/Armor/BaseArmor.cs @@ -436,9 +436,8 @@ namespace Server.Items BaseEnergyResistance + GetProtOffset() + GetResourceAttrs().ArmorEnergyResist + m_EnergyBonus; [CommandProperty(AccessLevel.GameMaster)] - public ArmorBodyType BodyPosition - { - get + public ArmorBodyType BodyPosition => + Layer switch { return Layer switch { @@ -1144,8 +1143,7 @@ namespace Server.Items if (GetSaveFlag(flags, SaveFlag.SkillBonuses)) SkillBonuses = new AosSkillBonuses(this, reader); - if (GetSaveFlag(flags, SaveFlag.PlayerConstructed)) - PlayerConstructed = true; + PlayerConstructed |= GetSaveFlag(flags, SaveFlag.PlayerConstructed); break; } @@ -1271,8 +1269,7 @@ namespace Server.Items } } - if (SkillBonuses == null) - SkillBonuses = new AosSkillBonuses(this); + SkillBonuses ??= new AosSkillBonuses(this); Mobile m = Parent as Mobile; @@ -1299,17 +1296,11 @@ namespace Server.Items m?.CheckStatTimers(); - if (version < 7) - PlayerConstructed = true; // we don't know, so, assume it's crafted + PlayerConstructed |= version < 7; // we don't know, so, assume it's crafted } - public override bool AllowSecureTrade(Mobile from, Mobile to, Mobile newOwner, bool accepted) - { - if (!Ethic.CheckTrade(from, to, newOwner, this)) - return false; - - return base.AllowSecureTrade(from, to, newOwner, accepted); - } + public override bool AllowSecureTrade(Mobile from, Mobile to, Mobile newOwner, bool accepted) => + Ethic.CheckTrade(@from, to, newOwner, this) && base.AllowSecureTrade(@from, to, newOwner, accepted); public override bool CanEquip(Mobile from) { @@ -1374,19 +1365,10 @@ namespace Server.Items return base.CanEquip(from); } - public override bool CheckPropertyConfliction(Mobile m) - { - if (base.CheckPropertyConfliction(m)) - return true; - - if (Layer == Layer.Pants) - return m.FindItemOnLayer(Layer.InnerLegs) != null; - - if (Layer == Layer.Shirt) - return m.FindItemOnLayer(Layer.InnerTorso) != null; - - return false; - } + public override bool CheckPropertyConfliction(Mobile m) => + base.CheckPropertyConfliction(m) || (Layer == Layer.Pants + ? m.FindItemOnLayer(Layer.InnerLegs) != null + : Layer == Layer.Shirt && m.FindItemOnLayer(Layer.InnerTorso) != null); public override bool OnEquip(Mobile from) { @@ -1477,25 +1459,9 @@ namespace Server.Items } } - public override bool AllowEquippedCast(Mobile from) - { - if (base.AllowEquippedCast(from)) - return true; + public override bool AllowEquippedCast(Mobile from) => base.AllowEquippedCast(@from) || Attributes.SpellChanneling != 0; - return Attributes.SpellChanneling != 0; - } - - public virtual int GetLuckBonus() - { - CraftResourceInfo resInfo = CraftResources.GetInfo(m_Resource); - - CraftAttributeInfo attrInfo = resInfo?.AttributeInfo; - - if (attrInfo == null) - return 0; - - return attrInfo.ArmorLuck; - } + public virtual int GetLuckBonus() => CraftResources.GetInfo(m_Resource)?.AttributeInfo?.ArmorLuck ?? 0; public override void GetProperties(ObjectPropertyList list) { @@ -1665,9 +1631,7 @@ namespace Server.Items if (attrs.Count == 0 && Crafter == null && Name != null) return; - EquipmentInfo eqInfo = new EquipmentInfo(number, m_Crafter, false, attrs.ToArray()); - - from.Send(new DisplayEquipmentInfo(this, eqInfo)); + EquipmentPackets.SendDisplayEquipmentInfo(from.NetState, this, number, m_Crafter, false, attrs); } [Flags] diff --git a/Projects/Scripts/Items/Armor/Glasses/ElvenGlasses.cs b/Projects/Scripts/Items/Armor/Glasses/ElvenGlasses.cs index 9f51f6393..d16ce0287 100644 --- a/Projects/Scripts/Items/Armor/Glasses/ElvenGlasses.cs +++ b/Projects/Scripts/Items/Armor/Glasses/ElvenGlasses.cs @@ -1,3 +1,5 @@ +using System; + namespace Server.Items { public class ElvenGlasses : BaseArmor @@ -120,16 +122,14 @@ namespace Server.Items SaveFlag flags = (SaveFlag)reader.ReadInt(); - if (GetSaveFlag(flags, SaveFlag.WeaponAttributes)) - WeaponAttributes = new AosWeaponAttributes(this, reader); - else - WeaponAttributes = new AosWeaponAttributes(this); + WeaponAttributes = GetSaveFlag(flags, SaveFlag.WeaponAttributes) ? new AosWeaponAttributes(this, reader) : new AosWeaponAttributes(this); } + [Flags] private enum SaveFlag { None = 0x00000000, WeaponAttributes = 0x00000001 } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Body Parts/Head.cs b/Projects/Scripts/Items/Body Parts/Head.cs index 96086f183..a8d26d885 100644 --- a/Projects/Scripts/Items/Body Parts/Head.cs +++ b/Projects/Scripts/Items/Body Parts/Head.cs @@ -33,9 +33,8 @@ namespace Server.Items [CommandProperty(AccessLevel.GameMaster)] public HeadType HeadType{ get; set; } - public override string DefaultName - { - get + public override string DefaultName => + PlayerName == null ? base.DefaultName : HeadType switch { if (PlayerName == null) return base.DefaultName; diff --git a/Projects/Scripts/Items/Books/BaseBook.cs b/Projects/Scripts/Items/Books/BaseBook.cs index 754cabba2..67392e12d 100644 --- a/Projects/Scripts/Items/Books/BaseBook.cs +++ b/Projects/Scripts/Items/Books/BaseBook.cs @@ -57,19 +57,17 @@ namespace Server.Items if (content == null) { - Pages = new BookPageInfo[pageCount]; + Pages = new BookPageInfo[Math.Min(pageCount, 255)]; for (int i = 0; i < Pages.Length; ++i) Pages[i] = new BookPageInfo(); } else - { Pages = content.Copy(); - } } // Intended for defined books only - public BaseBook(int itemID, bool writable) : this(itemID, 0) + public BaseBook(int itemID, bool writable) : this(itemID, 0, writable) { } @@ -230,12 +228,7 @@ namespace Server.Items Pages[i] = new BookPageInfo(reader); } else - { - if (content != null) - Pages = content.Copy(); - else - Pages = new BookPageInfo[0]; - } + Pages = content?.Copy() ?? new BookPageInfo[0]; break; } @@ -254,14 +247,7 @@ namespace Server.Items Pages[i] = new BookPageInfo(reader); } else - { - BookContent content = DefaultContent; - - if (content != null) - Pages = content.Copy(); - else - Pages = new BookPageInfo[0]; - } + Pages = DefaultContent?.Copy() ?? new BookPageInfo[0]; break; } @@ -307,8 +293,8 @@ namespace Server.Items Author = from.Name; } - from.Send(new BookHeader(from, this)); - from.Send(new BookPageDetails(this)); + BookPackets.SendBookHeader(from.NetState, from, this); + BookPackets.SendBookPageDetails(from.NetState, this); } public static void Initialize() @@ -350,14 +336,14 @@ namespace Server.Items if (titleLength > 60) return; - string title = pvSrc.ReadUTF8StringSafe(titleLength); + string title = pvSrc.ReadStringSafe(titleLength); int authorLength = pvSrc.ReadUInt16(); if (authorLength > 30) return; - string author = pvSrc.ReadUTF8StringSafe(authorLength); + string author = pvSrc.ReadStringSafe(authorLength); book.Title = Utility.FixHtml(title); book.Author = Utility.FixHtml(author); @@ -380,31 +366,23 @@ namespace Server.Items { int index = pvSrc.ReadUInt16(); - if (index >= 1 && index <= book.PagesCount) - { - --index; - - int lineCount = pvSrc.ReadUInt16(); - - if (lineCount <= 8) - { - string[] lines = new string[lineCount]; - - for (int j = 0; j < lineCount; ++j) - if ((lines[j] = pvSrc.ReadUTF8StringSafe()).Length >= 80) - return; - - book.Pages[index].Lines = lines; - } - else - { - return; - } - } - else - { + if (index < 1 || index > book.PagesCount) return; - } + + --index; + + int lineCount = pvSrc.ReadUInt16(); + + if (lineCount > 8) + return; + + string[] lines = new string[lineCount]; + + for (int j = 0; j < lineCount; ++j) + if ((lines[j] = pvSrc.ReadUTF8StringSafe()).Length >= 80) + return; + + book.Pages[index].Lines = lines; } } @@ -418,58 +396,4 @@ namespace Server.Items Content = 0x08 } } - - public sealed class BookPageDetails : Packet - { - public BookPageDetails(BaseBook book) : base(0x66) - { - EnsureCapacity(256); - - m_Stream.Write(book.Serial); - m_Stream.Write((ushort)book.PagesCount); - - for (int i = 0; i < book.PagesCount; ++i) - { - BookPageInfo page = book.Pages[i]; - - m_Stream.Write((ushort)(i + 1)); - m_Stream.Write((ushort)page.Lines.Length); - - for (int j = 0; j < page.Lines.Length; ++j) - { - byte[] buffer = Utility.UTF8.GetBytes(page.Lines[j]); - - m_Stream.Write(buffer, 0, buffer.Length); - m_Stream.Write((byte)0); - } - } - } - } - - public sealed class BookHeader : Packet - { - public BookHeader(Mobile from, BaseBook book) : base(0xD4) - { - string title = book.Title ?? ""; - string author = book.Author ?? ""; - - byte[] titleBuffer = Utility.UTF8.GetBytes(title); - byte[] authorBuffer = Utility.UTF8.GetBytes(author); - - EnsureCapacity(15 + titleBuffer.Length + authorBuffer.Length); - - m_Stream.Write(book.Serial); - m_Stream.Write(true); - m_Stream.Write(book.Writable && from.InRange(book.GetWorldLocation(), 1)); - m_Stream.Write((ushort)book.PagesCount); - - m_Stream.Write((ushort)(titleBuffer.Length + 1)); - m_Stream.Write(titleBuffer, 0, titleBuffer.Length); - m_Stream.Write((byte)0); // terminate - - m_Stream.Write((ushort)(authorBuffer.Length + 1)); - m_Stream.Write(authorBuffer, 0, authorBuffer.Length); - m_Stream.Write((byte)0); // terminate - } - } } diff --git a/Projects/Scripts/Items/Books/BrownBook.cs b/Projects/Scripts/Items/Books/BrownBook.cs index f6900edf3..611c134ba 100644 --- a/Projects/Scripts/Items/Books/BrownBook.cs +++ b/Projects/Scripts/Items/Books/BrownBook.cs @@ -13,8 +13,8 @@ namespace Server.Items } [Constructible] - public BrownBook(string title, string author, int pageCount, bool writable) : base(0xFEF, title, author, pageCount, - writable) + public BrownBook(string title, string author, int pageCount, bool writable) : + base(0xFEF, title, author, pageCount, writable) { } @@ -41,4 +41,4 @@ namespace Server.Items writer.Write(0); // version } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Books/Packets.cs b/Projects/Scripts/Items/Books/Packets.cs new file mode 100644 index 000000000..49a78fc2d --- /dev/null +++ b/Projects/Scripts/Items/Books/Packets.cs @@ -0,0 +1,80 @@ +using System; +using Server.Buffers; +using Server.Items; + +namespace Server.Network +{ + public static class BookPackets + { + public static void SendBookPageDetails(NetState ns, BaseBook book) + { + if (ns == null) + return; + + // 80 chars per line (240 bytes) + // 8 lines per page + // Max: 77049 bytes + int length = 9; + + for (int i = 0; i < book.PagesCount; i++) + length += 1926 * book.Pages[i].Lines.Length; + + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0x66); // Packet ID + writer.Position += 2; // Dynamic Length + + writer.Write(book.Serial); + writer.Write((ushort)book.PagesCount); + + for (int i = 0; i < book.PagesCount; i++) + { + BookPageInfo page = book.Pages[i]; + length = Math.Min(page.Lines.Length, 8); + + writer.Write((ushort)(i + 1)); + writer.Write((ushort)length); + + for (int j = 0; j < length; j++) + { + string line = page.Lines[j]; + writer.WriteUTF8Null(line); + } + } + + writer.Position = 1; + writer.Write((ushort)writer.WrittenCount); + + ns.Send(writer.Span); + } + + public static void SendBookHeader(NetState ns, Mobile from, BaseBook book) + { + if (ns == null) + return; + + string title = book.Title ?? ""; + string author = book.Author ?? ""; + + int length = 17 + title.Length + author.Length; + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0xD4); // Packet ID + writer.Position += 2; // Dynamic Length + + writer.Write(book.Serial); + writer.Write((byte)0x1); // true + writer.Write(book.Writable && from.InRange(book.GetWorldLocation(), 1)); + writer.Write((ushort)book.PagesCount); + + writer.Write((ushort)title.Length + 1); + writer.WriteAsciiNull(title); + + writer.Write((ushort)author.Length + 1); + writer.WriteAsciiNull(author); + + writer.Position = 1; + writer.Write((ushort)writer.WrittenCount); + + ns.Send(writer.Span); + } + } +} diff --git a/Projects/Scripts/Items/Books/RedBook.cs b/Projects/Scripts/Items/Books/RedBook.cs index 2ee8b7d15..d0ddb7bc7 100644 --- a/Projects/Scripts/Items/Books/RedBook.cs +++ b/Projects/Scripts/Items/Books/RedBook.cs @@ -13,8 +13,8 @@ namespace Server.Items } [Constructible] - public RedBook(string title, string author, int pageCount, bool writable) : base(0xFF1, title, author, pageCount, - writable) + public RedBook(string title, string author, int pageCount, bool writable) : + base(0xFF1, title, author, pageCount, writable) { } @@ -41,4 +41,4 @@ namespace Server.Items writer.Write(0); // version } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Books/TanBook.cs b/Projects/Scripts/Items/Books/TanBook.cs index 5be5297b0..ef604c743 100644 --- a/Projects/Scripts/Items/Books/TanBook.cs +++ b/Projects/Scripts/Items/Books/TanBook.cs @@ -13,8 +13,8 @@ namespace Server.Items } [Constructible] - public TanBook(string title, string author, int pageCount, bool writable) : base(0xFF0, title, author, pageCount, - writable) + public TanBook(string title, string author, int pageCount, bool writable) : + base(0xFF0, title, author, pageCount, writable) { } @@ -41,4 +41,4 @@ namespace Server.Items writer.Write(0); // version } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Clothing/BaseClothing.cs b/Projects/Scripts/Items/Clothing/BaseClothing.cs index 06ee87907..ac7ddf454 100644 --- a/Projects/Scripts/Items/Clothing/BaseClothing.cs +++ b/Projects/Scripts/Items/Clothing/BaseClothing.cs @@ -724,9 +724,7 @@ namespace Server.Items int number; if (Name == null) - { number = LabelNumber; - } else { LabelTo(from, Name); @@ -736,9 +734,7 @@ namespace Server.Items if (attrs.Count == 0 && Crafter == null && Name != null) return; - EquipmentInfo eqInfo = new EquipmentInfo(number, m_Crafter, false, attrs.ToArray()); - - from.Send(new DisplayEquipmentInfo(this, eqInfo)); + EquipmentPackets.SendDisplayEquipmentInfo(from.NetState, this, number, m_Crafter, false, attrs); } public virtual void AddEquipInfoAttributes(Mobile from, List attrs) @@ -904,25 +900,13 @@ namespace Server.Items else m_Resource = DefaultResource; - if (GetSaveFlag(flags, SaveFlag.Attributes)) - Attributes = new AosAttributes(this, reader); - else - Attributes = new AosAttributes(this); + Attributes = GetSaveFlag(flags, SaveFlag.Attributes) ? new AosAttributes(this, reader) : new AosAttributes(this); - if (GetSaveFlag(flags, SaveFlag.ClothingAttributes)) - ClothingAttributes = new AosArmorAttributes(this, reader); - else - ClothingAttributes = new AosArmorAttributes(this); + ClothingAttributes = GetSaveFlag(flags, SaveFlag.ClothingAttributes) ? new AosArmorAttributes(this, reader) : new AosArmorAttributes(this); - if (GetSaveFlag(flags, SaveFlag.SkillBonuses)) - SkillBonuses = new AosSkillBonuses(this, reader); - else - SkillBonuses = new AosSkillBonuses(this); + SkillBonuses = GetSaveFlag(flags, SaveFlag.SkillBonuses) ? new AosSkillBonuses(this, reader) : new AosSkillBonuses(this); - if (GetSaveFlag(flags, SaveFlag.Resistances)) - Resistances = new AosElementAttributes(this, reader); - else - Resistances = new AosElementAttributes(this); + Resistances = GetSaveFlag(flags, SaveFlag.Resistances) ? new AosElementAttributes(this, reader) : new AosElementAttributes(this); if (GetSaveFlag(flags, SaveFlag.MaxHitPoints)) m_MaxHitPoints = reader.ReadEncodedInt(); @@ -943,8 +927,7 @@ namespace Server.Items else m_StrReq = -1; - if (GetSaveFlag(flags, SaveFlag.PlayerConstructed)) - PlayerConstructed = true; + PlayerConstructed |= GetSaveFlag(flags, SaveFlag.PlayerConstructed); break; } @@ -982,8 +965,7 @@ namespace Server.Items } } - if (version < 2) - PlayerConstructed = true; // we don't know, so, assume it's crafted + PlayerConstructed |= version < 2; // we don't know, so, assume it's crafted if (version < 3) { diff --git a/Projects/Scripts/Items/Clothing/Hats.cs b/Projects/Scripts/Items/Clothing/Hats.cs index 122a4c086..45d17ad24 100644 --- a/Projects/Scripts/Items/Clothing/Hats.cs +++ b/Projects/Scripts/Items/Clothing/Hats.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using Server.Engines.Craft; using Server.Misc; -using Server.Network; namespace Server.Items { diff --git a/Projects/Scripts/Items/Containers/Container.cs b/Projects/Scripts/Items/Containers/Container.cs index 5dec60a0c..1d0186189 100644 --- a/Projects/Scripts/Items/Containers/Container.cs +++ b/Projects/Scripts/Items/Containers/Container.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using Server.ContextMenus; using Server.Mobiles; using Server.Multis; @@ -16,40 +17,17 @@ namespace Server.Items { } - public override int DefaultMaxWeight - { - get - { - if (IsSecure) - return 0; + public override int DefaultMaxWeight => IsSecure ? 0 : base.DefaultMaxWeight; - return base.DefaultMaxWeight; - } - } + public override bool IsAccessibleTo(Mobile m) => + BaseHouse.CheckAccessible(m, this) && base.IsAccessibleTo(m); - public override bool IsAccessibleTo(Mobile m) - { - if (!BaseHouse.CheckAccessible(m, this)) - return false; + public override bool CheckHold(Mobile m, Item item, bool message, bool checkItems, int plusItems, int plusWeight) => + (!IsSecure || BaseHouse.CheckHold(m, this, item, message, checkItems, plusItems, plusWeight)) && + base.CheckHold(m, item, message, checkItems, plusItems, plusWeight); - return base.IsAccessibleTo(m); - } - - public override bool CheckHold(Mobile m, Item item, bool message, bool checkItems, int plusItems, int plusWeight) - { - if (IsSecure && !BaseHouse.CheckHold(m, this, item, message, checkItems, plusItems, plusWeight)) - return false; - - return base.CheckHold(m, item, message, checkItems, plusItems, plusWeight); - } - - public override bool CheckItemUse(Mobile from, Item item) - { - if (IsDecoContainer && item is BaseBook) - return true; - - return base.CheckItemUse(from, item); - } + public override bool CheckItemUse(Mobile from, Item item) => + IsDecoContainer && item is BaseBook || base.CheckItemUse(from, item); public override void GetContextMenuEntries(Mobile from, List list) { @@ -79,13 +57,8 @@ namespace Server.Items List list = Items; - for (int i = 0; i < list.Count; ++i) - { - Item item = list[i]; - - if (!(item is Container) && item.StackWith(from, dropped, false)) - return true; - } + if (list.Any(item => !(item is Container) && item.StackWith(from, dropped, false))) + return true; DropItem(dropped); @@ -936,4 +909,4 @@ namespace Server.Items Weight = -1; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Containers/FillableContainers.cs b/Projects/Scripts/Items/Containers/FillableContainers.cs index 13b08e542..986be77cf 100644 --- a/Projects/Scripts/Items/Containers/FillableContainers.cs +++ b/Projects/Scripts/Items/Containers/FillableContainers.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Mobiles; namespace Server.Items @@ -95,14 +96,7 @@ namespace Server.Items } } - public int GetItemsCount() - { - int count = 0; - - foreach (Item item in Items) count += item.Amount; - - return count; - } + public int GetItemsCount() => Items.Sum(item => item.Amount); public void CheckRespawn() { @@ -1507,7 +1501,9 @@ namespace Server.Items Mobile nearest = null; FillableContent content = null; - foreach (Mobile mob in map.GetMobilesInRange(loc, 20)) + IPooledEnumerable eable = map.GetMobilesInRange(loc, 20); + + foreach (Mobile mob in eable) { if (nearest != null && mob.GetDistanceToSqrt(loc) > nearest.GetDistanceToSqrt(loc) && !(nearest is Cobbler && mob is Provisioner)) @@ -1520,6 +1516,8 @@ namespace Server.Items } } + eable.Free(); + return content; } } diff --git a/Projects/Scripts/Items/Containers/LockableContainer.cs b/Projects/Scripts/Items/Containers/LockableContainer.cs index 783f90b0a..e6b89b306 100644 --- a/Projects/Scripts/Items/Containers/LockableContainer.cs +++ b/Projects/Scripts/Items/Containers/LockableContainer.cs @@ -264,7 +264,7 @@ namespace Server.Items inaccessible = true; } - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Regular, 0x3B2, 3, number, "", "")); + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Regular, 0x3B2, 3, number); } return inaccessible; @@ -323,4 +323,4 @@ namespace Server.Items LabelTo(from, 1041645); //recovered from a shipwreck } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Containers/SalvageBag.cs b/Projects/Scripts/Items/Containers/SalvageBag.cs index cea584359..dad4c4ac7 100644 --- a/Projects/Scripts/Items/Containers/SalvageBag.cs +++ b/Projects/Scripts/Items/Containers/SalvageBag.cs @@ -126,16 +126,11 @@ namespace Server.Items #region Checks - private bool Resmeltables() //Where context menu checks for metal items and dragon barding deeds - { - foreach (Item i in Items) - return i?.Deleted == false && ( - i is BaseWeapon weapon && CraftResources.GetType(weapon.Resource) == CraftResourceType.Metal || - i is BaseArmor armor && CraftResources.GetType(armor.Resource) == CraftResourceType.Metal || - i is DragonBardingDeed); - - return false; - } + private bool Resmeltables() => //Where context menu checks for metal items and dragon barding deeds + Items.Select(i => i?.Deleted == false && + (i is BaseWeapon weapon && CraftResources.GetType(weapon.Resource) == CraftResourceType.Metal || + i is BaseArmor armor && CraftResources.GetType(armor.Resource) == CraftResourceType.Metal || + i is DragonBardingDeed)).FirstOrDefault(); private bool Scissorables() //Where context menu checks for Leather items and cloth items { diff --git a/Projects/Scripts/Items/Containers/TrappableContainer.cs b/Projects/Scripts/Items/Containers/TrappableContainer.cs index c5de08e12..804519d26 100644 --- a/Projects/Scripts/Items/Containers/TrappableContainer.cs +++ b/Projects/Scripts/Items/Containers/TrappableContainer.cs @@ -46,7 +46,7 @@ namespace Server.Items if (Deleted || !to.CanSee(this)) return; - to.Send(new MessageLocalized(Serial, ItemID, MessageType.Regular, hue, 3, number, "", "")); + Packets.SendMessageLocalized(to.NetState, Serial, ItemID, MessageType.Regular, hue, 3, number); } private void SendMessageTo(Mobile to, string text, int hue) @@ -54,7 +54,7 @@ namespace Server.Items if (Deleted || !to.CanSee(this)) return; - to.Send(new UnicodeMessage(Serial, ItemID, MessageType.Regular, hue, 3, "ENU", "", text)); + Packets.SendUnicodeMessage(to.NetState,Serial, ItemID, MessageType.Regular, hue, 3, "ENU", "", text); } public virtual bool ExecuteTrap(Mobile from) @@ -91,7 +91,7 @@ namespace Server.Items from.LocalOverheadMessage(MessageType.Regular, 0x2A, 503000); } - Effects.SendLocationEffect(loc, facet, 0x36BD, 15, 10); + Effects.SendLocationEffect(loc, facet, 0x36BD, 15); Effects.PlaySound(loc, facet, 0x307); break; @@ -129,7 +129,7 @@ namespace Server.Items AOS.Damage(from, damage, 100, 0, 0, 0, 0); - // A dart imbeds itself in your flesh! + // A dart embeds itself in your flesh! from.LocalOverheadMessage(MessageType.Regular, 0x62, 502998); } @@ -221,4 +221,4 @@ namespace Server.Items } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Containers/TreasureMapChest.cs b/Projects/Scripts/Items/Containers/TreasureMapChest.cs index a0ccfcde4..8a4432c52 100644 --- a/Projects/Scripts/Items/Containers/TreasureMapChest.cs +++ b/Projects/Scripts/Items/Containers/TreasureMapChest.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.ContextMenus; using Server.Engines.PartySystem; using Server.Gumps; @@ -39,7 +40,7 @@ namespace Server.Items public override int LabelNumber => 3000541; - public static Type[] Artifacts{ get; } = + public static Type[] Artifacts { get; } = { typeof(CandelabraOfSouls), typeof(GoldBricks), typeof(PhillipsWoodenSteed), typeof(ArcticDeathDealer), typeof(BlazeOfDeath), typeof(BurglarsBandana), @@ -51,18 +52,18 @@ namespace Server.Items }; [CommandProperty(AccessLevel.GameMaster)] - public int Level{ get; set; } + public int Level { get; set; } [CommandProperty(AccessLevel.GameMaster)] - public Mobile Owner{ get; set; } + public Mobile Owner { get; set; } [CommandProperty(AccessLevel.GameMaster)] - public DateTime DeleteTime{ get; private set; } + public DateTime DeleteTime { get; private set; } [CommandProperty(AccessLevel.GameMaster)] - public bool Temporary{ get; set; } + public bool Temporary { get; set; } - public List Guardians{ get; private set; } + public List Guardians { get; private set; } public override bool IsDecoContainer => false; @@ -196,18 +197,11 @@ namespace Server.Items }; } else - { numberItems = level * 6; - } for (int i = 0; i < numberItems; ++i) { - Item item; - - if (Core.AOS) - item = Loot.RandomArmorOrShieldOrWeaponOrJewelry(); - else - item = Loot.RandomArmorOrShieldOrWeapon(); + Item item = Core.AOS ? Loot.RandomArmorOrShieldOrWeaponOrJewelry() : Loot.RandomArmorOrShieldOrWeapon(); if (item is BaseWeapon weapon) { @@ -296,13 +290,12 @@ namespace Server.Items if (Level == 0 && from.AccessLevel < AccessLevel.GameMaster) { - foreach (Mobile m in Guardians) - if (m.Alive) - { - from.SendLocalizedMessage( - 1046448); // You must first kill the guardians before you may open this chest. - return true; - } + if (Guardians.Any(m => m.Alive)) + { + from.SendLocalizedMessage( + 1046448); // You must first kill the guardians before you may open this chest. + return true; + } LockPick(from); return false; @@ -395,29 +388,29 @@ namespace Server.Items switch (version) { case 2: - { - Guardians = reader.ReadStrongMobileList(); - Temporary = reader.ReadBool(); + { + Guardians = reader.ReadStrongMobileList(); + Temporary = reader.ReadBool(); - goto case 1; - } + goto case 1; + } case 1: - { - Owner = reader.ReadMobile(); + { + Owner = reader.ReadMobile(); - goto case 0; - } + goto case 0; + } case 0: - { - Level = reader.ReadInt(); - DeleteTime = reader.ReadDeltaTime(); - m_Lifted = reader.ReadStrongItemList(); + { + Level = reader.ReadInt(); + DeleteTime = reader.ReadDeltaTime(); + m_Lifted = reader.ReadStrongItemList(); - if (version < 2) - Guardians = new List(); + if (version < 2) + Guardians = new List(); - break; - } + break; + } } if (!Temporary) diff --git a/Projects/Scripts/Items/Deeds/HairRestylingDeed.cs b/Projects/Scripts/Items/Deeds/HairRestylingDeed.cs index 19eecb70c..a7026917f 100644 --- a/Projects/Scripts/Items/Deeds/HairRestylingDeed.cs +++ b/Projects/Scripts/Items/Deeds/HairRestylingDeed.cs @@ -56,9 +56,7 @@ namespace Server.Items new[] { 1074393, 1074390, 0x2fd0, 0x2fcd, 0xedde, 0xc6cb } // buns, long }; -/* - racial arrays are: cliloc_F, cliloc_M, ItemID_F, ItemID_M, gump_img_F, gump_img_M -*/ + // racial arrays are: cliloc_F, cliloc_M, ItemID_F, ItemID_M, gump_img_F, gump_img_M private int[][] HumanArray = /* why on earth cant these utilies be consistent with hex/dec */ { new[] { 0 }, @@ -73,10 +71,8 @@ namespace Server.Items new[] { 1011050, 1011050, 0x204A, 0x204A, 0xED29, 0xED29 }, // Topknot new[] { 1011396, 1011396, 0x2047, 0x2047, 0xed25, 0xc618 } // Curly }; -/* - gump data: bgX, bgY, htmlX, htmlY, imgX, imgY, butX, butY -*/ + // gump data: bgX, bgY, htmlX, htmlY, imgX, imgY, butX, butY private int[][] LayoutArray = { new[] { 0 }, /* padding: its more efficient than code to ++ the index/buttonid */ diff --git a/Projects/Scripts/Items/Deeds/HolidayTreeDeed.cs b/Projects/Scripts/Items/Deeds/HolidayTreeDeed.cs index c56b3b341..03ee8f05a 100644 --- a/Projects/Scripts/Items/Deeds/HolidayTreeDeed.cs +++ b/Projects/Scripts/Items/Deeds/HolidayTreeDeed.cs @@ -91,11 +91,11 @@ namespace Server.Items Point3D loc = new Point3D(p); if (p is StaticTarget target) - loc.Z -= TileData.ItemTable[target.ItemID] - .CalcHeight; /* NOTE: OSI does not properly normalize Z positioning here. - * A side affect is that you can only place on floors (due to the CanFit call). - * That functionality may be desired. And so, it's included in this script. - */ + loc.Z -= TileData.ItemTable[target.ItemID].CalcHeight; + /* NOTE: OSI does not properly normalize Z positioning here. + * A side affect is that you can only place on floors (due to the CanFit call). + * That functionality may be desired. And so, it's included in this script. + */ if (ValidatePlacement(from, loc)) EndPlace(from, type, loc); diff --git a/Projects/Scripts/Items/Equipment/EquipmentInfoAttribute.cs b/Projects/Scripts/Items/Equipment/EquipmentInfoAttribute.cs new file mode 100644 index 000000000..6f8ac034c --- /dev/null +++ b/Projects/Scripts/Items/Equipment/EquipmentInfoAttribute.cs @@ -0,0 +1,15 @@ +namespace Server.Items +{ + public class EquipInfoAttribute + { + public EquipInfoAttribute(int number, int charges = -1) + { + Number = number; + Charges = charges; + } + + public int Number { get; } + + public int Charges { get; } + } +} diff --git a/Projects/Scripts/Items/Equipment/Packets.cs b/Projects/Scripts/Items/Equipment/Packets.cs new file mode 100644 index 000000000..607227df7 --- /dev/null +++ b/Projects/Scripts/Items/Equipment/Packets.cs @@ -0,0 +1,56 @@ +using System.Collections.Generic; +using Server.Buffers; +using Server.Items; + +namespace Server.Network +{ + public static class EquipmentPackets + { + public static void SendDisplayEquipmentInfo(NetState ns, Item item, int number, Mobile crafter, bool unidentified, ICollection attrs) + { + int packetLength = 17 + + (crafter != null ? 6 + crafter.RawName?.Length ?? 0 : 0) + + (unidentified ? 4 : 0) + attrs.Count * 6; + + SpanWriter writer = new SpanWriter(stackalloc byte[packetLength]); + + writer.Write((byte)0xBF); // Extended Command Packet ID + writer.Write((ushort)packetLength); // Dynamic Length + + writer.Write((short)0x10); // Command + writer.Write(item.Serial); + writer.Write(number); + + if (crafter != null) + { + // TODO: We should not be referencing the crafter. + // They could have been deleted and the crafted by should still show up. + string name = crafter.RawName; + + writer.Write(-3); + + if (name == null) + writer.Write((ushort)0); + else + { + int length = name.Length; + writer.Write((ushort)length); + writer.WriteAsciiFixed(name, length); + } + } + + if (unidentified) + writer.Write(-4); + + foreach (EquipInfoAttribute attr in attrs) + { + writer.Write(attr.Number); + writer.Write((short)attr.Charges); + } + + writer.Write(-1); + + ns.Send(writer.Span); + } + } +} diff --git a/Projects/Scripts/Items/Food/CookableFood.cs b/Projects/Scripts/Items/Food/CookableFood.cs index cb03e9e15..66d3e86a6 100644 --- a/Projects/Scripts/Items/Food/CookableFood.cs +++ b/Projects/Scripts/Items/Food/CookableFood.cs @@ -43,13 +43,13 @@ namespace Server.Items } #if false - public override void OnDoubleClick( Mobile from ) - { - if ( !Movable ) - return; + public override void OnDoubleClick( Mobile from ) + { + if ( !Movable ) + return; - from.Target = new InternalTarget( this ); - } + from.Target = new InternalTarget( this ); + } #endif public static bool IsHeatSource(object targeted) @@ -63,22 +63,13 @@ namespace Server.Items else return false; - if (itemID >= 0xDE3 && itemID <= 0xDE9) - return true; // Campfire - if (itemID >= 0x461 && itemID <= 0x48E) - return true; // Sandstone oven/fireplace - if (itemID >= 0x92B && itemID <= 0x96C) - return true; // Stone oven/fireplace - if (itemID == 0xFAC) - return true; // Firepit - if (itemID >= 0x184A && itemID <= 0x184C) - return true; // Heating stand (left) - if (itemID >= 0x184E && itemID <= 0x1850) - return true; // Heating stand (right) - if (itemID >= 0x398C && itemID <= 0x399F) - return true; // Fire field - - return false; + return itemID == 0xFAC || + itemID >= 0xDE3 && itemID <= 0xDE9 || + itemID >= 0x461 && itemID <= 0x48E || + itemID >= 0x92B && itemID <= 0x96C || + itemID >= 0x184A && itemID <= 0x184C || + itemID >= 0x184E && itemID <= 0x1850 || + itemID >= 0x398C && itemID <= 0x399F; } private class InternalTarget : Target @@ -103,9 +94,7 @@ namespace Server.Items t.Start(); } else - { from.SendLocalizedMessage(500119); // You must wait to perform another action - } } } @@ -143,9 +132,7 @@ namespace Server.Items m_From.PlaySound(0x57); } else - { m_From.SendLocalizedMessage(500686); // You burn the food to a crisp! It's ruined. - } } } } diff --git a/Projects/Scripts/Items/Food/Cooking.cs b/Projects/Scripts/Items/Food/Cooking.cs index ca8a09e2a..aa68f6c75 100644 --- a/Projects/Scripts/Items/Food/Cooking.cs +++ b/Projects/Scripts/Items/Food/Cooking.cs @@ -47,13 +47,13 @@ namespace Server.Items } #if false - public override void OnDoubleClick( Mobile from ) - { - if ( !Movable ) - return; + public override void OnDoubleClick( Mobile from ) + { + if ( !Movable ) + return; - from.Target = new InternalTarget( this ); - } + from.Target = new InternalTarget( this ); + } #endif private class InternalTarget : Target @@ -135,13 +135,13 @@ namespace Server.Items } #if false - public override void OnDoubleClick( Mobile from ) - { - if ( !Movable ) - return; + public override void OnDoubleClick( Mobile from ) + { + if ( !Movable ) + return; - from.Target = new InternalTarget( this ); - } + from.Target = new InternalTarget( this ); + } #endif private class InternalTarget : Target @@ -454,9 +454,9 @@ namespace Server.Items ++ItemID; #if false - this.Delete(); + this.Delete(); - from.AddToBackpack( new SackFlourOpen() ); + from.AddToBackpack( new SackFlourOpen() ); #endif } } diff --git a/Projects/Scripts/Items/Games/BaseBoard.cs b/Projects/Scripts/Items/Games/BaseBoard.cs index fd292b550..d7ecddcd4 100644 --- a/Projects/Scripts/Items/Games/BaseBoard.cs +++ b/Projects/Scripts/Items/Games/BaseBoard.cs @@ -72,17 +72,13 @@ namespace Server.Items { if (dropped is BasePiece piece && piece.Board == this && base.OnDragDropInto(from, dropped, point)) { - Packet p = new PlaySound(0x127, GetWorldLocation()); - - p.Acquire(); + Point3D loc = GetWorldLocation(); if (RootParent == from) - from.Send(p); + Packets.SendPlaySound(from.NetState, 0x127, loc); else foreach (NetState state in GetClientsInRange(2)) - state.Send(p); - - p.Release(); + Packets.SendPlaySound(state, 0x127, loc); return true; } diff --git a/Projects/Scripts/Items/Games/Dices.cs b/Projects/Scripts/Items/Games/Dices.cs index d065caaed..29bc2d7bf 100644 --- a/Projects/Scripts/Items/Games/Dices.cs +++ b/Projects/Scripts/Items/Games/Dices.cs @@ -21,10 +21,8 @@ namespace Server.Items public override void OnDoubleClick(Mobile from) { - if (!from.InRange(GetWorldLocation(), 2)) - return; - - Roll(from); + if (from.InRange(GetWorldLocation(), 2)) + Roll(from); } public void Roll(Mobile from) @@ -45,4 +43,4 @@ namespace Server.Items int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Games/Mahjong/MahjongGame.cs b/Projects/Scripts/Items/Games/Mahjong/MahjongGame.cs index cefbd322a..ac0d77495 100644 --- a/Projects/Scripts/Items/Games/Mahjong/MahjongGame.cs +++ b/Projects/Scripts/Items/Games/Mahjong/MahjongGame.cs @@ -76,7 +76,7 @@ namespace Server.Engines.Mahjong m_SpectatorVision = value; if (Players.IsInGamePlayer(Players.DealerPosition)) - Players.Dealer.Send(new MahjongGeneralInfo(this)); + MahjongPackets.SendMahjongGeneralInfo(Players.Dealer.NetState, this); Players.SendTilesPacket(false, true); @@ -292,4 +292,4 @@ namespace Server.Engines.Mahjong } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Games/Mahjong/MahjongPacketHandlers.cs b/Projects/Scripts/Items/Games/Mahjong/MahjongPacketHandlers.cs index 9683f3363..d3a69f0cd 100644 --- a/Projects/Scripts/Items/Games/Mahjong/MahjongPacketHandlers.cs +++ b/Projects/Scripts/Items/Games/Mahjong/MahjongPacketHandlers.cs @@ -6,7 +6,7 @@ namespace Server.Engines.Mahjong public sealed class MahjongPacketHandlers { - private static OnMahjongPacketReceive[] m_SubCommandDelegates = new OnMahjongPacketReceive[0x100]; + private static readonly OnMahjongPacketReceive[] m_SubCommandDelegates = new OnMahjongPacketReceive[0x100]; public static void RegisterSubCommand(int subCmd, OnMahjongPacketReceive onReceive) { @@ -80,12 +80,7 @@ namespace Server.Engines.Mahjong public static void ExitGame(MahjongGame game, NetState state, PacketReader pvSrc) { - if (game == null) - return; - - Mobile from = state.Mobile; - - game.Players.LeaveGame(from); + game?.Players.LeaveGame(state.Mobile); } public static void GivePoints(MahjongGame game, NetState state, PacketReader pvSrc) @@ -230,4 +225,4 @@ namespace Server.Engines.Mahjong game.DealerIndicator.Move(new Point2D(x, y), direction, wind); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Games/Mahjong/MahjongPlayers.cs b/Projects/Scripts/Items/Games/Mahjong/MahjongPlayers.cs index dfb2f99bc..0bd9501c7 100644 --- a/Projects/Scripts/Items/Games/Mahjong/MahjongPlayers.cs +++ b/Projects/Scripts/Items/Games/Mahjong/MahjongPlayers.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; namespace Server.Engines.Mahjong { @@ -82,28 +83,13 @@ namespace Server.Engines.Mahjong return m_InGame[index]; } - public bool IsInGamePlayer(Mobile mobile) - { - int index = GetPlayerIndex(mobile); - - return IsInGamePlayer(index); - } + public bool IsInGamePlayer(Mobile mobile) => IsInGamePlayer(GetPlayerIndex(mobile)); public bool IsSpectator(Mobile mobile) => m_Spectators.Contains(mobile); - public int GetScore(int index) - { - if (index < 0 || index >= m_Scores.Length) - return 0; - return m_Scores[index]; - } + public bool IsSpectator(Mobile mobile) => m_Spectators.Contains(mobile); - public bool IsPublic(int index) - { - if (index < 0 || index >= m_PublicHand.Length) - return false; - return m_PublicHand[index]; - } + public bool IsPublic(int index) => index >= 0 && index < m_PublicHand.Length && m_PublicHand[index]; public void SetPublic(int index, bool value) { @@ -122,10 +108,7 @@ namespace Server.Engines.Mahjong { List list = new List(); - if (players) - for (int i = 0; i < m_Players.Length; i++) - if (IsInGamePlayer(i)) - list.Add(m_Players[i]); + if (players) list.AddRange(m_Players.Where((t, i) => IsInGamePlayer(i))); if (spectators) list.AddRange(m_Spectators); @@ -169,7 +152,7 @@ namespace Server.Engines.Mahjong { m_InGame[i] = false; - player.Send(new MahjongRelieve(Game)); + MahjongPackets.SendMahjongRelieve(player.NetState, Game); SendPlayerExitMessage(player); UpdateDealer(true); @@ -184,20 +167,16 @@ namespace Server.Engines.Mahjong Mobile mobile = m_Spectators[i]; if (mobile.NetState == null || mobile.Deleted) - { m_Spectators.RemoveAt(i); - } else if (!Game.IsAccessibleTo(mobile) || mobile.Map != Game.Map || !mobile.InRange(Game.GetWorldLocation(), 5)) { m_Spectators.RemoveAt(i); - mobile.Send(new MahjongRelieve(Game)); + MahjongPackets.SendMahjongRelieve(mobile.NetState, Game); } else - { i++; - } } if (removed && !UpdateSpectators()) @@ -276,12 +255,12 @@ namespace Server.Engines.Mahjong UpdateDealer(false); if (sendJoinGame) - player.Send(new MahjongJoinGame(Game)); + MahjongPackets.SendMahjongJoinGame(player.NetState, Game); SendPlayersPacket(true, true); - player.Send(new MahjongGeneralInfo(Game)); - player.Send(new MahjongTilesInfo(Game, player)); + MahjongPackets.SendMahjongGeneralInfo(player.NetState, Game); + MahjongPackets.SendMahjongTilesInfo(player.NetState, Game, player); if (DealerPosition == index) SendLocalizedMessage(1062773, player.Name); // ~1_name~ has entered the game as the dealer. @@ -289,14 +268,14 @@ namespace Server.Engines.Mahjong SendLocalizedMessage(1062772, player.Name); // ~1_name~ has entered the game as a player. } - private void AddSpectator(Mobile mobile) + private void AddSpectator(Mobile m) { - if (!IsSpectator(mobile)) m_Spectators.Add(mobile); + if (!IsSpectator(m)) m_Spectators.Add(m); - mobile.Send(new MahjongJoinGame(Game)); - mobile.Send(new MahjongPlayersInfo(Game, mobile)); - mobile.Send(new MahjongGeneralInfo(Game)); - mobile.Send(new MahjongTilesInfo(Game, mobile)); + MahjongPackets.SendMahjongJoinGame(m.NetState, Game); + MahjongPackets.SendMahjongPlayersInfo(m.NetState, Game, m); + MahjongPackets.SendMahjongGeneralInfo(m.NetState, Game); + MahjongPackets.SendMahjongTilesInfo(m.NetState, Game, m); } public void Join(Mobile mobile) @@ -304,9 +283,7 @@ namespace Server.Engines.Mahjong int index = GetPlayerIndex(mobile); if (index >= 0) - { AddPlayer(mobile, index, true); - } else { int nextSeat = GetNextSeat(); @@ -331,9 +308,7 @@ namespace Server.Engines.Mahjong SendPlayersPacket(true, true); } else - { m_Spectators.Remove(player); - } } public void ResetScores(int value) @@ -357,13 +332,11 @@ namespace Server.Engines.Mahjong m_Scores[toPosition] += amount; if (Game.ShowScores) - { SendPlayersPacket(true, true); - } else { - from.Send(new MahjongPlayersInfo(Game, from)); - to.Send(new MahjongPlayersInfo(Game, to)); + MahjongPackets.SendMahjongPlayersInfo(from.NetState, Game, from); + MahjongPackets.SendMahjongPlayersInfo(to.NetState, Game, to); } SendLocalizedMessage(1062774, @@ -377,7 +350,7 @@ namespace Server.Engines.Mahjong return; if (m_InGame[index]) - player.Send(new MahjongRelieve(Game)); + MahjongPackets.SendMahjongRelieve(player.NetState, Game); m_Players[index] = null; @@ -401,9 +374,9 @@ namespace Server.Engines.Mahjong DealerPosition = index; if (IsInGamePlayer(oldDealer)) - m_Players[oldDealer].Send(new MahjongPlayersInfo(Game, m_Players[oldDealer])); + MahjongPackets.SendMahjongPlayersInfo(m_Players[oldDealer].NetState, Game, m_Players[oldDealer]); - to.Send(new MahjongPlayersInfo(Game, to)); + MahjongPackets.SendMahjongPlayersInfo(to.NetState, Game, to); SendDealerChangedMessage(); } @@ -422,36 +395,25 @@ namespace Server.Engines.Mahjong public void SendPlayersPacket(bool players, bool spectators) { foreach (Mobile mobile in GetInGameMobiles(players, spectators)) - mobile.Send(new MahjongPlayersInfo(Game, mobile)); + MahjongPackets.SendMahjongPlayersInfo(mobile.NetState, Game, mobile); } public void SendGeneralPacket(bool players, bool spectators) { - List mobiles = GetInGameMobiles(players, spectators); - - if (mobiles.Count == 0) - return; - - MahjongGeneralInfo generalInfo = new MahjongGeneralInfo(Game); - - generalInfo.Acquire(); - - foreach (Mobile mobile in mobiles) - mobile.Send(generalInfo); - - generalInfo.Release(); + foreach (Mobile mobile in GetInGameMobiles(players, spectators)) + MahjongPackets.SendMahjongGeneralInfo(mobile.NetState, Game); } public void SendTilesPacket(bool players, bool spectators) { foreach (Mobile mobile in GetInGameMobiles(players, spectators)) - mobile.Send(new MahjongTilesInfo(Game, mobile)); + MahjongPackets.SendMahjongTilesInfo(mobile.NetState, Game, mobile); } public void SendTilePacket(MahjongTile tile, bool players, bool spectators) { foreach (Mobile mobile in GetInGameMobiles(players, spectators)) - mobile.Send(new MahjongTileInfo(tile, mobile)); + MahjongPackets.SendMahjongTileInfo(mobile.NetState, tile, mobile); } public void SendRelievePacket(bool players, bool spectators) @@ -461,14 +423,8 @@ namespace Server.Engines.Mahjong if (mobiles.Count == 0) return; - MahjongRelieve relieve = new MahjongRelieve(Game); - - relieve.Acquire(); - foreach (Mobile mobile in mobiles) - mobile.Send(relieve); - - relieve.Release(); + MahjongPackets.SendMahjongRelieve(mobile.NetState, Game); } public void SendLocalizedMessage(int number) diff --git a/Projects/Scripts/Items/Games/Mahjong/Packets.cs b/Projects/Scripts/Items/Games/Mahjong/Packets.cs index 39be5ea77..235083757 100644 --- a/Projects/Scripts/Items/Games/Mahjong/Packets.cs +++ b/Projects/Scripts/Items/Games/Mahjong/Packets.cs @@ -1,76 +1,78 @@ -using System.IO; +using Server.Buffers; using Server.Network; namespace Server.Engines.Mahjong { - public sealed class MahjongJoinGame : Packet + public static class MahjongPackets { - public MahjongJoinGame(MahjongGame game) : base(0xDA) + public static void SendMahjongJoinGame(NetState ns, MahjongGame game) { - EnsureCapacity(9); + if (ns == null) + return; - m_Stream.Write(game.Serial); - m_Stream.Write((byte)0); - m_Stream.Write((byte)0x19); + SpanWriter writer = new SpanWriter(stackalloc byte[9]); + writer.Write((byte)0xDA); // Packet ID + writer.Write((ushort)0x09); // Dynamic Length + + writer.Write(game.Serial); + writer.Write((short)0x19); + + ns.Send(writer.Span); } - } - public sealed class MahjongPlayersInfo : Packet - { - public MahjongPlayersInfo(MahjongGame game, Mobile to) : base(0xDA) + public static void SendMahjongPlayersInfo(NetState ns, MahjongGame game, Mobile to) { + if (ns == null) + return; + MahjongPlayers players = game.Players; + SpanWriter writer = new SpanWriter(stackalloc byte[11 + 45 * players.Seats]); + writer.Write((byte)0xDA); // Packet ID + writer.Position += 2; // Dynamic Length - EnsureCapacity(11 + 45 * players.Seats); + writer.Write(game.Serial); + writer.Write((short)0x02); + writer.Write((short)players.Seats); - m_Stream.Write(game.Serial); - m_Stream.Write((byte)0); - m_Stream.Write((byte)0x2); - - m_Stream.Write((byte)0); - m_Stream.Write((byte)players.Seats); - - int n = 0; + short n = 0; for (int i = 0; i < players.Seats; i++) { Mobile mobile = players.GetPlayer(i); if (mobile != null) { - m_Stream.Write(mobile.Serial); - m_Stream.Write(players.DealerPosition == i ? (byte)0x1 : (byte)0x2); - m_Stream.Write((byte)i); + writer.Write(mobile.Serial); + writer.Write(players.DealerPosition == i ? (byte)0x1 : (byte)0x2); + writer.Write((byte)i); if (game.ShowScores || mobile == to) - m_Stream.Write(players.GetScore(i)); + writer.Write(players.GetScore(i)); else - m_Stream.Write(0); + writer.Position++; // writer.Write(0); - m_Stream.Write((short)0); - m_Stream.Write((byte)0); + writer.Position += 3; - m_Stream.Write(players.IsPublic(i)); + writer.Write(players.IsPublic(i)); - m_Stream.WriteAsciiFixed(mobile.Name, 30); - m_Stream.Write(!players.IsInGamePlayer(i)); + writer.WriteAsciiFixed(mobile.Name, 30); + writer.Write(!players.IsInGamePlayer(i)); n++; } else if (game.ShowScores) { - m_Stream.Write(0); - m_Stream.Write((byte)0x2); - m_Stream.Write((byte)i); + writer.Position++; // writer.Write(0); + writer.Write((byte)0x2); + writer.Write((byte)i); - m_Stream.Write(players.GetScore(i)); + writer.Write(players.GetScore(i)); - m_Stream.Write((short)0); - m_Stream.Write((byte)0); + writer.Position += 3; - m_Stream.Write(players.IsPublic(i)); + writer.Write(players.IsPublic(i)); - m_Stream.WriteAsciiFixed("", 30); - m_Stream.Write(true); + writer.Position += 30; //writer.WriteAsciiFixed("", 30); + writer.Write((byte)0x1); // true n++; } @@ -78,58 +80,66 @@ namespace Server.Engines.Mahjong if (n != players.Seats) { - m_Stream.Seek(10, SeekOrigin.Begin); - m_Stream.Write((byte)n); + writer.Position = 9; + writer.Write(n); } + + writer.Position = 1; + writer.Write((short)writer.WrittenCount); + ns.Send(writer.Span); } - } - public sealed class MahjongGeneralInfo : Packet - { - public MahjongGeneralInfo(MahjongGame game) : base(0xDA) + public static void SendMahjongGeneralInfo(NetState ns, MahjongGame game) { - EnsureCapacity(13); + if (ns == null) + return; - m_Stream.Write(game.Serial); - m_Stream.Write((byte)0); - m_Stream.Write((byte)0x5); + SpanWriter writer = new SpanWriter(stackalloc byte[25]); + writer.Write((byte)0xDA); // Packet ID + writer.Write((ushort)25); // Dynamic Length - m_Stream.Write((short)0); - m_Stream.Write((byte)0); + writer.Write(game.Serial); + writer.Write((short)0x05); - m_Stream.Write((byte)((game.ShowScores ? 0x1 : 0x0) | (game.SpectatorVision ? 0x2 : 0x0))); + writer.Position += 3; - m_Stream.Write((byte)game.Dices.First); - m_Stream.Write((byte)game.Dices.Second); + writer.Write((byte)((game.ShowScores ? 0x1 : 0x0) | (game.SpectatorVision ? 0x2 : 0x0))); - m_Stream.Write((byte)game.DealerIndicator.Wind); - m_Stream.Write((short)game.DealerIndicator.Position.Y); - m_Stream.Write((short)game.DealerIndicator.Position.X); - m_Stream.Write((byte)game.DealerIndicator.Direction); + writer.Write((byte)game.Dices.First); + writer.Write((byte)game.Dices.Second); - m_Stream.Write((short)game.WallBreakIndicator.Position.Y); - m_Stream.Write((short)game.WallBreakIndicator.Position.X); + writer.Write((byte)game.DealerIndicator.Wind); + writer.Write((short)game.DealerIndicator.Position.Y); + writer.Write((short)game.DealerIndicator.Position.X); + writer.Write((byte)game.DealerIndicator.Direction); + + writer.Write((short)game.WallBreakIndicator.Position.Y); + writer.Write((short)game.WallBreakIndicator.Position.X); + + ns.Send(writer.Span); } - } - public sealed class MahjongTilesInfo : Packet - { - public MahjongTilesInfo(MahjongGame game, Mobile to) : base(0xDA) + public static void SendMahjongTilesInfo(NetState ns, MahjongGame game, Mobile to) { + if (ns == null) + return; + MahjongTile[] tiles = game.Tiles; MahjongPlayers players = game.Players; - EnsureCapacity(11 + 9 * tiles.Length); + int length = 11 + 9 * tiles.Length; + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0xDA); // Packet ID + writer.Write((short)length); // Dynamic Length - m_Stream.Write(game.Serial); - m_Stream.Write((byte)0); - m_Stream.Write((byte)0x4); + writer.Write(game.Serial); + writer.Write((short)0x4); - m_Stream.Write((short)tiles.Length); + writer.Write((short)tiles.Length); foreach (MahjongTile tile in tiles) { - m_Stream.Write((byte)tile.Number); + writer.Write((byte)tile.Number); if (tile.Flipped) { @@ -137,39 +147,40 @@ namespace Server.Engines.Mahjong if (hand < 0 || players.IsPublic(hand) || players.GetPlayer(hand) == to || game.SpectatorVision && players.IsSpectator(to)) - m_Stream.Write((byte)tile.Value); + writer.Write((byte)tile.Value); else - m_Stream.Write((byte)0); + writer.Position++; } else - { - m_Stream.Write((byte)0); - } + writer.Position++; - m_Stream.Write((short)tile.Position.Y); - m_Stream.Write((short)tile.Position.X); - m_Stream.Write((byte)tile.StackLevel); - m_Stream.Write((byte)tile.Direction); + writer.Write((short)tile.Position.Y); + writer.Write((short)tile.Position.X); + writer.Write((byte)tile.StackLevel); + writer.Write((byte)tile.Direction); - m_Stream.Write(tile.Flipped ? (byte)0x10 : (byte)0x0); + writer.Write(tile.Flipped ? (byte)0x10 : (byte)0x0); } - } - } - public sealed class MahjongTileInfo : Packet - { - public MahjongTileInfo(MahjongTile tile, Mobile to) : base(0xDA) + ns.Send(writer.Span); + } + + public static void SendMahjongTileInfo(NetState ns, MahjongTile tile, Mobile to) { + if (ns == null) + return; + MahjongGame game = tile.Game; MahjongPlayers players = game.Players; - EnsureCapacity(18); + SpanWriter writer = new SpanWriter(stackalloc byte[18]); + writer.Write((byte)0xDA); // Packet ID + writer.Write((short)18); // Dynamic Length - m_Stream.Write(tile.Game.Serial); - m_Stream.Write((byte)0); - m_Stream.Write((byte)0x3); + writer.Write(game.Serial); + writer.Write((short)0x3); - m_Stream.Write((byte)tile.Number); + writer.Write((byte)tile.Number); if (tile.Flipped) { @@ -177,33 +188,36 @@ namespace Server.Engines.Mahjong if (hand < 0 || players.IsPublic(hand) || players.GetPlayer(hand) == to || game.SpectatorVision && players.IsSpectator(to)) - m_Stream.Write((byte)tile.Value); + writer.Write((byte)tile.Value); else - m_Stream.Write((byte)0); + writer.Position++; } else - { - m_Stream.Write((byte)0); - } + writer.Position++; - m_Stream.Write((short)tile.Position.Y); - m_Stream.Write((short)tile.Position.X); - m_Stream.Write((byte)tile.StackLevel); - m_Stream.Write((byte)tile.Direction); + writer.Write((short)tile.Position.Y); + writer.Write((short)tile.Position.X); + writer.Write((byte)tile.StackLevel); + writer.Write((byte)tile.Direction); - m_Stream.Write(tile.Flipped ? (byte)0x10 : (byte)0x0); + writer.Write(tile.Flipped ? (byte)0x10 : (byte)0x0); + + ns.Send(writer.Span); } - } - public sealed class MahjongRelieve : Packet - { - public MahjongRelieve(MahjongGame game) : base(0xDA) + public static void SendMahjongRelieve(NetState ns, MahjongGame game) { - EnsureCapacity(9); + if (ns == null) + return; - m_Stream.Write(game.Serial); - m_Stream.Write((byte)0); - m_Stream.Write((byte)0x1A); + SpanWriter writer = new SpanWriter(stackalloc byte[18]); + writer.Write((byte)0xDA); // Packet ID + writer.Write((short)18); // Dynamic Length + + writer.Write(game.Serial); + writer.Write((short)0x1A); + + ns.Send(writer.Span); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Guilds/GuildDeed.cs b/Projects/Scripts/Items/Guilds/GuildDeed.cs index ea4197781..139077068 100644 --- a/Projects/Scripts/Items/Guilds/GuildDeed.cs +++ b/Projects/Scripts/Items/Guilds/GuildDeed.cs @@ -1,6 +1,5 @@ using Server.Guilds; using Server.Multis; -using Server.Prompts; namespace Server.Items { diff --git a/Projects/Scripts/Items/Guilds/Guildstone.cs b/Projects/Scripts/Items/Guilds/Guildstone.cs index c02b0cca4..3a34fdb7f 100644 --- a/Projects/Scripts/Items/Guilds/Guildstone.cs +++ b/Projects/Scripts/Items/Guilds/Guildstone.cs @@ -143,8 +143,7 @@ namespace Server.Items if (Guild.NewGuildSystem && ItemID == 0xED4) ItemID = 0xED6; - if (version <= 2) - m_BeforeChangeover = true; + m_BeforeChangeover |= version <= 2; if (Guild.NewGuildSystem && m_BeforeChangeover) Timer.DelayCall(TimeSpan.Zero, AddToHouse); @@ -251,10 +250,8 @@ namespace Server.Items from.SendGump(new GuildGump(from, Guild)); } else if (from.AccessLevel < AccessLevel.GameMaster && !Guild.IsMember(from)) - { - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Regular, 0x3B2, 3, 501158, "", - "")); // You are not a member ... - } + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Regular, 0x3B2, 3, + 501158); // You are not a member ... else { GuildGump.EnsureClosed(from); @@ -262,8 +259,6 @@ namespace Server.Items } } - #region IAddon Members - public Item Deed => new GuildstoneDeed(Guild, m_GuildName, m_GuildAbbrev); public bool CouldFit(IPoint3D p, Map map) => map.CanFit(p.X, p.Y, p.Z, ItemData.Height); @@ -376,9 +371,7 @@ namespace Server.Items list.Add(1060802, $"{Utility.FixHtml(name)} [{Utility.FixHtml(abbr)}]"); } else if (m_GuildName != null && m_GuildAbbrev != null) - { list.Add(1060802, $"{Utility.FixHtml(m_GuildName)} [{Utility.FixHtml(m_GuildAbbrev)}]"); - } } public override void OnDoubleClick(Mobile from) @@ -393,14 +386,10 @@ namespace Server.Items from.BeginTarget(-1, true, TargetFlags.None, Placement_OnTarget); } else - { from.SendLocalizedMessage(502092); // You must be in your house to do this. - } } else - { from.SendLocalizedMessage(1042001); // That must be in your pack for you to use it. - } } public void Placement_OnTarget(Mobile from, object targeted) @@ -424,14 +413,10 @@ namespace Server.Items Delete(); } else - { from.SendLocalizedMessage(1042036); // That location is not in your house. - } } else - { from.SendLocalizedMessage(1042001); // That must be in your pack for you to use it. - } } } } diff --git a/Projects/Scripts/Items/Maps/IndecipherableMap.cs b/Projects/Scripts/Items/Maps/IndecipherableMap.cs index 9cc9dfe9d..051e14fcb 100644 --- a/Projects/Scripts/Items/Maps/IndecipherableMap.cs +++ b/Projects/Scripts/Items/Maps/IndecipherableMap.cs @@ -3,13 +3,7 @@ namespace Server.Items public class IndecipherableMap : MapItem { [Constructible] - public IndecipherableMap() - { - if (Utility.RandomDouble() < 0.2) - Hue = 0x965; - else - Hue = 0x961; - } + public IndecipherableMap() => Hue = Utility.RandomDouble() < 0.2 ? 0x965 : 0x961; public IndecipherableMap(Serial serial) : base(serial) { @@ -36,4 +30,4 @@ namespace Server.Items int version = reader.ReadEncodedInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Maps/MapItem.cs b/Projects/Scripts/Items/Maps/MapItem.cs index d60d321cd..106f50e15 100644 --- a/Projects/Scripts/Items/Maps/MapItem.cs +++ b/Projects/Scripts/Items/Maps/MapItem.cs @@ -10,14 +10,16 @@ namespace Server.Items { private const int MaxUserPins = 50; private bool m_Editable; + private Map m_Facet; [Constructible] - public MapItem() : base(0x14EC) + public MapItem(Map facet = null) : base(0x14EC) { Weight = 1.0; Width = 200; Height = 200; + m_Facet = facet; } public MapItem(Serial serial) : base(serial) @@ -38,6 +40,13 @@ namespace Server.Items public List Pins{ get; } = new List(); + [CommandProperty(AccessLevel.GameMaster)] + public virtual Map Facet + { + get => m_Facet; + set => m_Facet = value; + } + #region ICraftable Members public int OnCraft(int quality, bool makersMark, Mobile from, CraftSystem craftSystem, Type typeRes, BaseTool tool, @@ -83,13 +92,24 @@ namespace Server.Items public virtual void DisplayTo(Mobile from) { - from.Send(new MapDetails(this)); - from.Send(new MapDisplay(this)); + NetState ns = from.NetState; + + if (ns.NewCharacterList) // 7.0.13.0+ supports maps on all facets + MapItemPackets.SendMapDetailsNew(ns, this); + else if (Facet != null && Facet != Map.Felucca && Facet != Map.Trammel) // Is it Felucca and Trammel, or just Felucca? + { + from.SendMessage("You must have client 7.0.13.0 or higher to display this map."); + return; + } + else + MapItemPackets.SendMapDetailsOld(ns, this); + + MapItemPackets.SendMapDisplay(from.NetState, this); for (int i = 0; i < Pins.Count; ++i) - from.Send(new MapAddPin(this, Pins[i])); + MapItemPackets.SendMapAddPin(from.NetState, this, Pins[i]); - from.Send(new MapSetEditable(this, ValidateEdit(from))); + MapItemPackets.SendMapSetEditable(from.NetState, this, ValidateEdit(from)); } public virtual void OnAddPin(Mobile from, int x, int y) @@ -144,7 +164,7 @@ namespace Server.Items if (Validate(from)) m_Editable = !m_Editable; - from.Send(new MapSetEditable(this, Validate(from) && m_Editable)); + MapItemPackets.SendMapSetEditable(from.NetState, this, m_Editable && ValidateEdit(from)); } public virtual void Validate(ref int x, ref int y) @@ -226,7 +246,9 @@ namespace Server.Items { base.Serialize(writer); - writer.Write(0); + writer.Write(1); + + writer.Write(m_Facet); writer.Write(Bounds); @@ -248,6 +270,9 @@ namespace Server.Items switch (version) { + case 1: + m_Facet = reader.ReadMap(); + goto case 0; case 0: { Bounds = reader.ReadRect2D(); @@ -306,71 +331,5 @@ namespace Server.Items break; } } - - private sealed class MapDetails : Packet - { - public MapDetails(MapItem map) : base(0x90, 19) - { - m_Stream.Write(map.Serial); - m_Stream.Write((short)0x139D); - m_Stream.Write((short)map.Bounds.Start.X); - m_Stream.Write((short)map.Bounds.Start.Y); - m_Stream.Write((short)map.Bounds.End.X); - m_Stream.Write((short)map.Bounds.End.Y); - m_Stream.Write((short)map.Width); - m_Stream.Write((short)map.Height); - } - } - - /* - private sealed class MapDetailsNew : Packet - { - public MapDetailsNew( MapItem map ) : base ( 0xF5, 21 ) - { - m_Stream.Write( (int) map.Serial ); - m_Stream.Write( (short) 0x139D ); - m_Stream.Write( (short) map.Bounds.Start.X ); - m_Stream.Write( (short) map.Bounds.Start.Y ); - m_Stream.Write( (short) map.Bounds.End.X ); - m_Stream.Write( (short) map.Bounds.End.Y ); - m_Stream.Write( (short) map.Width ); - m_Stream.Write( (short) map.Height ); - m_Stream.Write( (short) ( map.Facet == null ? 0 : map.Facet.MapID ) ); - } - } - */ - - private abstract class MapCommand : Packet - { - public MapCommand(MapItem map, int command, int number, int x, int y) : base(0x56, 11) - { - m_Stream.Write(map.Serial); - m_Stream.Write((byte)command); - m_Stream.Write((byte)number); - m_Stream.Write((short)x); - m_Stream.Write((short)y); - } - } - - private sealed class MapDisplay : MapCommand - { - public MapDisplay(MapItem map) : base(map, 5, 0, 0, 0) - { - } - } - - private sealed class MapAddPin : MapCommand - { - public MapAddPin(MapItem map, Point2D point) : base(map, 1, 0, point.X, point.Y) - { - } - } - - private sealed class MapSetEditable : MapCommand - { - public MapSetEditable(MapItem map, bool editable) : base(map, 7, editable ? 1 : 0, 0, 0) - { - } - } } } diff --git a/Projects/Scripts/Items/Maps/Packets.cs b/Projects/Scripts/Items/Maps/Packets.cs new file mode 100644 index 000000000..77d0805f4 --- /dev/null +++ b/Projects/Scripts/Items/Maps/Packets.cs @@ -0,0 +1,81 @@ +using Server.Buffers; +using Server.Items; + +namespace Server.Network +{ + public static class MapItemPackets + { + public static void SendMapDetailsOld(NetState ns, MapItem map) + { + if (ns == null) + return; + + SpanWriter writer = new SpanWriter(stackalloc byte[19]); + writer.Write((byte)0x90); // Packet ID + + writer.Write(map.Serial); + writer.Write((short)0x139D); + writer.Write((short)map.Bounds.Start.X); + writer.Write((short)map.Bounds.Start.Y); + writer.Write((short)map.Bounds.End.X); + writer.Write((short)map.Bounds.End.Y); + writer.Write((short)map.Width); + writer.Write((short)map.Height); + + ns.Send(writer.Span); + } + + public static void SendMapDetailsNew(NetState ns, MapItem map) + { + if (ns == null) + return; + + SpanWriter writer = new SpanWriter(stackalloc byte[21]); + writer.Write((byte)0xF5); // Packet ID + + writer.Write(map.Serial); + writer.Write((short)0x139D); + writer.Write((short)map.Bounds.Start.X); + writer.Write((short)map.Bounds.Start.Y); + writer.Write((short)map.Bounds.End.X); + writer.Write((short)map.Bounds.End.Y); + writer.Write((short)map.Width); + writer.Write((short)map.Height); + writer.Write( (short)(map.Facet?.MapID ?? 0) ); + + ns.Send(writer.Span); + } + + public static void SendMapDisplay(NetState ns, MapItem map) + { + SendMapCommand(ns, map, 5); + } + + public static void SendMapAddPin(NetState ns, MapItem map, Point2D p) + { + SendMapCommand(ns, map, 1, 0, p.X, p.Y); + } + + public static void SendMapSetEditable(NetState ns, MapItem map, bool editable) + { + SendMapCommand(ns, map, 7, editable ? 1 : 0); + } + + public static void SendMapCommand(NetState ns, MapItem map, int command, int number = 0, int x = 0, int y = 0) + { + if (ns == null) + return; + + SpanWriter writer = new SpanWriter(stackalloc byte[11]); + writer.Write((byte)0x56); // Packet ID + + writer.Write(map.Serial); + writer.Write((byte)command); + writer.Write((byte)number); + writer.Write((short)x); + writer.Write((short)y); + + ns.Send(writer.Span); + } + } +} diff --git a/Projects/Scripts/Items/Maps/PresetMap.cs b/Projects/Scripts/Items/Maps/PresetMap.cs index 9f79db312..5039220e3 100644 --- a/Projects/Scripts/Items/Maps/PresetMap.cs +++ b/Projects/Scripts/Items/Maps/PresetMap.cs @@ -78,7 +78,7 @@ namespace Server.Items public Rectangle2D Bounds{ get; } - public static PresetMapEntry[] Table{ get; } = + public static readonly PresetMapEntry[] Table = { new PresetMapEntry(1041189, 200, 200, 1092, 1396, 1736, 1924), // map of Britain new PresetMapEntry(1041203, 200, 200, 0256, 1792, 1736, 2560), // map of Britain to Skara Brae @@ -142,4 +142,4 @@ namespace Server.Items Yew, YewToBritain } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Maps/TreasureMap.cs b/Projects/Scripts/Items/Maps/TreasureMap.cs index 066f240eb..de2815a90 100644 --- a/Projects/Scripts/Items/Maps/TreasureMap.cs +++ b/Projects/Scripts/Items/Maps/TreasureMap.cs @@ -17,7 +17,7 @@ namespace Server.Items private static Point2D[] m_Locations; private static Point2D[] m_HavenLocations; - private static Type[][] m_SpawnTypes = + private static readonly Type[][] m_SpawnTypes = { new[] { typeof(HeadlessOne), typeof(Skeleton) }, new[] { typeof(Mongbat), typeof(Ratman), typeof(HeadlessOne), typeof(Skeleton), typeof(Zombie) }, @@ -32,18 +32,13 @@ namespace Server.Items private Mobile m_CompletedBy; private Mobile m_Decoder; private int m_Level; - private Map m_Map; [Constructible] - public TreasureMap(int level, Map map) + public TreasureMap(int level, Map facet = null) : base(facet) { m_Level = level; - m_Map = map; - if (level == 0) - ChestLocation = GetRandomHavenLocation(); - else - ChestLocation = GetRandomLocation(); + ChestLocation = level == 0 ? GetRandomHavenLocation() : GetRandomLocation(); Width = 300; Height = 300; @@ -127,12 +122,12 @@ namespace Server.Items } [CommandProperty(AccessLevel.GameMaster)] - public Map ChestMap + public override Map Facet { - get => m_Map; + get => base.Facet; set { - m_Map = value; + base.Facet = value; InvalidateProperties(); } } @@ -145,15 +140,9 @@ namespace Server.Items get { if (m_Decoder != null) - { - if (m_Level == 6) - return 1063453; - return 1041516 + m_Level; - } + return m_Level == 6 ? 1063453 : 1041516 + m_Level; - if (m_Level == 6) - return 1063452; - return 1041510 + m_Level; + return m_Level == 6 ? 1063452 : 1041510 + m_Level; } } @@ -162,10 +151,8 @@ namespace Server.Items if (m_Locations == null) LoadLocations(); - if (m_Locations.Length > 0) - return m_Locations[Utility.Random(m_Locations.Length)]; - - return Point2D.Zero; + // ReSharper disable once PossibleNullReferenceException + return m_Locations.Length > 0 ? m_Locations[Utility.Random(m_Locations.Length)] : Point2D.Zero; } public static Point2D GetRandomHavenLocation() @@ -173,10 +160,8 @@ namespace Server.Items if (m_HavenLocations == null) LoadLocations(); - if (m_HavenLocations.Length > 0) - return m_HavenLocations[Utility.Random(m_HavenLocations.Length)]; - - return Point2D.Zero; + // ReSharper disable once PossibleNullReferenceException + return m_HavenLocations.Length > 0 ? m_HavenLocations[Utility.Random(m_HavenLocations.Length)] : Point2D.Zero; } private static void LoadLocations() @@ -325,7 +310,7 @@ namespace Server.Items { from.SendLocalizedMessage(503020); // You are already digging treasure. } - else if (from.Map != m_Map) + else if (from.Map != Facet) { from.SendLocalizedMessage(1010479); // You seem to be in the right place, but may be on the wrong facet! } @@ -473,7 +458,7 @@ namespace Server.Items { base.GetProperties(list); - list.Add(m_Map == Map.Felucca ? 1041502 : 1041503); // for somewhere in Felucca : for somewhere in Trammel + list.Add(Facet == Map.Felucca ? 1041502 : 1041503); // for somewhere in Felucca : for somewhere in Trammel if (m_Completed) list.Add(1041507, m_CompletedBy == null ? "someone" : m_CompletedBy.Name); // completed by ~1_val~ @@ -483,9 +468,8 @@ namespace Server.Items { if (m_Completed) { - from.Send(new MessageLocalizedAffix(Serial, ItemID, MessageType.Label, 0x3B2, 3, 1048030, "", - AffixType.Append, - $" completed by {(m_CompletedBy == null ? "someone" : m_CompletedBy.Name)}", "")); + Packets.SendMessageLocalizedAffix(from.NetState, Serial, ItemID, MessageType.Label, 0x3B2, 3, 1048030, "", + AffixType.Append, $" completed by {m_CompletedBy?.Name ?? "someone"}"); } else if (m_Decoder != null) { @@ -496,10 +480,10 @@ namespace Server.Items } else { - if (m_Level == 6) - LabelTo(from, 1041522, $"#{1063452}\t \t#{(m_Map == Map.Felucca ? 1041502 : 1041503)}"); - else - LabelTo(from, 1041522, $"#{1041510 + m_Level}\t \t#{(m_Map == Map.Felucca ? 1041502 : 1041503)}"); + LabelTo(from, 1041522, + m_Level == 6 + ? $"#{1063452}\t \t#{(Facet == Map.Felucca ? 1041502 : 1041503)}" + : $"#{1041510 + m_Level}\t \t#{(Facet == Map.Felucca ? 1041502 : 1041503)}"); } } @@ -507,14 +491,13 @@ namespace Server.Items { base.Serialize(writer); - writer.Write(1); + writer.Write(2); writer.Write(m_CompletedBy); writer.Write(m_Level); writer.Write(m_Completed); writer.Write(m_Decoder); - writer.Write(m_Map); writer.Write(ChestLocation); } @@ -537,7 +520,8 @@ namespace Server.Items m_Level = reader.ReadInt(); m_Completed = reader.ReadBool(); m_Decoder = reader.ReadMobile(); - m_Map = reader.ReadMap(); + if (version < 2) + Facet = reader.ReadMap(); ChestLocation = reader.ReadPoint2D(); if (version == 0 && m_Completed) @@ -562,12 +546,10 @@ namespace Server.Items if (m_Map.Deleted) return; - Map map = m_Map.m_Map; + Map facet = m_Map.Facet; if (m_Map.m_Completed) - { from.SendLocalizedMessage(503028); // The treasure for this map has already been found. - } /* else if ( from != m_Map.m_Decoder ) { @@ -575,22 +557,14 @@ namespace Server.Items } */ else if (m_Map.m_Decoder != from && !m_Map.HasRequiredSkill(from)) - { from.SendLocalizedMessage( 503031); // You did not decode this map and have no clue where to look for the treasure. - } else if (!from.CanBeginAction()) - { from.SendLocalizedMessage(503020); // You are already digging treasure. - } else if (!HasDiggingTool(from)) - { - from.SendMessage("You must have a digging tool to dig for treasure."); - } - else if (from.Map != map) - { + from.SendLocalizedMessage(1114416); // You must have a digging tool to dig for treasure. + else if (from.Map != facet) from.SendLocalizedMessage(1010479); // You seem to be in the right place, but may be on the wrong facet! - } else { IPoint3D p = targeted as IPoint3D; @@ -617,19 +591,17 @@ namespace Server.Items if (Utility.InRange(targ3D, chest3D0, maxRange)) { if (from.Location.X == x && from.Location.Y == y) - { from.SendLocalizedMessage( 503030); // The chest can't be dug up because you are standing on top of it. - } - else if (map != null) + else if (facet != null) { - int z = map.GetAverageZ(x, y); + int z = facet.GetAverageZ(x, y); - if (!map.CanFit(x, y, z, 16, true)) + if (!facet.CanFit(x, y, z, 16, true)) from.SendLocalizedMessage( 503021); // You have found the treasure chest but something is keeping it from being dug up. else if (from.BeginAction()) - new DigTimer(from, m_Map, new Point3D(x, y, z), map).Start(); + new DigTimer(from, m_Map, new Point3D(x, y, z), facet).Start(); else from.SendLocalizedMessage(503020); // You are already digging treasure. } @@ -644,9 +616,7 @@ namespace Server.Items else { if (Utility.InRange(targ3D, chest3D0, 8)) // We're close, but not quite - { - from.SendAsciiMessage(0x44, "The treasure chest is very close!"); - } + from.SendLocalizedMessage(1080030, "", 0x44); // The treasure chest is very close! else { Direction dir = Utility.GetDirection(targ3D, chest3D0); diff --git a/Projects/Scripts/Items/Misc/BankCheck.cs b/Projects/Scripts/Items/Misc/BankCheck.cs index a07a360dd..161c06380 100644 --- a/Projects/Scripts/Items/Misc/BankCheck.cs +++ b/Projects/Scripts/Items/Misc/BankCheck.cs @@ -1,6 +1,5 @@ using System; using System.Globalization; -using Server.Accounting; using Server.Engines.Quests; using Server.Engines.Quests.Haven; using Server.Engines.Quests.Necro; diff --git a/Projects/Scripts/Items/Misc/Blocker.cs b/Projects/Scripts/Items/Misc/Blocker.cs index b5baf8be0..87cfcce25 100644 --- a/Projects/Scripts/Items/Misc/Blocker.cs +++ b/Projects/Scripts/Items/Misc/Blocker.cs @@ -1,3 +1,4 @@ +using Server.Buffers; using Server.Network; namespace Server.Items @@ -13,14 +14,21 @@ namespace Server.Items public override int LabelNumber => 503057; // Impassable! - protected override Packet GetWorldPacketFor(NetState state) + protected override void SendWorldPacketFor(NetState state) { Mobile mob = state.Mobile; if (mob?.AccessLevel >= AccessLevel.GameMaster) - return new GMItemPacket(this); + { + if (state.HighSeas) + SendGMItemHS(state); + else if (state.StygianAbyss) + SendGMItemSA(state); + else + SendGMItem(state); + } - return base.GetWorldPacketFor(state); + base.SendWorldPacketFor(state); } public override void Serialize(GenericWriter writer) @@ -37,66 +45,138 @@ namespace Server.Items int version = reader.ReadInt(); } - public sealed class GMItemPacket : Packet + private void SendGMItem(NetState ns) { - public GMItemPacket(Item item) : base(0x1A) - { - EnsureCapacity(20); + if (ns == null) + return; - // 14 base length - // +2 - Amount - // +2 - Hue - // +1 - Flags + SpanWriter w = new SpanWriter(stackalloc byte[20]); + w.Write((byte)0x1A); // Packet ID + w.Position += 2; // Dynamic Length - uint serial = item.Serial.Value; - int itemID = 0x1183; - int amount = item.Amount; - Point3D loc = item.Location; - int x = loc.X; - int y = loc.Y; - int hue = item.Hue; - int flags = item.GetPacketFlags(); - int direction = (int)item.Direction; + uint serial = Serial.Value; + int itemId = 0x1183; + int amount = Amount; + Point3D loc = Location; + int x = loc.X; + int y = loc.Y; + int hue = Hue; + int flags = GetPacketFlags(); + int direction = (int)Direction; - if (amount != 0) - serial |= 0x80000000; - else - serial &= 0x7FFFFFFF; + if (amount != 0) + serial |= 0x80000000; + else + serial &= 0x7FFFFFFF; - m_Stream.Write(serial); - m_Stream.Write((short)(itemID & 0x7FFF)); + w.Write(serial); - if (amount != 0) - m_Stream.Write((short)amount); + w.Write((short)itemId); - x &= 0x7FFF; + if (amount != 0) + w.Write((short)amount); - if (direction != 0) - x |= 0x8000; + x &= 0x7FFF; - m_Stream.Write((short)x); + if (direction != 0) x |= 0x8000; - y &= 0x3FFF; + w.Write((short)x); - if (hue != 0) - y |= 0x8000; + y &= 0x3FFF; - if (flags != 0) - y |= 0x4000; + if (hue != 0) y |= 0x8000; - m_Stream.Write((short)y); + if (flags != 0) y |= 0x4000; - if (direction != 0) - m_Stream.Write((byte)direction); + w.Write((short)y); - m_Stream.Write((sbyte)loc.Z); + if (direction != 0) + w.Write((byte)direction); - if (hue != 0) - m_Stream.Write((ushort)hue); + w.Write((sbyte)loc.Z); - if (flags != 0) - m_Stream.Write((byte)flags); - } + if (hue != 0) + w.Write((ushort)hue); + + if (flags != 0) + w.Write((byte)flags); + + w.Position = 1; + w.Write((ushort)w.WrittenCount); + + ns.Send(w.Span); + } + + public void SendGMItemSA(NetState ns) + { + if (ns == null) + return; + + SpanWriter w = new SpanWriter(stackalloc byte[24]); + w.Write((byte)0xF3); // Packet ID + + w.Write((short)0x01); + + int itemId = 0x1183; + + w.Position++; // w.Write((byte)0); + + w.Write(Serial); + + w.Write((short)itemId); + + w.Write((byte)Direction); + + short amount = (short)Amount; + w.Write(amount); + w.Write(amount); + + Point3D loc = Location; + w.Write((short)(loc.X & 0x7FFF)); + w.Write((short)(loc.Y & 0x3FFF)); + w.Write((sbyte)loc.Z); + + w.Write((byte)Light); + w.Write((short)Hue); + w.Write((byte)GetPacketFlags()); + + ns.Send(w.RawSpan); + } + + public void SendGMItemHS(NetState ns) + { + if (ns == null) + return; + + SpanWriter w = new SpanWriter(stackalloc byte[26]); + w.Write((byte)0xF3); // Packet ID + + w.Write((short)0x01); + + int itemId = 0x1183; + + w.Position++; // w.Write((byte)0); + + w.Write(Serial); + + w.Write((short)itemId); + + w.Write((byte)Direction); + + short amount = (short)Amount; + w.Write(amount); + w.Write(amount); + + Point3D loc = Location; + w.Write((short)(loc.X & 0x7FFF)); + w.Write((short)(loc.Y & 0x3FFF)); + w.Write((sbyte)loc.Z); + + w.Write((byte)Light); + w.Write((short)Hue); + w.Write((byte)GetPacketFlags()); + + ns.Send(w.RawSpan); } } } diff --git a/Projects/Scripts/Items/Misc/BulletinBoards.cs b/Projects/Scripts/Items/Misc/BulletinBoards.cs index 69ec0b014..7e17e5874 100644 --- a/Projects/Scripts/Items/Misc/BulletinBoards.cs +++ b/Projects/Scripts/Items/Misc/BulletinBoards.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Server.Buffers; using Server.Network; using Server.Targeting; @@ -54,7 +55,7 @@ namespace Server.Items } [CommandProperty(AccessLevel.GameMaster)] - public string BoardName{ get; set; } + public string BoardName { get; set; } public static bool CheckTime(DateTime time, TimeSpan range) => time + range < DateTime.UtcNow; @@ -66,8 +67,10 @@ namespace Server.Items if (minutes != 0 && seconds != 0) return $"{minutes} minute{(minutes == 1 ? "" : "s")} and {seconds} second{(seconds == 1 ? "" : "s")}"; + if (minutes != 0) return $"{minutes} minute{(minutes == 1 ? "" : "s")}"; + return $"{seconds} second{(seconds == 1 ? "" : "s")}"; } @@ -146,11 +149,8 @@ namespace Server.Items NetState state = from.NetState; - state.Send(new BBDisplayBoard(this)); - if (state.ContainerGridLines) - state.Send(new ContainerContent6017(from, this)); - else - state.Send(new ContainerContent(from, this)); + BBPackets.SendBBDisplayBoard(state, this); + Packets.SendContainerContent(state, from, this); } else { @@ -232,18 +232,14 @@ namespace Server.Items public static void BBRequestContent(Mobile from, BaseBulletinBoard board, PacketReader pvSrc) { - if (!(World.FindItem(pvSrc.ReadUInt32()) is BulletinMessage msg) || msg.Parent != board) - return; - - from.Send(new BBMessageContent(board, msg)); + if (World.FindItem(pvSrc.ReadUInt32()) is BulletinMessage msg && msg.Parent == board) + BBPackets.SendBBMessageContent(from.NetState, board, msg); } public static void BBRequestHeader(Mobile from, BaseBulletinBoard board, PacketReader pvSrc) { - if (!(World.FindItem(pvSrc.ReadUInt32()) is BulletinMessage msg) || msg.Parent != board) - return; - - from.Send(new BBMessageHeader(board, msg)); + if (World.FindItem(pvSrc.ReadUInt32()) is BulletinMessage msg && msg.Parent == board) + BBPackets.SendBBMessageHeader(from.NetState, board, msg); } public static void BBPostMessage(Mobile from, BaseBulletinBoard board, PacketReader pvSrc) @@ -271,7 +267,7 @@ namespace Server.Items return; } - string subject = pvSrc.ReadUTF8StringSafe(pvSrc.ReadByte()); + string subject = pvSrc.ReadStringSafe(pvSrc.ReadByte()); if (subject.Length == 0) return; @@ -282,7 +278,7 @@ namespace Server.Items return; for (int i = 0; i < lines.Length; ++i) - lines[i] = pvSrc.ReadUTF8StringSafe(pvSrc.ReadByte()); + lines[i] = pvSrc.ReadStringSafe(pvSrc.ReadByte()); board.PostMessage(from, thread, subject, lines); } @@ -344,25 +340,25 @@ namespace Server.Items { } - public Mobile Poster{ get; private set; } + public Mobile Poster { get; private set; } - public BulletinMessage Thread{ get; private set; } + public BulletinMessage Thread { get; private set; } - public string Subject{ get; private set; } + public string Subject { get; private set; } - public DateTime Time{ get; private set; } + public DateTime Time { get; private set; } - public DateTime LastPostTime{ get; set; } + public DateTime LastPostTime { get; set; } - public string PostedName{ get; private set; } + public string PostedName { get; private set; } - public int PostedBody{ get; private set; } + public int PostedBody { get; private set; } - public int PostedHue{ get; private set; } + public int PostedHue { get; private set; } - public BulletinEquip[] PostedEquip{ get; private set; } + public BulletinEquip[] PostedEquip { get; private set; } - public string[] Lines{ get; private set; } + public string[] Lines { get; private set; } public string GetTimeAsString() => Time.ToString("MMM dd, yyyy"); @@ -452,70 +448,64 @@ namespace Server.Items } } - public class BBDisplayBoard : Packet + public static class BBPackets { - public BBDisplayBoard(BaseBulletinBoard board) : base(0x71) + public static void SendBBDisplayBoard(NetState ns, BaseBulletinBoard board) { - EnsureCapacity(38); + SpanWriter writer = new SpanWriter(stackalloc byte[38]); + writer.Write((byte)0x71); // Packet ID + writer.Write((ushort)38); // Dynamic Length - byte[] buffer = Utility.UTF8.GetBytes(board.BoardName ?? ""); + writer.Position++; // writer.Write((byte)0); // Command + writer.Write(board.Serial); + writer.WriteAsciiNull(board.BoardName ?? "", 29); - m_Stream.Write((byte)0x00); // PacketID - m_Stream.Write(board.Serial); // Bulletin board serial - - // Bulletin board name - if (buffer.Length >= 29) - { - m_Stream.Write(buffer, 0, 29); - m_Stream.Write((byte)0); - } - else - { - m_Stream.Write(buffer, 0, buffer.Length); - m_Stream.Fill(30 - buffer.Length); - } - } - } - - public class BBMessageHeader : Packet - { - public BBMessageHeader(BaseBulletinBoard board, BulletinMessage msg) : base(0x71) - { - string poster = SafeString(msg.PostedName); - string subject = SafeString(msg.Subject); - string time = SafeString(msg.GetTimeAsString()); - - EnsureCapacity(22 + poster.Length + subject.Length + time.Length); - - m_Stream.Write((byte)0x01); // PacketID - m_Stream.Write(board.Serial); // Bulletin board serial - m_Stream.Write(msg.Serial); // Message serial - - BulletinMessage thread = msg.Thread; - - if (thread == null) - m_Stream.Write(0); // Thread serial--root - else - m_Stream.Write(thread.Serial); // Thread serial--parent - - WriteString(poster); - WriteString(subject); - WriteString(time); + ns.Send(writer.Span); } - public void WriteString(string v) + public static void SendBBMessageHeader(NetState ns, BaseBulletinBoard board, BulletinMessage msg) { - byte[] buffer = Utility.UTF8.GetBytes(v); - int len = buffer.Length + 1; + string poster = msg.PostedName ?? ""; + string subject = msg.Subject ?? ""; + string time = msg.GetTimeAsString() ?? ""; - if (len > 255) - len = 255; + byte posterLength = Math.Min((byte)poster.Length, (byte)254); + byte subjectLength = Math.Min((byte)subject.Length, (byte)254); + byte timeLength = Math.Min((byte)time.Length, (byte)254); - m_Stream.Write((byte)len); - m_Stream.Write(buffer, 0, len - 1); - m_Stream.Write((byte)0); + int length = 22 + posterLength + subjectLength + timeLength; + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0x71); // Packet ID + writer.Write((ushort)length); // Dynamic Length + + writer.Write((byte)0x01); // Command + writer.Write(board.Serial); // Bulletin board serial + writer.Write(msg.Serial); // Message serial + writer.Write(msg.Thread?.Serial ?? 0); + + writer.Write(posterLength); + writer.WriteAsciiNull(poster, posterLength + 1); + writer.Write(subjectLength); + writer.WriteAsciiNull(subject, subjectLength + 1); + writer.Write(timeLength); + writer.WriteAsciiNull(time, timeLength + 1); + + ns.Send(writer.Span); } + public static void SendBBMessageContent(NetState ns, BaseBulletinBoard board, BulletinMessage msg) + { + string poster = msg.PostedName ?? ""; + string subject = msg.Subject ?? ""; + string time = msg.GetTimeAsString() ?? ""; + + byte posterLength = Math.Min((byte)poster.Length, (byte)254); + byte subjectLength = Math.Min((byte)subject.Length, (byte)254); + byte timeLength = Math.Min((byte)time.Length, (byte)254); + + int equipLength = Math.Min(msg.PostedEquip.Length, 255); + int msgLength = Math.Min(msg.Lines.Length, 255); + public string SafeString(string v) => v ?? string.Empty; } @@ -529,72 +519,43 @@ namespace Server.Items EnsureCapacity(22 + poster.Length + subject.Length + time.Length); - m_Stream.Write((byte)0x02); // PacketID - m_Stream.Write(board.Serial); // Bulletin board serial - m_Stream.Write(msg.Serial); // Message serial + writer.Write((byte)0x02); // Command + writer.Write(board.Serial); // Bulletin board serial + writer.Write(msg.Serial); // Message serial - WriteString(poster); - WriteString(subject); - WriteString(time); + writer.Write(posterLength); + writer.WriteAsciiNull(poster, posterLength + 1); + writer.Write(subjectLength); + writer.WriteAsciiNull(subject, subjectLength + 1); + writer.Write(timeLength); + writer.WriteAsciiNull(time, timeLength + 1); - m_Stream.Write((short)msg.PostedBody); - m_Stream.Write((short)msg.PostedHue); + writer.Write((short)msg.PostedBody); + writer.Write((short)msg.PostedHue); - int len = msg.PostedEquip.Length; + writer.Write((byte)equipLength); - if (len > 255) - len = 255; - - m_Stream.Write((byte)len); - - for (int i = 0; i < len; ++i) + for (int i = 0; i < equipLength; ++i) { BulletinEquip eq = msg.PostedEquip[i]; - m_Stream.Write((short)eq.itemID); - m_Stream.Write((short)eq.hue); + writer.Write((short)eq.itemID); + writer.Write((short)eq.hue); } - len = msg.Lines.Length; + writer.Write((byte)msgLength); - if (len > 255) - len = 255; + for (int i = 0; i < msgLength; ++i) + { + string line = msg.Lines[i]; + byte len = Math.Min((byte)line.Length, (byte)254); + writer.WriteAsciiNull(line, len); + } - m_Stream.Write((byte)len); + writer.Position = 1; + writer.Write((ushort)writer.WrittenCount); - for (int i = 0; i < len; ++i) - WriteString(msg.Lines[i], true); - } - - public void WriteString(string v) - { - WriteString(v, false); - } - - public void WriteString(string v, bool padding) - { - byte[] buffer = Utility.UTF8.GetBytes(v); - int tail = padding ? 2 : 1; - int len = buffer.Length + tail; - - if (len > 255) - len = 255; - - m_Stream.Write((byte)len); - m_Stream.Write(buffer, 0, len - tail); - - if (padding) - m_Stream.Write((short)0); // padding compensates for a client bug - else - m_Stream.Write((byte)0); - } - - public string SafeString(string v) - { - if (v == null) - return string.Empty; - - return v; + ns.Send(writer.Span); } } } diff --git a/Projects/Scripts/Items/Misc/CommunicationCrystals.cs b/Projects/Scripts/Items/Misc/CommunicationCrystals.cs index d660b678f..1cd235d19 100644 --- a/Projects/Scripts/Items/Misc/CommunicationCrystals.cs +++ b/Projects/Scripts/Items/Misc/CommunicationCrystals.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Network; using Server.Targeting; @@ -29,14 +30,7 @@ namespace Server.Items public int Amount{ get; } - public static CrystalRechargeInfo Get(Type type) - { - foreach (CrystalRechargeInfo info in Table) - if (info.Type == type) - return info; - - return null; - } + public static CrystalRechargeInfo Get(Type type) => Table.FirstOrDefault(info => info.Type == type); } public class BroadcastCrystal : Item diff --git a/Projects/Scripts/Items/Misc/Corpses/Corpse.cs b/Projects/Scripts/Items/Misc/Corpses/Corpse.cs index 5aaa1f3fc..dd37973f3 100644 --- a/Projects/Scripts/Items/Misc/Corpses/Corpse.cs +++ b/Projects/Scripts/Items/Misc/Corpses/Corpse.cs @@ -100,7 +100,7 @@ namespace Server.Items public Corpse(Mobile owner, HairInfo hair, FacialHairInfo facialhair, List equipItems) : base(0x2006) { - // To supress console warnings, stackable must be true + // To suppress console warnings, stackable must be true Stackable = true; Amount = owner.Body; // protocol defines that for itemid 0x2006, amount=body Stackable = false; @@ -193,16 +193,7 @@ namespace Server.Items } [CommandProperty(AccessLevel.GameMaster)] - public virtual bool InstancedCorpse - { - get - { - if (!Core.SE) - return false; - - return DateTime.UtcNow < TimeOfDeath + InstancedCorpseTime; - } - } + public virtual bool InstancedCorpse => Core.SE && DateTime.UtcNow < TimeOfDeath + InstancedCorpseTime; public override bool IsDecoContainer => false; @@ -302,9 +293,7 @@ namespace Server.Items Mobile dead = Owner; if (GetFlag(CorpseFlag.Carved) || dead == null) - { from.SendLocalizedMessage(500485); // You see nothing useful to carve from the corpse. - } else if (((Body)Amount).IsHuman && ItemID == 0x2006) { new Blood(0x122D).MoveToWorld(Location, Map); @@ -328,13 +317,9 @@ namespace Server.Items from.CriminalAction(true); } else if (dead is BaseCreature creature) - { creature.OnCarve(from, this, item); - } else - { from.SendLocalizedMessage(500485); // You see nothing useful to carve from the corpse. - } } public override bool IsChildVisibleTo(Mobile m, Item child) => @@ -347,8 +332,7 @@ namespace Server.Items if (Aggressors.Count == 0 || Items.Count == 0) return; - if (m_InstancedItems == null) - m_InstancedItems = new Dictionary(); + m_InstancedItems ??= new Dictionary(); List m_Stackables = new List(); List m_Unstackables = new List(); @@ -401,7 +385,7 @@ namespace Server.Items } if (remainder == 0) - m_InstancedItems.Add(item, new InstancedItemInfo(item, attackers[attackers.Count - 1])); + m_InstancedItems.Add(item, new InstancedItemInfo(item, attackers[^1])); else m_Unstackables.Add(item); } @@ -427,9 +411,7 @@ namespace Server.Items if (InstancedCorpse) { - if (m_InstancedItems == null) - m_InstancedItems = new Dictionary(); - + m_InstancedItems ??= new Dictionary(); m_InstancedItems.Add(carved, new InstancedItemInfo(carved, carver)); } } @@ -464,7 +446,6 @@ namespace Server.Items public override void OnAfterDelete() { m_DecayTimer?.Stop(); - m_DecayTimer = null; } @@ -543,29 +524,23 @@ namespace Server.Items writer.WriteDeltaTime(TimeOfDeath); - List> list = m_RestoreTable == null - ? null - : new List>(m_RestoreTable); - int count = list?.Count ?? 0; - - writer.Write(count); - - for (int i = 0; i < count; ++i) + if (m_RestoreTable == null) + writer.Write(0); + else { - KeyValuePair kvp = list[i]; - Item item = kvp.Key; - Point3D loc = kvp.Value; + writer.Write(m_RestoreTable.Count); - writer.Write(item); + foreach (var (item, loc) in m_RestoreTable) + { + writer.Write(item); - if (item.Location == loc) - { - writer.Write(false); - } - else - { - writer.Write(true); - writer.Write(loc); + if (item.Location == loc) + writer.Write(false); + else + { + writer.Write(true); + writer.Write(loc); + } } } @@ -757,12 +732,8 @@ namespace Server.Items if (!(((Body)Amount).IsHuman && ItemID == 0x2006)) return; - if (state.ContainerGridLines) - state.Send(new CorpseContent6017(state.Mobile, this)); - else - state.Send(new CorpseContent(state.Mobile, this)); - - state.Send(new CorpseEquip(state.Mobile, this)); + CorpsePackets.SendCorpseContent(state, state.Mobile, this); + CorpsePackets.SendCorpseEquip(state, state.Mobile, this); } public bool IsCriminalAction(Mobile from) @@ -836,8 +807,7 @@ namespace Server.Items if (item == null) return; - if (m_RestoreTable == null) - m_RestoreTable = new Dictionary(); + m_RestoreTable ??= new Dictionary(); m_RestoreTable[item] = loc; } @@ -1065,7 +1035,7 @@ namespace Server.Items ObjectPropertyList opl = PropertyList; if (opl.Header > 0) - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Label, hue, 3, opl.Header, Name, opl.HeaderArgs)); + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, hue, 3, opl.Header, Name, opl.HeaderArgs); } public override void OnSingleClick(Mobile from) @@ -1075,14 +1045,12 @@ namespace Server.Items if (ItemID == 0x2006) // Corpse form { if (m_CorpseName != null) - from.Send(new AsciiMessage(Serial, ItemID, MessageType.Label, hue, 3, "", m_CorpseName)); + Packets.SendAsciiMessage(from.NetState, Serial, ItemID, MessageType.Label, hue, 3, "", m_CorpseName); else - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Label, hue, 3, 1046414, "", Name)); + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, hue, 3, 1046414, "", Name); } else // Bone form - { - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Label, hue, 3, 1046414, "", Name)); - } + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, hue, 3, 1046414, "", Name); } private class InstancedItemInfo diff --git a/Projects/Scripts/Items/Misc/Corpses/Packets.cs b/Projects/Scripts/Items/Misc/Corpses/Packets.cs index cb4cb10d9..7040d5060 100644 --- a/Projects/Scripts/Items/Misc/Corpses/Packets.cs +++ b/Projects/Scripts/Items/Misc/Corpses/Packets.cs @@ -1,24 +1,29 @@ using System.Collections.Generic; -using System.IO; +using Server.Buffers; using Server.Items; namespace Server.Network { - public sealed class CorpseEquip : Packet + public static class CorpsePackets { - public CorpseEquip(Mobile beholder, Corpse beheld) : base(0x89) + public static void SendCorpseEquip(NetState ns, Mobile beholder, Corpse beheld) { + if (ns == null) + return; + List list = beheld.EquipItems; - int count = list.Count; - if (beheld.Hair != null && beheld.Hair.ItemID > 0) - count++; - if (beheld.FacialHair != null && beheld.FacialHair.ItemID > 0) - count++; + int length = 8 + list.Count * 5; + if (beheld.Hair?.ItemID > 0) + length += 5; + if (beheld.FacialHair?.ItemID > 0) + length += 5; - EnsureCapacity(8 + count * 5); + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0x89); // Packet ID + writer.Write((ushort)length); // Dynamic Length - m_Stream.Write(beheld.Serial); + writer.Write(beheld.Serial); for (int i = 0; i < list.Count; ++i) { @@ -26,173 +31,180 @@ namespace Server.Network if (!item.Deleted && beholder.CanSee(item) && item.Parent == beheld) { - m_Stream.Write((byte)(item.Layer + 1)); - m_Stream.Write(item.Serial); + writer.Write((byte)(item.Layer + 1)); + writer.Write(item.Serial); } } - if (beheld.Hair != null && beheld.Hair.ItemID > 0) + if (beheld.Hair?.ItemID > 0) { - m_Stream.Write((byte)(Layer.Hair + 1)); - m_Stream.Write(HairInfo.FakeSerial(beheld.Owner) - 2); + writer.Write((byte)(Layer.Hair + 1)); + writer.Write(HairInfo.FakeSerial(beheld.Owner.Serial) - 2); } - if (beheld.FacialHair != null && beheld.FacialHair.ItemID > 0) + if (beheld.FacialHair?.ItemID > 0) { - m_Stream.Write((byte)(Layer.FacialHair + 1)); - m_Stream.Write(FacialHairInfo.FakeSerial(beheld.Owner) - 2); + writer.Write((byte)(Layer.FacialHair + 1)); + writer.Write(FacialHairInfo.FakeSerial(beheld.Owner.Serial) - 2); } - m_Stream.Write((byte)Layer.Invalid); + writer.Position++; // writer.Write((byte)Layer.Invalid); + + ns.Send(writer.Span); } - } - public sealed class CorpseContent : Packet - { - public CorpseContent(Mobile beholder, Corpse beheld) - : base(0x3C) + public static void SendCorpseContent(NetState ns, Mobile beholder, Corpse corpse) { - List items = beheld.EquipItems; - int count = items.Count; + if (ns == null) + return; - if (beheld.Hair != null && beheld.Hair.ItemID > 0) - count++; - if (beheld.FacialHair != null && beheld.FacialHair.ItemID > 0) - count++; + if (ns.ContainerGridLines) + SendCorpseContentNew(ns, beholder, corpse); + else + SendCorpseContentOld(ns, beholder, corpse); + } - EnsureCapacity(5 + count * 19); + public static void SendCorpseContentOld(NetState ns, Mobile beholder, Corpse corpse) + { + if (ns == null) + return; - long pos = m_Stream.Position; + List items = corpse.EquipItems; + int length = 5 + items.Count * 19; - int written = 0; + if (corpse.Hair?.ItemID > 0) + length += 19; + if (corpse.FacialHair?.ItemID > 0) + length += 19; - m_Stream.Write((ushort)0); + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0x3C); // Packet ID + writer.Write((ushort)length); // Dynamic Length + writer.Position += 2; + + ushort written = 0; for (int i = 0; i < items.Count; ++i) { Item child = items[i]; - if (!child.Deleted && child.Parent == beheld && beholder.CanSee(child)) + if (!child.Deleted && child.Parent == corpse && beholder.CanSee(child)) { - m_Stream.Write(child.Serial); - m_Stream.Write((ushort)child.ItemID); - m_Stream.Write((byte)0); // signed, itemID offset - m_Stream.Write((ushort)child.Amount); - m_Stream.Write((short)child.X); - m_Stream.Write((short)child.Y); - m_Stream.Write(beheld.Serial); - m_Stream.Write((ushort)child.Hue); + writer.Write(child.Serial); + writer.Write((ushort)child.ItemID); + writer.Position++; // signed, itemID offset + writer.Write((ushort)child.Amount); + writer.Write((short)child.X); + writer.Write((short)child.Y); + writer.Write(corpse.Serial); + writer.Write((ushort)child.Hue); ++written; } } - if (beheld.Hair != null && beheld.Hair.ItemID > 0) + if (corpse.Hair?.ItemID > 0) { - m_Stream.Write(HairInfo.FakeSerial(beheld.Owner) - 2); - m_Stream.Write((ushort)beheld.Hair.ItemID); - m_Stream.Write((byte)0); // signed, itemID offset - m_Stream.Write((ushort)1); - m_Stream.Write((short)0); - m_Stream.Write((short)0); - m_Stream.Write(beheld.Serial); - m_Stream.Write((ushort)beheld.Hair.Hue); + writer.Write(HairInfo.FakeSerial(corpse.Owner.Serial) - 2); + writer.Write((ushort)corpse.Hair.ItemID); + writer.Position++; // signed, itemID offset + writer.Write((ushort)1); + writer.Position += 4; + writer.Write(corpse.Serial); + writer.Write((ushort)corpse.Hair.Hue); ++written; } - if (beheld.FacialHair != null && beheld.FacialHair.ItemID > 0) + if (corpse.FacialHair?.ItemID > 0) { - m_Stream.Write(FacialHairInfo.FakeSerial(beheld.Owner) - 2); - m_Stream.Write((ushort)beheld.FacialHair.ItemID); - m_Stream.Write((byte)0); // signed, itemID offset - m_Stream.Write((ushort)1); - m_Stream.Write((short)0); - m_Stream.Write((short)0); - m_Stream.Write(beheld.Serial); - m_Stream.Write((ushort)beheld.FacialHair.Hue); + writer.Write(FacialHairInfo.FakeSerial(corpse.Owner.Serial) - 2); + writer.Write((ushort)corpse.FacialHair.ItemID); + writer.Position++; // signed, itemID offset + writer.Write((ushort)1); + writer.Position += 4; + writer.Write(corpse.Serial); + writer.Write((ushort)corpse.FacialHair.Hue); ++written; } - m_Stream.Seek(pos, SeekOrigin.Begin); - m_Stream.Write((ushort)written); + writer.Position = 3; + writer.Write(written); + + ns.Send(writer.Span); } - } - public sealed class CorpseContent6017 : Packet - { - public CorpseContent6017(Mobile beholder, Corpse beheld) - : base(0x3C) + public static void SendCorpseContentNew(NetState ns, Mobile beholder, Corpse corpse) { - List items = beheld.EquipItems; - int count = items.Count; + if (ns == null) + return; - if (beheld.Hair != null && beheld.Hair.ItemID > 0) - count++; - if (beheld.FacialHair != null && beheld.FacialHair.ItemID > 0) - count++; + List items = corpse.EquipItems; + int length = 5 + items.Count * 20; - EnsureCapacity(5 + count * 20); + if (corpse.Hair?.ItemID > 0) + length += 20; + if (corpse.FacialHair?.ItemID > 0) + length += 20; - long pos = m_Stream.Position; + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0x3C); // Packet ID + writer.Write((ushort)length); // Dynamic Length + writer.Position += 2; - int written = 0; - - m_Stream.Write((ushort)0); + ushort written = 0; for (int i = 0; i < items.Count; ++i) { Item child = items[i]; - if (!child.Deleted && child.Parent == beheld && beholder.CanSee(child)) + if (!child.Deleted && child.Parent == corpse && beholder.CanSee(child)) { - m_Stream.Write(child.Serial); - m_Stream.Write((ushort)child.ItemID); - m_Stream.Write((byte)0); // signed, itemID offset - m_Stream.Write((ushort)child.Amount); - m_Stream.Write((short)child.X); - m_Stream.Write((short)child.Y); - m_Stream.Write((byte)0); // Grid Location? - m_Stream.Write(beheld.Serial); - m_Stream.Write((ushort)child.Hue); + writer.Write(child.Serial); + writer.Write((ushort)child.ItemID); + writer.Position++; // signed, itemID offset + writer.Write((ushort)child.Amount); + writer.Write((short)child.X); + writer.Write((short)child.Y); + writer.Position++; // grid location + writer.Write(corpse.Serial); + writer.Write((ushort)child.Hue); ++written; } } - if (beheld.Hair != null && beheld.Hair.ItemID > 0) + if (corpse.Hair?.ItemID > 0) { - m_Stream.Write(HairInfo.FakeSerial(beheld.Owner) - 2); - m_Stream.Write((ushort)beheld.Hair.ItemID); - m_Stream.Write((byte)0); // signed, itemID offset - m_Stream.Write((ushort)1); - m_Stream.Write((short)0); - m_Stream.Write((short)0); - m_Stream.Write((byte)0); // Grid Location? - m_Stream.Write(beheld.Serial); - m_Stream.Write((ushort)beheld.Hair.Hue); + writer.Write(HairInfo.FakeSerial(corpse.Owner.Serial) - 2); + writer.Write((ushort)corpse.Hair.ItemID); + writer.Position++; // signed, itemID offset + writer.Write((ushort)1); + writer.Position += 5; + writer.Write(corpse.Serial); + writer.Write((ushort)corpse.Hair.Hue); ++written; } - if (beheld.FacialHair != null && beheld.FacialHair.ItemID > 0) + if (corpse.FacialHair?.ItemID > 0) { - m_Stream.Write(FacialHairInfo.FakeSerial(beheld.Owner) - 2); - m_Stream.Write((ushort)beheld.FacialHair.ItemID); - m_Stream.Write((byte)0); // signed, itemID offset - m_Stream.Write((ushort)1); - m_Stream.Write((short)0); - m_Stream.Write((short)0); - m_Stream.Write((byte)0); // Grid Location? - m_Stream.Write(beheld.Serial); - m_Stream.Write((ushort)beheld.FacialHair.Hue); + writer.Write(FacialHairInfo.FakeSerial(corpse.Owner.Serial) - 2); + writer.Write((ushort)corpse.FacialHair.ItemID); + writer.Position++; // signed, itemID offset + writer.Write((ushort)1); + writer.Position += 5; + writer.Write(corpse.Serial); + writer.Write((ushort)corpse.FacialHair.Hue); ++written; } - m_Stream.Seek(pos, SeekOrigin.Begin); - m_Stream.Write((ushort)written); + writer.Position = 3; + writer.Write(written); + + ns.Send(writer.Span); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Misc/EffectController.cs b/Projects/Scripts/Items/Misc/EffectController.cs index 16f94d462..ecf776620 100644 --- a/Projects/Scripts/Items/Misc/EffectController.cs +++ b/Projects/Scripts/Items/Misc/EffectController.cs @@ -304,7 +304,7 @@ namespace Server.Items { case ECEffectType.Lightning: { - Effects.SendBoltEffect(from, false, EffectHue); + Effects.SendBoltEffect(from, false); break; } case ECEffectType.Location: @@ -334,4 +334,4 @@ namespace Server.Items } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Misc/EffectItem.cs b/Projects/Scripts/Items/Misc/EffectItem.cs index dcddd3b74..ebd8c9992 100644 --- a/Projects/Scripts/Items/Misc/EffectItem.cs +++ b/Projects/Scripts/Items/Misc/EffectItem.cs @@ -83,4 +83,4 @@ namespace Server.Items } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Misc/Firebomb.cs b/Projects/Scripts/Items/Misc/Firebomb.cs index 6ab46e1a2..0bc4553bf 100644 --- a/Projects/Scripts/Items/Misc/Firebomb.cs +++ b/Projects/Scripts/Items/Misc/Firebomb.cs @@ -66,8 +66,7 @@ namespace Server.Items from.SendLocalizedMessage(1060581); // You've already lit it! Better throw it now! } - if (m_Users == null) - m_Users = new List(); + m_Users ??= new List(); if (!m_Users.Contains(from)) m_Users.Add(from); diff --git a/Projects/Scripts/Items/Misc/Gold.cs b/Projects/Scripts/Items/Misc/Gold.cs index 4a8553f01..bacb07ef1 100644 --- a/Projects/Scripts/Items/Misc/Gold.cs +++ b/Projects/Scripts/Items/Misc/Gold.cs @@ -1,5 +1,4 @@ using System; -using Server.Accounting; namespace Server.Items { diff --git a/Projects/Scripts/Items/Misc/InteriorDecorator.cs b/Projects/Scripts/Items/Misc/InteriorDecorator.cs index 8e01befe1..c9012b72e 100644 --- a/Projects/Scripts/Items/Misc/InteriorDecorator.cs +++ b/Projects/Scripts/Items/Misc/InteriorDecorator.cs @@ -182,8 +182,7 @@ namespace Server.Items if (addon != null) { - if (count == 1 && Core.SE) - isDecorableComponent = true; + isDecorableComponent |= count == 1 && Core.SE; if (m_Decorator.Command == DecorateCommand.Turn) { @@ -191,8 +190,7 @@ namespace Server.Items (FlippableAddonAttribute[])addon.GetType() .GetCustomAttributes(typeof(FlippableAddonAttribute), false); - if (attributes.Length > 0) - isDecorableComponent = true; + isDecorableComponent = attributes.Length > 0; } } diff --git a/Projects/Scripts/Items/Misc/Key.cs b/Projects/Scripts/Items/Misc/Key.cs index 475b3492b..60a99de75 100644 --- a/Projects/Scripts/Items/Misc/Key.cs +++ b/Projects/Scripts/Items/Misc/Key.cs @@ -1,5 +1,4 @@ using Server.Network; -using Server.Prompts; using Server.Targeting; namespace Server.Items @@ -204,14 +203,9 @@ namespace Server.Items { base.GetProperties(list); - string desc; + string desc = m_KeyVal == 0 ? "(blank)" : m_Description?.Trim() ?? ""; - if (m_KeyVal == 0) - desc = "(blank)"; - else if ((desc = m_Description) == null || (desc = desc.Trim()).Length <= 0) - desc = null; - - if (desc != null) + if (desc != "") list.Add(desc); } @@ -219,15 +213,10 @@ namespace Server.Items { base.OnSingleClick(from); - string desc; - - if (m_KeyVal == 0) - desc = "(blank)"; - else if ((desc = m_Description) == null || (desc = desc.Trim()).Length <= 0) - desc = ""; + string desc = m_KeyVal == 0 ? "(blank)" : m_Description?.Trim() ?? ""; if (desc.Length > 0) - from.Send(new UnicodeMessage(Serial, ItemID, MessageType.Regular, 0x3B2, 3, "ENU", "", desc)); + Packets.SendUnicodeMessage(from.NetState, Serial, ItemID, MessageType.Regular, 0x3B2, 3, "ENU", "", desc); } public bool UseOn(Mobile from, ILockable o) diff --git a/Projects/Scripts/Items/Misc/KeyRing.cs b/Projects/Scripts/Items/Misc/KeyRing.cs index 4965f6827..40480d8a7 100644 --- a/Projects/Scripts/Items/Misc/KeyRing.cs +++ b/Projects/Scripts/Items/Misc/KeyRing.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using Server.Targeting; namespace Server.Items @@ -109,14 +110,7 @@ namespace Server.Items UpdateItemID(); } - public bool ContainsKey(uint keyValue) - { - foreach (Key key in Keys) - if (key.KeyValue == keyValue) - return true; - - return false; - } + public bool ContainsKey(uint keyValue) => Keys.Any(key => key.KeyValue == keyValue); private void UpdateItemID() { @@ -169,9 +163,7 @@ namespace Server.Items } else if (targeted is ILockable o) { - foreach (Key key in m_KeyRing.Keys) - if (key.UseOn(from, o)) - return; + if (m_KeyRing.Keys.Any(key => key.UseOn(from, o))) return; from.SendLocalizedMessage(1008140); // You do not have a key for that. } @@ -182,4 +174,4 @@ namespace Server.Items } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Misc/LOSBlocker.cs b/Projects/Scripts/Items/Misc/LOSBlocker.cs index 2d44cef77..ca21df5a3 100644 --- a/Projects/Scripts/Items/Misc/LOSBlocker.cs +++ b/Projects/Scripts/Items/Misc/LOSBlocker.cs @@ -1,3 +1,4 @@ +using Server.Buffers; using Server.Network; namespace Server.Items @@ -19,13 +20,21 @@ namespace Server.Items TileData.ItemTable[0x21A2].Height = 20; } - protected override Packet GetWorldPacketFor(NetState state) + protected override void SendWorldPacketFor(NetState state) { Mobile mob = state.Mobile; - if (mob?.AccessLevel >= AccessLevel.GameMaster) return new GMItemPacket(this); + if (mob?.AccessLevel >= AccessLevel.GameMaster) + { + if (state.HighSeas) + SendGMItemHS(state); + else if (state.StygianAbyss) + SendGMItemSA(state); + else + SendGMItem(state); + } - return base.GetWorldPacketFor(state); + base.SendWorldPacketFor(state); } public override void Serialize(GenericWriter writer) @@ -45,66 +54,138 @@ namespace Server.Items ItemID = 0x21A2; } - public sealed class GMItemPacket : Packet + private void SendGMItem(NetState ns) { - public GMItemPacket(Item item) : base(0x1A) - { - EnsureCapacity(20); + if (ns == null) + return; - // 14 base length - // +2 - Amount - // +2 - Hue - // +1 - Flags + SpanWriter w = new SpanWriter(stackalloc byte[20]); + w.Write((byte)0x1A); // Packet ID + w.Position += 2; // Dynamic Length - uint serial = item.Serial.Value; - int itemID = 0x36FF; - int amount = item.Amount; - Point3D loc = item.Location; - int x = loc.X; - int y = loc.Y; - int hue = item.Hue; - int flags = item.GetPacketFlags(); - int direction = (int)item.Direction; + uint serial = Serial.Value; + int itemId = 0x36FF; + int amount = Amount; + Point3D loc = Location; + int x = loc.X; + int y = loc.Y; + int hue = Hue; + int flags = GetPacketFlags(); + int direction = (int)Direction; - if (amount != 0) - serial |= 0x80000000; - else - serial &= 0x7FFFFFFF; + if (amount != 0) + serial |= 0x80000000; + else + serial &= 0x7FFFFFFF; - m_Stream.Write(serial); - m_Stream.Write((short)(itemID & 0x7FFF)); + w.Write(serial); - if (amount != 0) - m_Stream.Write((short)amount); + w.Write((short)itemId); - x &= 0x7FFF; + if (amount != 0) + w.Write((short)amount); - if (direction != 0) - x |= 0x8000; + x &= 0x7FFF; - m_Stream.Write((short)x); + if (direction != 0) x |= 0x8000; - y &= 0x3FFF; + w.Write((short)x); - if (hue != 0) - y |= 0x8000; + y &= 0x3FFF; - if (flags != 0) - y |= 0x4000; + if (hue != 0) y |= 0x8000; - m_Stream.Write((short)y); + if (flags != 0) y |= 0x4000; - if (direction != 0) - m_Stream.Write((byte)direction); + w.Write((short)y); - m_Stream.Write((sbyte)loc.Z); + if (direction != 0) + w.Write((byte)direction); - if (hue != 0) - m_Stream.Write((ushort)hue); + w.Write((sbyte)loc.Z); - if (flags != 0) - m_Stream.Write((byte)flags); - } + if (hue != 0) + w.Write((ushort)hue); + + if (flags != 0) + w.Write((byte)flags); + + w.Position = 1; + w.Write((ushort)w.WrittenCount); + + ns.Send(w.Span); + } + + public void SendGMItemSA(NetState ns) + { + if (ns == null) + return; + + SpanWriter w = new SpanWriter(stackalloc byte[24]); + w.Write((byte)0xF3); // Packet ID + + w.Write((short)0x01); + + int itemId = 0x36FF; + + w.Position++; // w.Write((byte)0); + + w.Write(Serial); + + w.Write((short)itemId); + + w.Write((byte)Direction); + + short amount = (short)Amount; + w.Write(amount); + w.Write(amount); + + Point3D loc = Location; + w.Write((short)(loc.X & 0x7FFF)); + w.Write((short)(loc.Y & 0x3FFF)); + w.Write((sbyte)loc.Z); + + w.Write((byte)Light); + w.Write((short)Hue); + w.Write((byte)GetPacketFlags()); + + ns.Send(w.RawSpan); + } + + public void SendGMItemHS(NetState ns) + { + if (ns == null) + return; + + SpanWriter w = new SpanWriter(stackalloc byte[26]); + w.Write((byte)0xF3); // Packet ID + + w.Write((short)0x01); + + int itemId = 0x36FF; + + w.Position++; // w.Write((byte)0); + + w.Write(Serial); + + w.Write((short)itemId); + + w.Write((byte)Direction); + + short amount = (short)Amount; + w.Write(amount); + w.Write(amount); + + Point3D loc = Location; + w.Write((short)(loc.X & 0x7FFF)); + w.Write((short)(loc.Y & 0x3FFF)); + w.Write((sbyte)loc.Z); + + w.Write((byte)Light); + w.Write((short)Hue); + w.Write((byte)GetPacketFlags()); + + ns.Send(w.RawSpan); } } } diff --git a/Projects/Scripts/Items/Misc/PlayerBulletinBoards.cs b/Projects/Scripts/Items/Misc/PlayerBulletinBoards.cs index 2789f301d..7d5259e7d 100644 --- a/Projects/Scripts/Items/Misc/PlayerBulletinBoards.cs +++ b/Projects/Scripts/Items/Misc/PlayerBulletinBoards.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using Server.Gumps; using Server.Multis; -using Server.Prompts; using Server.Mobiles; using Server.Network; using Server.ContextMenus; diff --git a/Projects/Scripts/Items/Misc/PowerGenerator.cs b/Projects/Scripts/Items/Misc/PowerGenerator.cs index db1d950c4..00da04a2c 100644 --- a/Projects/Scripts/Items/Misc/PowerGenerator.cs +++ b/Projects/Scripts/Items/Misc/PowerGenerator.cs @@ -31,11 +31,7 @@ namespace Server.Items private void AddGeneratorComponent(int itemID, int x, int y, int z) { - AddonComponent component = new AddonComponent(itemID); - component.Name = "a power generator"; - component.Hue = 0x451; - - AddComponent(component, x, y, z); + AddComponent(new AddonComponent(itemID){ Name = "a power generator", Hue = 0x451 }, x, y, z); } public override void Serialize(GenericWriter writer) @@ -148,9 +144,7 @@ namespace Server.Items visited[current.X, current.Y] = true; } else - { current = stack[--stackSize - 1]; - } } Path = new Node[stackSize]; @@ -197,9 +191,8 @@ namespace Server.Items public void DoDamage(Mobile to) { - to.Send(new UnicodeMessage(Serial, ItemID, MessageType.Regular, 0x3B2, 3, "", "", - "The generator shoots an arc of electricity at you!")); - to.BoltEffect(0); + Packets.SendMessageLocalized(to.NetState, Serial, ItemID, MessageType.Regular, 0x3B2, 3, 1152372); // The Nexus shoots an arc of energy at you! + to.BoltEffect(); to.LocalOverheadMessage(MessageType.Regular, 0xC9, true, "* Your body convulses from electric shock *"); to.NonlocalOverheadMessage(MessageType.Regular, 0xC9, true, $"* {to.Name} spasms from electric shock *"); @@ -358,7 +351,7 @@ namespace Server.Items hues[n.X, n.Y] = NodeHue.Blue; } - Node lastNode = path[path.Length - 1]; + Node lastNode = path[^1]; hues[lastNode.X, lastNode.Y] = NodeHue.Red; for (int i = 0; i < sideLength; i++) diff --git a/Projects/Scripts/Items/Misc/PublicMoongate.cs b/Projects/Scripts/Items/Misc/PublicMoongate.cs index c0af37445..d3dc1e9fc 100644 --- a/Projects/Scripts/Items/Misc/PublicMoongate.cs +++ b/Projects/Scripts/Items/Misc/PublicMoongate.cs @@ -119,11 +119,7 @@ namespace Server.Items private static void DeleteAll() { - List list = new List(); - - foreach (Item item in World.Items.Values) - if (item is PublicMoongate) - list.Add(item); + List list = World.Items.Values.OfType().Cast().ToList(); foreach (Item item in list) item.Delete(); @@ -349,7 +345,7 @@ namespace Server.Items } } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID == 0) // Cancel return; diff --git a/Projects/Scripts/Items/Misc/Teleporter.cs b/Projects/Scripts/Items/Misc/Teleporter.cs index bf922bff7..74db4bc7b 100644 --- a/Projects/Scripts/Items/Misc/Teleporter.cs +++ b/Projects/Scripts/Items/Misc/Teleporter.cs @@ -157,10 +157,7 @@ namespace Server.Items { base.GetProperties(list); - if (m_Active) - list.Add(1060742); // active - else - list.Add(1060743); // inactive + list.Add(m_Active ? 1060742 : 1060743); if (m_MapDest != null) list.Add(1060658, "Map\t{0}", m_MapDest); @@ -234,12 +231,12 @@ namespace Server.Items bool sendEffect = !m.Hidden || m.AccessLevel == AccessLevel.Player; if (m_SourceEffect && sendEffect) - Effects.SendLocationEffect(m.Location, m.Map, 0x3728, 10, 10); + Effects.SendLocationEffect(m.Location, m.Map, 0x3728, 10); m.MoveToWorld(p, map); if (m_DestEffect && sendEffect) - Effects.SendLocationEffect(m.Location, m.Map, 0x3728, 10, 10); + Effects.SendLocationEffect(m.Location, m.Map, 0x3728, 10); if (m_SoundID > 0 && sendEffect) Effects.PlaySound(m.Location, m.Map, m_SoundID); @@ -395,11 +392,10 @@ namespace Server.Items if (m.BeginAction(this)) { if (m_MessageString != null) - m.Send(new UnicodeMessage(Serial, ItemID, MessageType.Regular, 0x3B2, 3, "ENU", null, - m_MessageString)); + Packets.SendUnicodeMessage(m.NetState, Serial, ItemID, MessageType.Regular, 0x3B2, 3, "ENU", "", + m_MessageString); else if (m_MessageNumber != 0) - m.Send(new MessageLocalized(Serial, ItemID, MessageType.Regular, 0x3B2, 3, m_MessageNumber, null, - "")); + Packets.SendMessageLocalized(m.NetState, Serial, ItemID, MessageType.Regular, 0x3B2, 3, m_MessageNumber); Timer.DelayCall(TimeSpan.FromSeconds(5.0), () => m.EndAction(this)); } @@ -525,12 +521,7 @@ namespace Server.Items if (!m.InRange(GetWorldLocation(), m_Range)) return; - bool isMatch = false; - - if (m_Keyword >= 0 && e.HasKeyword(m_Keyword)) - isMatch = true; - else if (m_Substring != null && e.Speech.ToLower().IndexOf(m_Substring.ToLower()) >= 0) - isMatch = true; + bool isMatch = m_Keyword >= 0 && e.HasKeyword(m_Keyword) || m_Substring != null && e.Speech.ToLower().IndexOf(m_Substring.ToLower()) >= 0; if (!isMatch || !CanTeleport(m)) return; @@ -820,10 +811,10 @@ namespace Server.Items writer.Write(TimeoutDelay); writer.Write(m_Teleporting.Count); - foreach (KeyValuePair kvp in m_Teleporting) + foreach (var (key, value) in m_Teleporting) { - writer.Write(kvp.Key); - writer.Write(kvp.Value.Next); + writer.Write(key); + writer.Write(value.Next); } } @@ -1063,9 +1054,7 @@ namespace Server.Items case Layer.Backpack: case Layer.Mount: case Layer.Bank: - { continue; // ignore - } default: { m.SendMessage("You must remove all of your equipment before proceeding."); diff --git a/Projects/Scripts/Items/Misc/TrashBarrel.cs b/Projects/Scripts/Items/Misc/TrashBarrel.cs index da67c25df..fc578e383 100644 --- a/Projects/Scripts/Items/Misc/TrashBarrel.cs +++ b/Projects/Scripts/Items/Misc/TrashBarrel.cs @@ -112,7 +112,7 @@ namespace Server.Items if (items.Count > 0) { - PublicOverheadMessage(MessageType.Regular, 0x3B2, message, ""); + PublicOverheadMessage(MessageType.Regular, 0x3B2, message); for (int i = items.Count - 1; i >= 0; --i) { diff --git a/Projects/Scripts/Items/Misc/UnholyBone.cs b/Projects/Scripts/Items/Misc/UnholyBone.cs index 236a41a1e..4f34ecc50 100644 --- a/Projects/Scripts/Items/Misc/UnholyBone.cs +++ b/Projects/Scripts/Items/Misc/UnholyBone.cs @@ -26,7 +26,7 @@ namespace Server.Items public void Carve(Mobile from, Item item) { Effects.PlaySound(GetWorldLocation(), Map, 0x48F); - Effects.SendLocationEffect(GetWorldLocation(), Map, 0x3728, 10, 10, 0, 0); + Effects.SendLocationEffect(GetWorldLocation(), Map, 0x3728, 10); if (0.3 > Utility.RandomDouble()) { diff --git a/Projects/Scripts/Items/Quivers/BaseQuiver.cs b/Projects/Scripts/Items/Quivers/BaseQuiver.cs index f38f31d44..def02a29d 100644 --- a/Projects/Scripts/Items/Quivers/BaseQuiver.cs +++ b/Projects/Scripts/Items/Quivers/BaseQuiver.cs @@ -302,7 +302,7 @@ namespace Server.Items if ((prop = Attributes.RegenMana) != 0) list.Add(1060440, prop.ToString()); // mana regeneration ~1_val~ - if ((prop = Attributes.NightSight) != 0) + if (Attributes.NightSight != 0) list.Add(1060441); // night sight if ((prop = Attributes.ReflectPhysical) != 0) diff --git a/Projects/Scripts/Items/Resources/Tailor/BoltOfCloth.cs b/Projects/Scripts/Items/Resources/Tailor/BoltOfCloth.cs index d57728a15..3e97a980e 100644 --- a/Projects/Scripts/Items/Resources/Tailor/BoltOfCloth.cs +++ b/Projects/Scripts/Items/Resources/Tailor/BoltOfCloth.cs @@ -54,10 +54,8 @@ namespace Server.Items public override void OnSingleClick(Mobile from) { - int number = Amount == 1 ? 1049122 : 1049121; - - from.Send( - new MessageLocalized(Serial, ItemID, MessageType.Label, 0x3B2, 3, number, "", (Amount * 50).ToString())); + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, 0x3B2, 3, + Amount == 1 ? 1049122 : 1049121, "", (Amount * 50).ToString()); } } } diff --git a/Projects/Scripts/Items/Resources/Tailor/Cloth.cs b/Projects/Scripts/Items/Resources/Tailor/Cloth.cs index 9c98be700..4f5705daa 100644 --- a/Projects/Scripts/Items/Resources/Tailor/Cloth.cs +++ b/Projects/Scripts/Items/Resources/Tailor/Cloth.cs @@ -55,9 +55,8 @@ namespace Server.Items public override void OnSingleClick(Mobile from) { - int number = Amount == 1 ? 1049124 : 1049123; - - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Regular, 0x3B2, 3, number, "", Amount.ToString())); + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, 0x3B2, 3, + Amount == 1 ? 1049124 : 1049123, "", Amount.ToString()); } } } diff --git a/Projects/Scripts/Items/Resources/Tailor/Leathers.cs b/Projects/Scripts/Items/Resources/Tailor/Leathers.cs index a8568f553..8661bfcee 100644 --- a/Projects/Scripts/Items/Resources/Tailor/Leathers.cs +++ b/Projects/Scripts/Items/Resources/Tailor/Leathers.cs @@ -29,16 +29,10 @@ namespace Server.Items } } - public override int LabelNumber - { - get - { - if (m_Resource >= CraftResource.SpinedLeather && m_Resource <= CraftResource.BarbedLeather) - return 1049684 + (m_Resource - CraftResource.SpinedLeather); - - return 1047022; - } - } + public override int LabelNumber => + m_Resource >= CraftResource.SpinedLeather && m_Resource <= CraftResource.BarbedLeather + ? 1049684 + (m_Resource - CraftResource.SpinedLeather) + : 1047022; int ICommodity.DescriptionNumber => LabelNumber; bool ICommodity.IsDeedable => true; diff --git a/Projects/Scripts/Items/Resources/Tailor/UncutCloth.cs b/Projects/Scripts/Items/Resources/Tailor/UncutCloth.cs index 676283400..eda2b6400 100644 --- a/Projects/Scripts/Items/Resources/Tailor/UncutCloth.cs +++ b/Projects/Scripts/Items/Resources/Tailor/UncutCloth.cs @@ -55,9 +55,8 @@ namespace Server.Items public override void OnSingleClick(Mobile from) { - int number = Amount == 1 ? 1049124 : 1049123; - - from.Send(new MessageLocalized(Serial, ItemID, MessageType.Regular, 0x3B2, 3, number, "", Amount.ToString())); + Packets.SendMessageLocalized(from.NetState, Serial, ItemID, MessageType.Label, 0x3B2, 3, + Amount == 1 ? 1049124 : 1049123, "", Amount.ToString()); } } } diff --git a/Projects/Scripts/Items/Skill Items/Camping/Campfire.cs b/Projects/Scripts/Items/Skill Items/Camping/Campfire.cs index cbe187746..8f9a35130 100644 --- a/Projects/Scripts/Items/Skill Items/Camping/Campfire.cs +++ b/Projects/Scripts/Items/Skill Items/Camping/Campfire.cs @@ -44,7 +44,7 @@ namespace Server.Items [CommandProperty(AccessLevel.GameMaster)] public CampfireStatus Status { - get + get => ItemID switch { return ItemID switch { diff --git a/Projects/Scripts/Items/Skill Items/Fishing/Misc/SOS.cs b/Projects/Scripts/Items/Skill Items/Fishing/Misc/SOS.cs index 2b3639fc9..dc4f20bae 100644 --- a/Projects/Scripts/Items/Skill Items/Fishing/Misc/SOS.cs +++ b/Projects/Scripts/Items/Skill Items/Fishing/Misc/SOS.cs @@ -233,21 +233,19 @@ namespace Server.Items bool xEast = false, ySouth = false; string fmt; - if (Sextant.Format(loc, map, ref xLong, ref yLat, ref xMins, ref yMins, ref xEast, ref ySouth)) - fmt = $"{yLat}°{yMins}'{(ySouth ? "S" : "N")},{xLong}°{xMins}'{(xEast ? "E" : "W")}"; - else - fmt = "?????"; + fmt = Sextant.Format(loc, map, ref xLong, ref yLat, ref xMins, ref yMins, ref xEast, ref ySouth) ? + $"{yLat}°{yMins}'{(ySouth ? "S" : "N")},{xLong}°{xMins}'{(xEast ? "E" : "W")}" : "?????"; AddPage(0); AddBackground(0, 40, 350, 300, 2520); - AddHtmlLocalized(30, 80, 285, 160, 1018326, true, - true); /* This is a message hastily scribbled by a passenger aboard a sinking ship. - * While it is probably too late to save the passengers and crew, - * perhaps some treasure went down with the ship! - * The message gives the ship's last known sextant co-ordinates. - */ + AddHtmlLocalized(30, 80, 285, 160, 1018326, true, true); + /* This is a message hastily scribbled by a passenger aboard a sinking ship. + * While it is probably too late to save the passengers and crew, + * perhaps some treasure went down with the ship! + * The message gives the ship's last known sextant co-ordinates.= + */ AddHtml(35, 240, 230, 20, fmt); diff --git a/Projects/Scripts/Items/Skill Items/Fishing/Misc/SpecialFishingNet.cs b/Projects/Scripts/Items/Skill Items/Fishing/Misc/SpecialFishingNet.cs index db5d8c74d..e82ef9e7d 100644 --- a/Projects/Scripts/Items/Skill Items/Fishing/Misc/SpecialFishingNet.cs +++ b/Projects/Scripts/Items/Skill Items/Fishing/Misc/SpecialFishingNet.cs @@ -200,7 +200,6 @@ namespace Server.Items switch (Utility.Random(8)) { default: - case 0: x = -1; y = -1; break; @@ -405,4 +404,4 @@ namespace Server.Items int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Skill Items/Harvest Tools/BaseHarvestTool.cs b/Projects/Scripts/Items/Skill Items/Harvest Tools/BaseHarvestTool.cs index 26bbbabf4..abf96ad14 100644 --- a/Projects/Scripts/Items/Skill Items/Harvest Tools/BaseHarvestTool.cs +++ b/Projects/Scripts/Items/Skill Items/Harvest Tools/BaseHarvestTool.cs @@ -159,9 +159,7 @@ namespace Server.Items if (!(from is PlayerMobile pm)) return; - ContextMenuEntry miningEntry = new ContextMenuEntry(pm.ToggleMiningStone ? 6179 : 6178); - miningEntry.Color = 0x421F; - list.Add(miningEntry); + list.Add(new ContextMenuEntry(pm.ToggleMiningStone ? 6179 : 6178) {Color = 0x421F}); list.Add(new ToggleMiningStoneEntry(pm, false, 6176)); list.Add(new ToggleMiningStoneEntry(pm, true, 6177)); diff --git a/Projects/Scripts/Items/Skill Items/Magical/Misc/Moongate.cs b/Projects/Scripts/Items/Skill Items/Magical/Misc/Moongate.cs index b0e17a24e..672019d2d 100644 --- a/Projects/Scripts/Items/Skill Items/Magical/Misc/Moongate.cs +++ b/Projects/Scripts/Items/Skill Items/Magical/Misc/Moongate.cs @@ -167,7 +167,7 @@ namespace Server.Items from.Map != Map.Felucca && TargetMap == Map.Felucca && ShowFeluccaWarning) { if (from.AccessLevel == AccessLevel.Player || !from.Hidden) - from.Send(new PlaySound(0x20E, from.Location)); + Packets.SendPlaySound(from.NetState, 0x20E, from.Location); from.CloseGump(); from.SendGump(new MoongateConfirmGump(from, this)); } @@ -381,7 +381,7 @@ namespace Server.Items } } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID == 1) m_Gate.EndConfirmation(m_From); diff --git a/Projects/Scripts/Items/Skill Items/Magical/Misc/RecallRune.cs b/Projects/Scripts/Items/Skill Items/Magical/Misc/RecallRune.cs index af4e695b7..f78663b1a 100644 --- a/Projects/Scripts/Items/Skill Items/Magical/Misc/RecallRune.cs +++ b/Projects/Scripts/Items/Skill Items/Magical/Misc/RecallRune.cs @@ -1,5 +1,4 @@ using Server.Multis; -using Server.Prompts; using Server.Regions; namespace Server.Items diff --git a/Projects/Scripts/Items/Skill Items/Magical/Potions/Explosion Potions/BaseExplosionPotion.cs b/Projects/Scripts/Items/Skill Items/Magical/Potions/Explosion Potions/BaseExplosionPotion.cs index 84957e0fb..fcb582922 100644 --- a/Projects/Scripts/Items/Skill Items/Magical/Potions/Explosion Potions/BaseExplosionPotion.cs +++ b/Projects/Scripts/Items/Skill Items/Magical/Potions/Explosion Potions/BaseExplosionPotion.cs @@ -76,8 +76,7 @@ namespace Server.Items from.RevealingAction(); - if (Users == null) - Users = new List(); + Users ??= new List(); if (!Users.Contains(from)) Users.Add(from); @@ -169,7 +168,7 @@ namespace Server.Items Effects.PlaySound(loc, map, 0x307); - Effects.SendLocationEffect(loc, map, 0x36B0, 9, 10, 0, 0); + Effects.SendLocationEffect(loc, map, 0x36B0, 9); int alchemyBonus = 0; if (direct) diff --git a/Projects/Scripts/Items/Skill Items/Magical/Potions/NightSight.cs b/Projects/Scripts/Items/Skill Items/Magical/Potions/NightSight.cs index c4bc72042..d5256e9aa 100644 --- a/Projects/Scripts/Items/Skill Items/Magical/Potions/NightSight.cs +++ b/Projects/Scripts/Items/Skill Items/Magical/Potions/NightSight.cs @@ -29,7 +29,7 @@ namespace Server.Items public override void Drink(Mobile from) { - if (from.BeginAction()) + if (from.BeginAction()) { new LightCycle.NightSightTimer(from).Start(); from.LightLevel = LightCycle.DungeonLevel / 2; @@ -43,9 +43,7 @@ namespace Server.Items Consume(); } else - { from.SendMessage("You already have nightsight."); - } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Skill Items/Magical/Runebook.cs b/Projects/Scripts/Items/Skill Items/Magical/Runebook.cs index 2bc7d5692..fe054f07e 100644 --- a/Projects/Scripts/Items/Skill Items/Magical/Runebook.cs +++ b/Projects/Scripts/Items/Skill Items/Magical/Runebook.cs @@ -355,13 +355,9 @@ namespace Server.Items if (dropped is RecallRune rune) { if (IsLockedDown && from.AccessLevel < AccessLevel.GameMaster) - { from.SendLocalizedMessage(502413, null, 0x35); // That cannot be done while the book is locked down. - } else if (IsOpen(from)) - { from.SendLocalizedMessage(1005571); // You cannot place objects in the book while viewing the contents. - } else if (Entries.Count < 16) { if (rune.Marked && rune.TargetMap != null) @@ -370,12 +366,12 @@ namespace Server.Items rune.Delete(); - from.Send(new PlaySound(0x42, GetWorldLocation())); + Packets.SendPlaySound(from.NetState, 0x42, GetWorldLocation()); string desc = rune.Description; if (desc == null || (desc = desc.Trim()).Length == 0) - desc = "(indescript)"; + desc = "(nondescript)"; from.SendMessage(desc); @@ -385,15 +381,13 @@ namespace Server.Items from.SendLocalizedMessage(502409); // This rune does not have a marked location. } else - { from.SendLocalizedMessage(502401); // This runebook is full. - } } else if (dropped is RecallScroll) { if (CurCharges < MaxCharges) { - from.Send(new PlaySound(0x249, GetWorldLocation())); + Packets.SendPlaySound(from.NetState, 0x259, GetWorldLocation()); int amount = dropped.Amount; @@ -411,9 +405,7 @@ namespace Server.Items } } else - { from.SendLocalizedMessage(502410); // This book already has the maximum amount of charges. - } } return false; diff --git a/Projects/Scripts/Items/Skill Items/Magical/Spellbook.cs b/Projects/Scripts/Items/Skill Items/Magical/Spellbook.cs index ca99ee343..b97d2ebca 100644 --- a/Projects/Scripts/Items/Skill Items/Magical/Spellbook.cs +++ b/Projects/Scripts/Items/Skill Items/Magical/Spellbook.cs @@ -491,7 +491,7 @@ namespace Server.Items scroll.Delete(); - from.Send(new PlaySound(0x249, GetWorldLocation())); + Packets.SendPlaySound(from.NetState, 0x249, GetWorldLocation()); return true; } } @@ -569,49 +569,16 @@ namespace Server.Items return; if (Parent == null) - { - to.Send(WorldPacket); - } + SendWorldPacketFor(ns); else if (Parent is Item) - { // What will happen if the client doesn't know about our parent? - if (ns.ContainerGridLines) - to.Send(new ContainerContentUpdate6017(this)); - else - to.Send(new ContainerContentUpdate(this)); - } + Packets.SendContainerContentUpdate(ns, this); else if (Parent is Mobile) - { // What will happen if the client doesn't know about our parent? - to.Send(new EquipUpdate(this)); - } + Packets.SendEquipUpdate(ns, this); - if (ns.HighSeas) - to.Send(new DisplaySpellbookHS(this)); - else - to.Send(new DisplaySpellbook(this)); - - if (ObjectPropertyList.Enabled) - { - if (ns.NewSpellbook) - { - to.Send(new NewSpellbookContent(this, ItemID, BookOffset + 1, m_Content)); - } - else - { - if (ns.ContainerGridLines) - to.Send(new SpellbookContent6017(SpellCount, BookOffset + 1, m_Content, this)); - else - to.Send(new SpellbookContent(SpellCount, BookOffset + 1, m_Content, this)); - } - } - else - { - if (ns.ContainerGridLines) - to.Send(new SpellbookContent6017(SpellCount, BookOffset + 1, m_Content, this)); - else - to.Send(new SpellbookContent(SpellCount, BookOffset + 1, m_Content, this)); - } + Packets.SendDisplayContainer(ns, Serial); + Packets.SendSpellbookContent(ns, Serial, ItemID, BookOffset + 1, m_Content); } public override void GetProperties(ObjectPropertyList list) @@ -810,11 +777,9 @@ namespace Server.Items } } - if (Attributes == null) - Attributes = new AosAttributes(this); + Attributes ??= new AosAttributes(this); - if (SkillBonuses == null) - SkillBonuses = new AosSkillBonuses(this); + SkillBonuses ??= new AosSkillBonuses(this); if (Core.AOS && Parent is Mobile mobile) SkillBonuses.AddTo(mobile); diff --git a/Projects/Scripts/Items/Skill Items/Misc/Bandage.cs b/Projects/Scripts/Items/Skill Items/Misc/Bandage.cs index 752c68f87..f842d091d 100644 --- a/Projects/Scripts/Items/Skill Items/Misc/Bandage.cs +++ b/Projects/Scripts/Items/Skill Items/Misc/Bandage.cs @@ -387,7 +387,7 @@ namespace Server.Items double toHeal = min + Utility.RandomDouble() * (max - min); if (Patient.Body.IsMonster || Patient.Body.IsAnimal) - toHeal += Patient.HitsMax / 100; + toHeal += Patient.HitsMax / 100.0; if (Core.AOS) toHeal -= toHeal * Slips * 0.35; // TODO: Verify algorithm diff --git a/Projects/Scripts/Items/Skill Items/Misc/FireHorn.cs b/Projects/Scripts/Items/Skill Items/Misc/FireHorn.cs index 5e0d9c5d0..127cde348 100644 --- a/Projects/Scripts/Items/Skill Items/Misc/FireHorn.cs +++ b/Projects/Scripts/Items/Skill Items/Misc/FireHorn.cs @@ -79,9 +79,8 @@ namespace Server.Items from.Backpack.ConsumeUpTo(typeof(SulfurousAsh), sulfAsh); from.PlaySound(0x15F); - Effects.SendPacket(from, from.Map, - new HuedEffect(EffectType.Moving, from.Serial, Serial.Zero, 0x36D4, from.Location, loc, 5, 0, false, true, 0, - 0)); + + Effects.SendMovingEffect(from, loc, from.Map, 0x36D4, 5, 0, false, true); IPooledEnumerable eable = from.Map.GetMobilesInRange(new Point3D(loc), 2); @@ -92,11 +91,9 @@ namespace Server.Items || Core.AOS && !from.InLOS(m)) return false; - if (m.Player) - playerVsPlayer = true; + playerVsPlayer |= m.Player; return true; - }).ToList(); eable.Free(); diff --git a/Projects/Scripts/Items/Skill Items/Musical Instruments/BaseInstrument.cs b/Projects/Scripts/Items/Skill Items/Musical Instruments/BaseInstrument.cs index b1e840c8b..462ba6d62 100644 --- a/Projects/Scripts/Items/Skill Items/Musical Instruments/BaseInstrument.cs +++ b/Projects/Scripts/Items/Skill Items/Musical Instruments/BaseInstrument.cs @@ -406,13 +406,8 @@ namespace Server.Items number = 1041000; } - if (attrs.Count == 0 && Crafter == null && Name != null) - return; - - EquipmentInfo eqInfo = new EquipmentInfo(number, m_Crafter, false, - attrs.ToArray()); - - from.Send(new DisplayEquipmentInfo(this, eqInfo)); + if (attrs.Count > 0 || Crafter != null || Name == null) + EquipmentPackets.SendDisplayEquipmentInfo(from.NetState, this, number, m_Crafter, false, attrs); } public override void Serialize(GenericWriter writer) diff --git a/Projects/Scripts/Items/Skill Items/Ninjitsu/LeatherNinjaBelt.cs b/Projects/Scripts/Items/Skill Items/Ninjitsu/LeatherNinjaBelt.cs index 2c77e45ea..35773aa8c 100644 --- a/Projects/Scripts/Items/Skill Items/Ninjitsu/LeatherNinjaBelt.cs +++ b/Projects/Scripts/Items/Skill Items/Ninjitsu/LeatherNinjaBelt.cs @@ -6,7 +6,7 @@ using Server.Mobiles; namespace Server.Items { [Flippable(0x2790, 0x27DB)] - public class LeatherNinjaBelt : BaseWaist, IDyable, INinjaWeapon + public class LeatherNinjaBelt : BaseWaist, INinjaWeapon { private Poison m_Poison; private int m_PoisonCharges; @@ -27,18 +27,18 @@ namespace Server.Items public override CraftResource DefaultResource => CraftResource.RegularLeather; - public virtual int WrongAmmoMessage => 1063301; //You can only place shuriken in a ninja belt. - public virtual int NoFreeHandMessage => 1063299; //You must have a free hand to throw shuriken. - public virtual int EmptyWeaponMessage => 1063297; //You have no shuriken in your ninja belt! - public virtual int RecentlyUsedMessage => 1063298; //You cannot throw another shuriken yet. - public virtual int FullWeaponMessage => 1063302; //You cannot add any more shuriken. + public int WrongAmmoMessage => 1063301; //You can only place shuriken in a ninja belt. + public int NoFreeHandMessage => 1063299; //You must have a free hand to throw shuriken. + public int EmptyWeaponMessage => 1063297; //You have no shuriken in your ninja belt! + public int RecentlyUsedMessage => 1063298; //You cannot throw another shuriken yet. + public int FullWeaponMessage => 1063302; //You cannot add any more shuriken. - public virtual int WeaponMinRange => 2; - public virtual int WeaponMaxRange => 10; + public int WeaponMinRange => 2; + public int WeaponMaxRange => 10; - public virtual int WeaponDamage => Utility.RandomMinMax(3, 5); + public int WeaponDamage => Utility.RandomMinMax(3, 5); - public virtual Type AmmoType => typeof(Shuriken); + public Type AmmoType => typeof(Shuriken); [CommandProperty(AccessLevel.GameMaster)] public int UsesRemaining @@ -81,7 +81,8 @@ namespace Server.Items public void AttackAnimation(Mobile from, Mobile to) { - if (from.Body.IsHuman) from.Animate(from.Mounted ? 26 : 9, 7, 1, true, false, 0); + if (from.Body.IsHuman) + from.Animate(from.Mounted ? 26 : 9, 7, 1, true, false, 0); from.PlaySound(0x23A); from.MovingEffect(to, 0x27AC, 1, 0, false, false); @@ -156,4 +157,4 @@ namespace Server.Items } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Skill Items/Tailor Items/Misc/Dyes.cs b/Projects/Scripts/Items/Skill Items/Tailor Items/Misc/Dyes.cs index 8a86ab078..ff72147f8 100644 --- a/Projects/Scripts/Items/Skill Items/Tailor Items/Misc/Dyes.cs +++ b/Projects/Scripts/Items/Skill Items/Tailor Items/Misc/Dyes.cs @@ -1,4 +1,3 @@ -using Server.HuePickers; using Server.Targeting; namespace Server.Items diff --git a/Projects/Scripts/Items/Skill Items/Thief/DisguisePersistance.cs b/Projects/Scripts/Items/Skill Items/Thief/DisguisePersistance.cs index 50d3b0ccf..f41182141 100644 --- a/Projects/Scripts/Items/Skill Items/Thief/DisguisePersistance.cs +++ b/Projects/Scripts/Items/Skill Items/Thief/DisguisePersistance.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; namespace Server.Items { @@ -31,12 +30,10 @@ namespace Server.Items writer.Write(timerCount); - foreach (KeyValuePair entry in DisguiseTimers.Timers) + foreach (var (m, value) in DisguiseTimers.Timers) { - Mobile m = entry.Key; - writer.Write(m); - writer.Write(entry.Value.Next - DateTime.UtcNow); + writer.Write(value.Next - DateTime.UtcNow); writer.Write(m.NameMod); } } diff --git a/Projects/Scripts/Items/Skill Items/Tinkering/Spyglass.cs b/Projects/Scripts/Items/Skill Items/Tinkering/Spyglass.cs index 2dae504f3..711d7b173 100644 --- a/Projects/Scripts/Items/Skill Items/Tinkering/Spyglass.cs +++ b/Projects/Scripts/Items/Skill Items/Tinkering/Spyglass.cs @@ -20,10 +20,10 @@ namespace Server.Items from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 1008155); // You peer into the heavens, seeking the moons... - from.Send(new MessageLocalizedAffix(from.Serial, from.Body, MessageType.Regular, 0x3B2, 3, - 1008146 + (int)Clock.GetMoonPhase(Map.Trammel, from.X, from.Y), "", AffixType.Prepend, "Trammel : ", "")); - from.Send(new MessageLocalizedAffix(from.Serial, from.Body, MessageType.Regular, 0x3B2, 3, - 1008146 + (int)Clock.GetMoonPhase(Map.Felucca, from.X, from.Y), "", AffixType.Prepend, "Felucca : ", "")); + Packets.SendMessageLocalizedAffix(from.NetState, from.Serial, from.Body, MessageType.Regular, 0x3B2, 3, + 1008146 + (int)Clock.GetMoonPhase(Map.Trammel, from.X, from.Y), "", AffixType.Prepend, "Trammel : "); + Packets.SendMessageLocalizedAffix(from.NetState, from.Serial, from.Body, MessageType.Regular, 0x3B2, 3, + 1008146 + (int)Clock.GetMoonPhase(Map.Felucca, from.X, from.Y), "", AffixType.Prepend, "Felucca : "); if (from is PlayerMobile player) { @@ -33,7 +33,7 @@ namespace Server.Items return; FindIngredientObjective obj = qs.FindObjective(); - + if (obj?.Completed == false && obj.Ingredient == Ingredient.StarChart) { Clock.GetTime(from.Map, from.X, from.Y, out int hours, out int _); @@ -68,4 +68,4 @@ namespace Server.Items int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Special/8th Anniversary Items/Dawn's Music Box/DawnsMusicBox.cs b/Projects/Scripts/Items/Special/8th Anniversary Items/Dawn's Music Box/DawnsMusicBox.cs index e5d2fcfb0..3216bf7d0 100644 --- a/Projects/Scripts/Items/Special/8th Anniversary Items/Dawn's Music Box/DawnsMusicBox.cs +++ b/Projects/Scripts/Items/Special/8th Anniversary Items/Dawn's Music Box/DawnsMusicBox.cs @@ -7,16 +7,6 @@ using Server.Network; namespace Server.Items { - public sealed class StopMusic : Packet - { - public static readonly Packet Instance = SetStatic(new StopMusic()); - - public StopMusic() : base(0x6D, 3) - { - m_Stream.Write((short)0x1FFF); - } - } - [Flippable(0x2AF9, 0x2AFD)] public class DawnsMusicBox : Item, ISecurable { @@ -158,7 +148,7 @@ namespace Server.Items else m_ItemID = ItemID; - m.Send(new PlayMusic(music)); + Packets.SendPlayMusic(m.NetState, music); m_Timer = Timer.DelayCall(TimeSpan.FromSeconds(0.5), TimeSpan.FromSeconds(0.5), 4, Animate); } @@ -167,7 +157,7 @@ namespace Server.Items if (m_Timer?.Running == true) m_Timer.Stop(); - m.Send(StopMusic.Instance); + Packets.SendStopMusic(m.NetState); if (m_Count > 0) ItemID = m_ItemID; diff --git a/Projects/Scripts/Items/Special/Evil Home Decor Collection/SacrificialAltar.cs b/Projects/Scripts/Items/Special/Evil Home Decor Collection/SacrificialAltar.cs index c8dfa3341..faa446550 100644 --- a/Projects/Scripts/Items/Special/Evil Home Decor Collection/SacrificialAltar.cs +++ b/Projects/Scripts/Items/Special/Evil Home Decor Collection/SacrificialAltar.cs @@ -108,7 +108,7 @@ namespace Server.Items Point3D location = Location; location.Z += 10; - Effects.SendLocationEffect(location, Map, 0x3709, 10, 10, 0x356, 0); + Effects.SendLocationEffect(location, Map, 0x3709, 10, 10, 0x356); Effects.PlaySound(location, Map, 0x32E); if (Items.Count > 0) diff --git a/Projects/Scripts/Items/Special/House Raffle/HouseRaffleStone.cs b/Projects/Scripts/Items/Special/House Raffle/HouseRaffleStone.cs index 9186c5dc1..a23ff661a 100644 --- a/Projects/Scripts/Items/Special/House Raffle/HouseRaffleStone.cs +++ b/Projects/Scripts/Items/Special/House Raffle/HouseRaffleStone.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Net; using System.Text; using Server.Accounting; @@ -290,22 +291,9 @@ namespace Server.Items } } - private bool HasEntered(Mobile from) - { - if (!(from.Account is Account acc)) - return false; - - foreach (RaffleEntry entry in Entries) - if (entry.From != null) - { - Account entryAcc = entry.From.Account as Account; - - if (entryAcc == acc) - return true; - } - - return false; - } + private bool HasEntered(Mobile from) => + from.Account is Account acc && + (from entry in Entries select entry.From?.Account as Account).Any(entryAcc => entryAcc == acc); private bool IsAtIPLimit(Mobile from) { @@ -315,12 +303,7 @@ namespace Server.Items IPAddress address = from.NetState.Address; int tickets = 0; - foreach (RaffleEntry entry in Entries) - if (Utility.IPMatchClassC(entry.Address, address)) - if (++tickets >= EntryLimitPerIP) - return true; - - return false; + return Entries.Where(entry => Utility.IPMatchClassC(entry.Address, address)).Any(entry => ++tickets >= EntryLimitPerIP); } public static string FormatLocation(Point3D loc, Map map, bool displayMap) diff --git a/Projects/Scripts/Items/Special/Solen Items/BagOfSending.cs b/Projects/Scripts/Items/Special/Solen Items/BagOfSending.cs index 33832fb3d..a186285ba 100644 --- a/Projects/Scripts/Items/Special/Solen Items/BagOfSending.cs +++ b/Projects/Scripts/Items/Special/Solen Items/BagOfSending.cs @@ -219,54 +219,34 @@ namespace Server.Items return; if (from.Region.IsPartOf()) - { from.SendMessage("You may not do that in jail."); - } else if (!m_Bag.IsChildOf(from.Backpack)) - { - MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1062334, - 0x59); // The bag of sending must be in your backpack. 1054107 is gone from client, using generic response - } + MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1054107, + 0x59); // This item must be in your backpack. else if (m_Bag.Charges == 0) - { MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1042544, 0x59); // This item is out of charges. - } else if (targeted is Item item) { int reqCharges = (int)Math.Max(1, Math.Ceiling(item.TotalWeight / 10.0)); if (!item.IsChildOf(from.Backpack)) - { MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1054152, 0x59); // You may only send items from your backpack to your bank box. - } else if (item is BagOfSending || item is Container) - { - from.Send(new AsciiMessage(m_Bag.Serial, m_Bag.ItemID, MessageType.Regular, 0x3B2, 3, "", - "You cannot send a container through the bag of sending.")); - } + Packets.SendAsciiMessage(from.NetState, m_Bag.Serial, m_Bag.ItemID, MessageType.Regular, 0x3B2, 3, "", + "You cannot send a container through the bag of sending." ); else if (item.LootType == LootType.Cursed) - { MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1054108, 0x59); // The bag of sending rejects the cursed item. - } else if (!item.VerifyMove(from) || item is QuestItem || item.Nontransferable) - { MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1054109, 0x59); // The bag of sending rejects that item. - } else if (SpellHelper.IsDoomGauntlet(from.Map, from.Location)) - { from.SendLocalizedMessage(1062089); // You cannot use that here. - } else if (!from.BankBox.TryDropItem(from, item, false)) - { MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1054110, 0x59); // Your bank box is full. - } else if (Core.ML && reqCharges > m_Bag.Charges) - { from.SendLocalizedMessage(1079932); //You don't have enough charges to send that much weight - } else { m_Bag.Charges -= Core.ML ? reqCharges : 1; @@ -278,4 +258,4 @@ namespace Server.Items } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Special/Solen Items/BallOfSummoning.cs b/Projects/Scripts/Items/Special/Solen Items/BallOfSummoning.cs index 24a0bee0e..27e16780b 100644 --- a/Projects/Scripts/Items/Special/Solen Items/BallOfSummoning.cs +++ b/Projects/Scripts/Items/Special/Solen Items/BallOfSummoning.cs @@ -177,41 +177,27 @@ namespace Server.Items return; if (Charges == 0) - { SendLocalizedMessageTo(from, 1054122); // The Crystal Ball darkens. It must be charged before it can be used again. - } else if (pet is BaseMount mount && mount.Rider == from) - { MessageHelper.SendLocalizedMessageTo(this, from, 1054124, 0x36); // The Crystal Ball fills with a yellow mist. Why would you summon your pet while riding it? - } else if (pet.Map == Map.Internal && (!pet.IsStabled || from.Followers + pet.ControlSlots > from.FollowersMax)) - { MessageHelper.SendLocalizedMessageTo(this, from, 1054125, 0x5); // The Crystal Ball fills with a blue mist. Your pet is not responding to the summons. - } else if ((!pet.Controlled || pet.ControlMaster != from) && !from.Stabled.Contains(pet)) - { MessageHelper.SendLocalizedMessageTo(this, from, 1054126, 0x8FD); // The Crystal Ball fills with a grey mist. You are not the owner of the pet you are attempting to summon. - } else if (!pet.IsBonded) - { MessageHelper.SendLocalizedMessageTo(this, from, 1054127, 0x22); // The Crystal Ball fills with a red mist. You appear to have let your bond to your pet deteriorate. - } else if (from.Map == Map.Ilshenar || from.Region.IsPartOf() || from.Region.IsPartOf() || from.Region.IsPartOf()) - { - from.Send(new AsciiMessage(Serial, ItemID, MessageType.Regular, 0x22, 3, "", - "You cannot summon your pet to this location.")); - } + Packets.SendAsciiMessage(from.NetState, Serial, ItemID, MessageType.Regular, 0x22, 3, "", + "You cannot summon your pet to this location."); else if (Core.ML && from is PlayerMobile mobile && DateTime.UtcNow < mobile.LastPetBallTime.AddSeconds(15.0)) - { MessageHelper.SendLocalizedMessageTo(this, mobile, 1080072, 0x22); // You must wait a few seconds before you can summon your pet. - } else { if (Core.ML) diff --git a/Projects/Scripts/Items/Special/Solen Items/BraceletOfBinding.cs b/Projects/Scripts/Items/Special/Solen Items/BraceletOfBinding.cs index 4417b9b8e..9e4478191 100644 --- a/Projects/Scripts/Items/Special/Solen Items/BraceletOfBinding.cs +++ b/Projects/Scripts/Items/Special/Solen Items/BraceletOfBinding.cs @@ -5,7 +5,6 @@ using Server.Factions; using Server.Misc; using Server.Mobiles; using Server.Network; -using Server.Prompts; using Server.Regions; using Server.Spells; using Server.Targeting; diff --git a/Projects/Scripts/Items/Special/SoulStone.cs b/Projects/Scripts/Items/Special/SoulStone.cs index ea64d856e..aee2dd8ed 100644 --- a/Projects/Scripts/Items/Special/SoulStone.cs +++ b/Projects/Scripts/Items/Special/SoulStone.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using Server.Accounting; using Server.Engines.VeteranRewards; using Server.Factions; @@ -579,7 +580,6 @@ namespace Server.Items return; } - SkillName skill = m_Stone.Skill; double skillValue = m_Stone.SkillValue; Skill fromSkill = from.Skills[m_Stone.Skill]; @@ -589,27 +589,8 @@ namespace Server.Items */ int requiredAmount = (int)(skillValue * 10) - fromSkill.BaseFixedPoint - (from.SkillsCap - from.SkillsTotal); - bool cannotAbsorb = false; - - if (fromSkill.Lock != SkillLock.Up) - { - cannotAbsorb = true; - } - else if (requiredAmount > 0) - { - int available = 0; - - for (int i = 0; i < from.Skills.Length; ++i) - { - if (from.Skills[i].Lock != SkillLock.Down) - continue; - - available += from.Skills[i].BaseFixedPoint; - } - - if (requiredAmount > available) - cannotAbsorb = true; - } + bool cannotAbsorb = fromSkill.Lock != SkillLock.Up || requiredAmount > 0 && + requiredAmount > from.Skills.Where(t => t.Lock == SkillLock.Down).Sum(t => t.BaseFixedPoint); if (cannotAbsorb) { diff --git a/Projects/Scripts/Items/Special/Special Scrolls/PowerScroll.cs b/Projects/Scripts/Items/Special/Special Scrolls/PowerScroll.cs index 1e567af7b..c5de04d58 100644 --- a/Projects/Scripts/Items/Special/Special Scrolls/PowerScroll.cs +++ b/Projects/Scripts/Items/Special/Special Scrolls/PowerScroll.cs @@ -81,10 +81,12 @@ namespace Server.Items } public override int Message => - 1049469; /* Using a scroll increases the maximum amount of a specific skill or your maximum statistics. - * When used, the effect is not immediately seen without a gain of points with that skill or statistics. - * You can view your maximum skill values in your skills window. - * You can view your maximum statistic value in your statistics window. */ + 1049469; + /* Using a scroll increases the maximum amount of a specific skill or your maximum statistics. + * When used, the effect is not immediately seen without a gain of points with that skill or statistics. + * You can view your maximum skill values in your skills window. + * You can view your maximum statistic value in your statistics window. + */ public override int Title { @@ -93,10 +95,12 @@ namespace Server.Items double level = (Value - 105.0) / 5.0; if (level >= 0.0 && level <= 3.0 && Value % 5.0 == 0.0) - return 1049635 + (int)level; /* Wonderous Scroll (105 Skill): OR - * Exalted Scroll (110 Skill): OR - * Mythical Scroll (115 Skill): OR - * Legendary Scroll (120 Skill): */ + return 1049635 + (int)level; + /* Wonderous Scroll (105 Skill): OR + * Exalted Scroll (110 Skill): OR + * Mythical Scroll (115 Skill): OR + * Legendary Scroll (120 Skill): + */ return 0; } @@ -154,10 +158,12 @@ namespace Server.Items double level = (Value - 105.0) / 5.0; if (level >= 0.0 && level <= 3.0 && Value % 5.0 == 0.0) - list.Add(1049639 + (int)level, GetNameLocalized()); /* a wonderous scroll of ~1_type~ (105 Skill) OR - * an exalted scroll of ~1_type~ (110 Skill) OR - * a mythical scroll of ~1_type~ (115 Skill) OR - * a legendary scroll of ~1_type~ (120 Skill) */ + list.Add(1049639 + (int)level, GetNameLocalized()); + /* a wonderous scroll of ~1_type~ (105 Skill) OR + * an exalted scroll of ~1_type~ (110 Skill) OR + * a mythical scroll of ~1_type~ (115 Skill) OR + * a legendary scroll of ~1_type~ (120 Skill) + */ else list.Add("a power scroll of {0} ({1} Skill)", GetName(), Value); } diff --git a/Projects/Scripts/Items/Special/Special Scrolls/ScrollofAlacrity.cs b/Projects/Scripts/Items/Special/Special Scrolls/ScrollofAlacrity.cs index 1728e261d..aa4921f2f 100644 --- a/Projects/Scripts/Items/Special/Special Scrolls/ScrollofAlacrity.cs +++ b/Projects/Scripts/Items/Special/Special Scrolls/ScrollofAlacrity.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using Server.Engines.MLQuests; using Server.Engines.MLQuests.Objectives; using Server.Mobiles; @@ -21,9 +22,11 @@ namespace Server.Items public override int LabelNumber => 1078604; // Scroll of Alacrity public override int Message => - 1078602; /*Using a Scroll of Transcendence for a given skill will permanently increase your current - *level in that skill by the amount of points displayed on the scroll. - *As you may not gain skills beyond your maximum skill cap, any excess points will be lost.*/ + 1078602; + /* Using a Scroll of Transcendence for a given skill will permanently increase your current + * level in that skill by the amount of points displayed on the scroll. + * As you may not gain skills beyond your maximum skill cap, any excess points will be lost. + */ public override string DefaultTitle => "Scroll of Alacrity:"; @@ -74,8 +77,10 @@ namespace Server.Items if (tskill >= tcap || from.Skills[Skill].Lock != SkillLock.Up) { from.SendLocalizedMessage( - 1094935); /*You cannot increase this skill at this time. The skill may be locked or set to lower in your skill menu. - *If you are at your total skill cap, you must use a Powerscroll to increase your current skill cap.*/ + 1094935); + /* You cannot increase this skill at this time. The skill may be locked or set to lower in your skill menu. + * If you are at your total skill cap, you must use a Powerscroll to increase your current skill cap. + */ return; } diff --git a/Projects/Scripts/Items/Special/Special Scrolls/ScrollofTranscendence.cs b/Projects/Scripts/Items/Special/Special Scrolls/ScrollofTranscendence.cs index 3eeefe93c..d1d1c66a0 100644 --- a/Projects/Scripts/Items/Special/Special Scrolls/ScrollofTranscendence.cs +++ b/Projects/Scripts/Items/Special/Special Scrolls/ScrollofTranscendence.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using Server.Engines.MLQuests; using Server.Engines.MLQuests.Objectives; using Server.Mobiles; @@ -21,9 +22,11 @@ namespace Server.Items public override int LabelNumber => 1094934; // Scroll of Transcendence public override int Message => - 1094933; /*Using a Scroll of Transcendence for a given skill will permanently increase your current - *level in that skill by the amount of points displayed on the scroll. - *As you may not gain skills beyond your maximum skill cap, any excess points will be lost.*/ + 1094933; + /* Using a Scroll of Transcendence for a given skill will permanently increase your current + * level in that skill by the amount of points displayed on the scroll. + * As you may not gain skills beyond your maximum skill cap, any excess points will be lost. + */ public override string DefaultTitle => $"Scroll of Transcendence ({Value} Skill):"; @@ -112,8 +115,10 @@ namespace Server.Items if (!canGain) { from.SendLocalizedMessage( - 1094935); /*You cannot increase this skill at this time. The skill may be locked or set to lower in your skill menu. - *If you are at your total skill cap, you must use a Powerscroll to increase your current skill cap.*/ + 1094935); + /* You cannot increase this skill at this time. The skill may be locked or set to lower in your skill menu. + * If you are at your total skill cap, you must use a Powerscroll to increase your current skill cap. + */ return; } diff --git a/Projects/Scripts/Items/Special/Special Scrolls/SpecialScroll.cs b/Projects/Scripts/Items/Special/Special Scrolls/SpecialScroll.cs index 40fefa434..9090b11c5 100644 --- a/Projects/Scripts/Items/Special/Special Scrolls/SpecialScroll.cs +++ b/Projects/Scripts/Items/Special/Special Scrolls/SpecialScroll.cs @@ -158,7 +158,7 @@ namespace Server.Items AddHtmlLocalized(310, 20, 120, 20, AosSkillBonuses.GetLabel(m_Scroll.Skill), 0xFFFFFF); } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (info.ButtonID == 1) m_Scroll.Use(m_Mobile); diff --git a/Projects/Scripts/Items/Special/Special Scrolls/StatScroll.cs b/Projects/Scripts/Items/Special/Special Scrolls/StatScroll.cs index 4ebb96f5c..c3de85fcb 100644 --- a/Projects/Scripts/Items/Special/Special Scrolls/StatScroll.cs +++ b/Projects/Scripts/Items/Special/Special Scrolls/StatScroll.cs @@ -12,10 +12,12 @@ namespace Server.Items } public override int Message => - 1049469; /* Using a scroll increases the maximum amount of a specific skill or your maximum statistics. - * When used, the effect is not immediately seen without a gain of points with that skill or statistics. - * You can view your maximum skill values in your skills window. - * You can view your maximum statistic value in your statistics window. */ + 1049469; + /* Using a scroll increases the maximum amount of a specific skill or your maximum statistics. + * When used, the effect is not immediately seen without a gain of points with that skill or statistics. + * You can view your maximum skill values in your skills window. + * You can view your maximum statistic value in your statistics window. + */ public override int Title { @@ -24,11 +26,13 @@ namespace Server.Items int level = ((int)Value - 230) / 5; if (level >= 0 && level <= 4 && Value % 5 == 0) - return 1049458 + level; /* Wonderous Scroll (+5 Maximum Stats): OR - * Exalted Scroll (+10 Maximum Stats): OR - * Mythical Scroll (+15 Maximum Stats): OR - * Legendary Scroll (+20 Maximum Stats): OR - * Ultimate Scroll (+25 Maximum Stats): */ + return 1049458 + level; + /* Wonderous Scroll (+5 Maximum Stats): OR + * Exalted Scroll (+10 Maximum Stats): OR + * Mythical Scroll (+15 Maximum Stats): OR + * Legendary Scroll (+20 Maximum Stats): OR + * Ultimate Scroll (+25 Maximum Stats): + */ return 0; } @@ -42,11 +46,13 @@ namespace Server.Items int level = ((int)Value - 230) / 5; if (level >= 0 && level <= 4 && (int)Value % 5 == 0) - list.Add(1049463 + level, "#1049476"); /* a wonderous scroll of ~1_type~ (+5 Maximum Stats) OR - * an exalted scroll of ~1_type~ (+10 Maximum Stats) OR - * a mythical scroll of ~1_type~ (+15 Maximum Stats) OR - * a legendary scroll of ~1_type~ (+20 Maximum Stats) OR - * an ultimate scroll of ~1_type~ (+25 Maximum Stats) */ + list.Add(1049463 + level, "#1049476"); + /* a wonderous scroll of ~1_type~ (+5 Maximum Stats) OR + * an exalted scroll of ~1_type~ (+10 Maximum Stats) OR + * a mythical scroll of ~1_type~ (+15 Maximum Stats) OR + * a legendary scroll of ~1_type~ (+20 Maximum Stats) OR + * an ultimate scroll of ~1_type~ (+25 Maximum Stats) + */ else list.Add("a scroll of power ({0}{1} Maximum Stats)", Value - 225 >= 0 ? "+" : "", Value - 225); } diff --git a/Projects/Scripts/Items/Special/Veteran Rewards/AnkhOfSacrifice.cs b/Projects/Scripts/Items/Special/Veteran Rewards/AnkhOfSacrifice.cs index 4d81265d3..cbdb6164a 100644 --- a/Projects/Scripts/Items/Special/Veteran Rewards/AnkhOfSacrifice.cs +++ b/Projects/Scripts/Items/Special/Veteran Rewards/AnkhOfSacrifice.cs @@ -135,9 +135,9 @@ namespace Server.Items { } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { - Mobile from = state.Mobile; + Mobile from = sender.Mobile; if (info.ButtonID == 1 || info.ButtonID == 2) { @@ -147,9 +147,10 @@ namespace Server.Items return; } - if (from is PlayerMobile mobile) mobile.AnkhNextUse = DateTime.UtcNow + TimeSpan.FromHours(1); + if (from is PlayerMobile mobile) + mobile.AnkhNextUse = DateTime.UtcNow + TimeSpan.FromHours(1); - base.OnResponse(state, info); + base.OnResponse(sender, info); } } } diff --git a/Projects/Scripts/Items/Special/Veteran Rewards/Brazier.cs b/Projects/Scripts/Items/Special/Veteran Rewards/Brazier.cs index 7f43e8011..724723140 100644 --- a/Projects/Scripts/Items/Special/Veteran Rewards/Brazier.cs +++ b/Projects/Scripts/Items/Special/Veteran Rewards/Brazier.cs @@ -63,8 +63,7 @@ namespace Server.Items public void TurnOn() { - if (m_Fire == null) - m_Fire = new Item(); + m_Fire ??= new Item(); m_Fire.ItemID = 0x19AB; m_Fire.Movable = false; diff --git a/Projects/Scripts/Items/Special/Veteran Rewards/Cannon.cs b/Projects/Scripts/Items/Special/Veteran Rewards/Cannon.cs index 3c7c68035..a16a27f78 100644 --- a/Projects/Scripts/Items/Special/Veteran Rewards/Cannon.cs +++ b/Projects/Scripts/Items/Special/Veteran Rewards/Cannon.cs @@ -63,37 +63,37 @@ namespace Server.Items switch (direction) { case CannonDirection.North: - { - AddComponent(new CannonAddonComponent(0xE8D), 0, 0, 0); - AddComponent(new CannonAddonComponent(0xE8C), 0, 1, 0); - AddComponent(new CannonAddonComponent(0xE8B), 0, 2, 0); + { + AddComponent(new CannonAddonComponent(0xE8D), 0, 0, 0); + AddComponent(new CannonAddonComponent(0xE8C), 0, 1, 0); + AddComponent(new CannonAddonComponent(0xE8B), 0, 2, 0); - break; - } + break; + } case CannonDirection.East: - { - AddComponent(new CannonAddonComponent(0xE96), 0, 0, 0); - AddComponent(new CannonAddonComponent(0xE95), -1, 0, 0); - AddComponent(new CannonAddonComponent(0xE94), -2, 0, 0); + { + AddComponent(new CannonAddonComponent(0xE96), 0, 0, 0); + AddComponent(new CannonAddonComponent(0xE95), -1, 0, 0); + AddComponent(new CannonAddonComponent(0xE94), -2, 0, 0); - break; - } + break; + } case CannonDirection.South: - { - AddComponent(new CannonAddonComponent(0xE91), 0, 0, 0); - AddComponent(new CannonAddonComponent(0xE92), 0, -1, 0); - AddComponent(new CannonAddonComponent(0xE93), 0, -2, 0); + { + AddComponent(new CannonAddonComponent(0xE91), 0, 0, 0); + AddComponent(new CannonAddonComponent(0xE92), 0, -1, 0); + AddComponent(new CannonAddonComponent(0xE93), 0, -2, 0); - break; - } + break; + } default: - { - AddComponent(new CannonAddonComponent(0xE8E), 0, 0, 0); - AddComponent(new CannonAddonComponent(0xE8F), 1, 0, 0); - AddComponent(new CannonAddonComponent(0xE90), 2, 0, 0); + { + AddComponent(new CannonAddonComponent(0xE8E), 0, 0, 0); + AddComponent(new CannonAddonComponent(0xE8F), 1, 0, 0); + AddComponent(new CannonAddonComponent(0xE90), 2, 0, 0); - break; - } + break; + } } } @@ -114,7 +114,7 @@ namespace Server.Items } [CommandProperty(AccessLevel.GameMaster)] - public CannonDirection CannonDirection{ get; private set; } + public CannonDirection CannonDirection { get; private set; } [CommandProperty(AccessLevel.GameMaster)] public int Charges @@ -261,34 +261,19 @@ namespace Server.Items { if (!Utility.InRange(new Point3D(p), m_Cannon.Location, 2)) { - bool allow = false; int x = p.X - m_Cannon.X; int y = p.Y - m_Cannon.Y; - switch (m_Cannon.CannonDirection) + bool allow = m_Cannon.CannonDirection switch { - case CannonDirection.North: - if (y < 0 && Math.Abs(x) <= -y / 3) - allow = true; - break; - case CannonDirection.East: - if (x > 0 && Math.Abs(y) <= x / 3) - allow = true; - - break; - case CannonDirection.South: - if (y > 0 && Math.Abs(x) <= y / 3) - allow = true; - - break; - case CannonDirection.West: - if (x < 0 && Math.Abs(y) <= -x / 3) - allow = true; - - break; - } + CannonDirection.North => y < 0 && Math.Abs(x) <= -y / 3, + CannonDirection.East => x > 0 && Math.Abs(y) <= x / 3, + CannonDirection.South => y > 0 && Math.Abs(x) <= y / 3, + CannonDirection.West => x < 0 && Math.Abs(y) <= -x / 3, + _ => false, + }; if (allow && Utility.InRange(new Point3D(p), m_Cannon.Location, 14)) m_Cannon.DoFireEffect(p); @@ -301,9 +286,7 @@ namespace Server.Items } } else - { from.SendLocalizedMessage(1049630); // You cannot see that target! - } } protected override void OnTargetOutOfRange(Mobile from, object targeted) @@ -341,10 +324,10 @@ namespace Server.Items AddHtmlLocalized(195, 109, 120, 20, 1076197, 0x7FFF); // Recharge } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (m_Cannon?.Deleted == false && info.ButtonID == (int)Buttons.Recharge) - m_Cannon.Fill(state.Mobile, m_Keg); + m_Cannon.Fill(sender.Mobile, m_Keg); } private enum Buttons @@ -373,7 +356,8 @@ namespace Server.Items public override BaseAddon Addon => new CannonAddon(m_Direction) { - Charges = m_Charges, IsRewardItem = m_IsRewardItem + Charges = m_Charges, + IsRewardItem = m_IsRewardItem }; [CommandProperty(AccessLevel.GameMaster)] diff --git a/Projects/Scripts/Items/Special/Veteran Rewards/WeaponEngravingTool.cs b/Projects/Scripts/Items/Special/Veteran Rewards/WeaponEngravingTool.cs index 481b6c4c5..9090a7077 100644 --- a/Projects/Scripts/Items/Special/Veteran Rewards/WeaponEngravingTool.cs +++ b/Projects/Scripts/Items/Special/Veteran Rewards/WeaponEngravingTool.cs @@ -243,7 +243,7 @@ namespace Server.Items AddTextEntry(75, 245, 350, 40, 0x0, (int)Buttons.Text, ""); } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (m_Tool?.Deleted != false || m_Target?.Deleted != false) return; @@ -319,12 +319,12 @@ namespace Server.Items AddHtmlLocalized(40, 109, 100, 20, 1060051, 0x7FFF); // CANCEL } - public override void OnResponse(NetState state, RelayInfo info) + public override void OnResponse(NetState sender, RelayInfo info) { if (m_Engraver?.Deleted != false || info.ButtonID != (int)Buttons.Confirm) return; - m_Engraver.Recharge(state.Mobile, m_Guildmaster); + m_Engraver.Recharge(sender.Mobile, m_Guildmaster); } private enum Buttons diff --git a/Projects/Scripts/Items/Talismans/TalismanSlayer.cs b/Projects/Scripts/Items/Talismans/TalismanSlayer.cs index 15b84549a..71966f898 100644 --- a/Projects/Scripts/Items/Talismans/TalismanSlayer.cs +++ b/Projects/Scripts/Items/Talismans/TalismanSlayer.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Mobiles; namespace Server.Items @@ -73,9 +74,7 @@ namespace Server.Items }, [TalismanSlayerName.Bovine] = new[] { - typeof(Cow), typeof(Bull), typeof(Gaman) /*, typeof( MinotaurCaptain ), - typeof( MinotaurScout ), typeof( Minotaur )*/ - // TODO TormentedMinotaur + typeof(Cow), typeof(Bull), typeof(Gaman), typeof(TormentedMinotaur) } }; } @@ -83,15 +82,11 @@ namespace Server.Items public static bool Slays(TalismanSlayerName name, Mobile m) { if (m == null || !m_Table.TryGetValue(name, out Type[] types) || types == null) - return false;; + return false; Type type = m.GetType(); - for (int i = 0; i < types.Length; i++) - if (types[i].IsAssignableFrom(type)) - return true; - - return false; + return types.Any(t => t.IsAssignableFrom(type)); } } } diff --git a/Projects/Scripts/Items/Talismans/TalismanSummons.cs b/Projects/Scripts/Items/Talismans/TalismanSummons.cs index e2e4e933f..6863a4c5a 100644 --- a/Projects/Scripts/Items/Talismans/TalismanSummons.cs +++ b/Projects/Scripts/Items/Talismans/TalismanSummons.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Server.ContextMenus; using Server.Items; +using Server.Regions; namespace Server.Mobiles { @@ -396,9 +397,6 @@ namespace Server.Mobiles int version = reader.ReadEncodedInt(); } - /* - // An area attack that only damages staff, wtf? - private DateTime m_NextWave; public void AreaHeatDamage() @@ -408,29 +406,20 @@ namespace Server.Mobiles if ( mob != null ) { if ( mob.InRange( Location, 2 ) ) - { - if ( mob.AccessLevel != AccessLevel.Player ) + if ( mob.AccessLevel == AccessLevel.Player ) { AOS.Damage( mob, Utility.Random( 2, 3 ), 0, 100, 0, 0, 0 ); mob.SendLocalizedMessage( 1008112 ); // The intense heat is damaging you! } - } - GuardedRegion r = Region as GuardedRegion; - - if ( r != null && mob.Alive ) - { + if ( Region is GuardedRegion && mob.Alive ) foreach ( Mobile m in GetMobilesInRange( 2 ) ) - { if ( !mob.CanBeHarmful( m ) ) mob.CriminalAction( false ); - } - } } m_NextWave = DateTime.UtcNow + TimeSpan.FromSeconds( 3 ); } - */ } public class SummonedOrcBrute : BaseTalismanSummon @@ -631,4 +620,4 @@ namespace Server.Mobiles int version = reader.ReadEncodedInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Traps/GasTrap.cs b/Projects/Scripts/Items/Traps/GasTrap.cs index a6950be9c..9bd0efdef 100644 --- a/Projects/Scripts/Items/Traps/GasTrap.cs +++ b/Projects/Scripts/Items/Traps/GasTrap.cs @@ -35,7 +35,7 @@ namespace Server.Items [CommandProperty(AccessLevel.GameMaster)] public GasTrapType Type { - get + get => ItemID switch { return ItemID switch { @@ -69,7 +69,7 @@ namespace Server.Items if (Poison == null || !from.Player || !from.Alive || from.AccessLevel > AccessLevel.Player) return; - Effects.SendLocationEffect(Location, Map, GetBaseID(Type) - 2, 16, 3, GetEffectHue(), 0); + Effects.SendLocationEffect(Location, Map, GetBaseID(Type) - 2, 16, 3, GetEffectHue()); Effects.PlaySound(Location, Map, 0x231); from.ApplyPoison(from, Poison); diff --git a/Projects/Scripts/Items/Traps/GiantSpikeTrap.cs b/Projects/Scripts/Items/Traps/GiantSpikeTrap.cs index f5425d39e..121d9a38e 100644 --- a/Projects/Scripts/Items/Traps/GiantSpikeTrap.cs +++ b/Projects/Scripts/Items/Traps/GiantSpikeTrap.cs @@ -24,7 +24,7 @@ namespace Server.Items if (from.AccessLevel > AccessLevel.Player) return; - Effects.SendLocationEffect(Location, Map, 0x1D99, 48, 2, GetEffectHue(), 0); + Effects.SendLocationEffect(Location, Map, 0x1D99, 48, 2, GetEffectHue()); if (from.Alive && CheckRange(from.Location, 0)) SpellHelper.Damage(TimeSpan.FromTicks(1), from, from, Utility.Dice(10, 7, 0)); diff --git a/Projects/Scripts/Items/Traps/SawTrap.cs b/Projects/Scripts/Items/Traps/SawTrap.cs index 7b1de8d2c..8b28281d1 100644 --- a/Projects/Scripts/Items/Traps/SawTrap.cs +++ b/Projects/Scripts/Items/Traps/SawTrap.cs @@ -26,7 +26,7 @@ namespace Server.Items [CommandProperty(AccessLevel.GameMaster)] public SawTrapType Type { - get + get => ItemID switch { return ItemID switch { @@ -62,7 +62,7 @@ namespace Server.Items if (!from.Alive || from.AccessLevel > AccessLevel.Player) return; - Effects.SendLocationEffect(Location, Map, GetBaseID(Type) + 1, 6, 3, GetEffectHue(), 0); + Effects.SendLocationEffect(Location, Map, GetBaseID(Type) + 1, 6, 3, GetEffectHue()); Effects.PlaySound(Location, Map, 0x21C); SpellHelper.Damage(TimeSpan.FromTicks(1), from, from, Utility.RandomMinMax(5, 15)); diff --git a/Projects/Scripts/Items/Traps/SpikeTrap.cs b/Projects/Scripts/Items/Traps/SpikeTrap.cs index 0a4a636df..843b02e07 100644 --- a/Projects/Scripts/Items/Traps/SpikeTrap.cs +++ b/Projects/Scripts/Items/Traps/SpikeTrap.cs @@ -26,7 +26,7 @@ namespace Server.Items [CommandProperty(AccessLevel.GameMaster)] public SpikeTrapType Type { - get + get => ItemID switch { return ItemID switch { @@ -56,13 +56,7 @@ namespace Server.Items public bool Extended { get => ItemID == GetExtendedID(Type); - set - { - if (value) - ItemID = GetExtendedID(Type); - else - ItemID = GetBaseID(Type); - } + set => ItemID = value ? GetExtendedID(Type) : GetBaseID(Type); } public override bool PassivelyTriggered => false; @@ -101,7 +95,7 @@ namespace Server.Items if (!from.Alive || from.AccessLevel > AccessLevel.Player) return; - Effects.SendLocationEffect(Location, Map, GetBaseID(Type) + 1, 18, 3, GetEffectHue(), 0); + Effects.SendLocationEffect(Location, Map, GetBaseID(Type) + 1, 18, 3, GetEffectHue()); Effects.PlaySound(Location, Map, 0x22C); foreach (Mobile mob in GetMobilesInRange(0)) @@ -122,7 +116,7 @@ namespace Server.Items public virtual void OnSpikeRetracted() { Extended = false; - Effects.SendLocationEffect(Location, Map, GetExtendedID(Type) - 1, 6, 3, GetEffectHue(), 0); + Effects.SendLocationEffect(Location, Map, GetExtendedID(Type) - 1, 6, 3, GetEffectHue()); } public override void Serialize(GenericWriter writer) diff --git a/Projects/Scripts/Items/Traps/StoneFaceTrap.cs b/Projects/Scripts/Items/Traps/StoneFaceTrap.cs index 2aab141f8..f9a320d74 100644 --- a/Projects/Scripts/Items/Traps/StoneFaceTrap.cs +++ b/Projects/Scripts/Items/Traps/StoneFaceTrap.cs @@ -40,22 +40,24 @@ namespace Server.Items } set { - bool breathing = Breathing; - - ItemID = breathing ? GetFireID(value) : GetBaseID(value); - } + 0x10F5 => StoneFaceTrapType.NorthWestWall, + 0x10F6 => StoneFaceTrapType.NorthWestWall, + 0x10F7 => StoneFaceTrapType.NorthWestWall, + 0x10FC => StoneFaceTrapType.NorthWall, + 0x10FD => StoneFaceTrapType.NorthWall, + 0x10FE => StoneFaceTrapType.NorthWall, + 0x110F => StoneFaceTrapType.WestWall, + 0x1110 => StoneFaceTrapType.WestWall, + 0x1111 => StoneFaceTrapType.WestWall, + _ => StoneFaceTrapType.NorthWestWall + }; + set => ItemID = Breathing ? GetFireID(value) : GetBaseID(value); } public bool Breathing { get => ItemID == GetFireID(Type); - set - { - if (value) - ItemID = GetFireID(Type); - else - ItemID = GetBaseID(Type); - } + set => ItemID = value ? GetFireID(Type) : GetBaseID(Type); } public override bool PassivelyTriggered => true; @@ -157,4 +159,4 @@ namespace Server.Items int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Wands/BaseWand.cs b/Projects/Scripts/Items/Wands/BaseWand.cs index 656850536..97819c442 100644 --- a/Projects/Scripts/Items/Wands/BaseWand.cs +++ b/Projects/Scripts/Items/Wands/BaseWand.cs @@ -236,22 +236,15 @@ namespace Server.Items int number; if (Name == null) - { number = 1017085; - } else { LabelTo(from, Name); number = 1041000; } - if (attrs.Count == 0 && Crafter == null && Name != null) - return; - - EquipmentInfo eqInfo = new EquipmentInfo(number, Crafter, false, - attrs.ToArray()); - - from.Send(new DisplayEquipmentInfo(this, eqInfo)); + if (attrs.Count > 0 || Crafter != null || Name == null) + EquipmentPackets.SendDisplayEquipmentInfo(from.NetState, this, number, Crafter, false, attrs); } public void Cast(Spell spell) @@ -279,4 +272,4 @@ namespace Server.Items public virtual bool OnWandTarget(Mobile from, object o) => true; } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Weapons/Abilities/WeaponAbility.cs b/Projects/Scripts/Items/Weapons/Abilities/WeaponAbility.cs index dff3bf72e..50b2d774f 100644 --- a/Projects/Scripts/Items/Weapons/Abilities/WeaponAbility.cs +++ b/Projects/Scripts/Items/Weapons/Abilities/WeaponAbility.cs @@ -125,13 +125,13 @@ namespace Server.Items { int mana = BaseMana; - double skillTotal = GetSkill(from, SkillName.Swords) + GetSkill(from, SkillName.Macing) - + GetSkill(from, SkillName.Fencing) + + double skillTotal = GetSkill(from, SkillName.Swords) + GetSkill(from, SkillName.Macing) + + GetSkill(from, SkillName.Fencing) + GetSkill(from, SkillName.Archery) + - GetSkill(from, SkillName.Parry) - + GetSkill(from, SkillName.Lumberjacking) + - GetSkill(from, SkillName.Stealth) - + GetSkill(from, SkillName.Poisoning) + + GetSkill(from, SkillName.Parry) + + GetSkill(from, SkillName.Lumberjacking) + + GetSkill(from, SkillName.Stealth) + + GetSkill(from, SkillName.Poisoning) + GetSkill(from, SkillName.Bushido) + GetSkill(from, SkillName.Ninjitsu); @@ -256,55 +256,33 @@ namespace Server.Items #region Dueling - string option = null; - - if (this is ArmorIgnore) - option = "Armor Ignore"; - else if (this is BleedAttack) - option = "Bleed Attack"; - else if (this is ConcussionBlow) - option = "Concussion Blow"; - else if (this is CrushingBlow) - option = "Crushing Blow"; - else if (this is Disarm) - option = "Disarm"; - else if (this is Dismount) - option = "Dismount"; - else if (this is DoubleStrike) - option = "Double Strike"; - else if (this is InfectiousStrike) - option = "Infectious Strike"; - else if (this is MortalStrike) - option = "Mortal Strike"; - else if (this is MovingShot) - option = "Moving Shot"; - else if (this is ParalyzingBlow) - option = "Paralyzing Blow"; - else if (this is ShadowStrike) - option = "Shadow Strike"; - else if (this is WhirlwindAttack) - option = "Whirlwind Attack"; - else if (this is RidingSwipe) - option = "Riding Swipe"; - else if (this is FrenziedWhirlwind) - option = "Frenzied Whirlwind"; - else if (this is Block) - option = "Block"; - else if (this is DefenseMastery) - option = "Defense Mastery"; - else if (this is NerveStrike) - option = "Nerve Strike"; - else if (this is TalonStrike) - option = "Talon Strike"; - else if (this is Feint) - option = "Feint"; - else if (this is DualWield) - option = "Dual Wield"; - else if (this is DoubleShot) - option = "Double Shot"; - else if (this is ArmorPierce) - option = "Armor Pierce"; - + string option = this switch + { + ArmorIgnore _ => "Armor Ignore", + BleedAttack _ => "Bleed Attack", + ConcussionBlow _ => "Concussion Blow", + CrushingBlow _ => "Crushing Blow", + Disarm _ => "Disarm", + Dismount _ => "Dismount", + DoubleStrike _ => "Double Strike", + InfectiousStrike _ => "Infectious Strike", + MortalStrike _ => "Mortal Strike", + MovingShot _ => "Moving Shot", + ParalyzingBlow _ => "Paralyzing Blow", + ShadowStrike _ => "Shadow Strike", + WhirlwindAttack _ => "Whirlwind Attack", + RidingSwipe _ => "Riding Swipe", + FrenziedWhirlwind _ => "Frenzied Whirlwind", + Block _ => "Block", + DefenseMastery _ => "Defense Mastery", + NerveStrike _ => "Nerve Strike", + TalonStrike _ => "Talon Strike", + Feint _ => "Feint", + DualWield _ => "Dual Wield", + DoubleShot _ => "Double Shot", + ArmorPierce _ => "Armor Pierce", + _ => null + }; if (option != null && !DuelContext.AllowSpecialAbility(from, option, true)) return false; @@ -381,7 +359,7 @@ namespace Server.Items Table.Remove(m); if (Core.AOS && m.NetState != null) - m.Send(ClearWeaponAbility.Instance); + Packets.SendClearWeaponAbility(m.NetState); } public static void Initialize() diff --git a/Projects/Scripts/Items/Weapons/BaseWeapon.cs b/Projects/Scripts/Items/Weapons/BaseWeapon.cs index c3a156618..2d686d4dc 100644 --- a/Projects/Scripts/Items/Weapons/BaseWeapon.cs +++ b/Projects/Scripts/Items/Weapons/BaseWeapon.cs @@ -291,24 +291,16 @@ namespace Server.Items if (m_Quality == WeaponQuality.Exceptional) bonus += 20; - switch (m_DurabilityLevel) + + bonus += m_DurabilityLevel switch { - case WeaponDurabilityLevel.Durable: - bonus += 20; - break; - case WeaponDurabilityLevel.Substantial: - bonus += 50; - break; - case WeaponDurabilityLevel.Massive: - bonus += 70; - break; - case WeaponDurabilityLevel.Fortified: - bonus += 100; - break; - case WeaponDurabilityLevel.Indestructible: - bonus += 120; - break; - } + WeaponDurabilityLevel.Durable => 20, + WeaponDurabilityLevel.Substantial => 50, + WeaponDurabilityLevel.Massive => 70, + WeaponDurabilityLevel.Fortified => 100, + WeaponDurabilityLevel.Indestructible => 120, + _ => 0 + }; if (Core.AOS) { @@ -516,10 +508,9 @@ namespace Server.Items double swrd = m.Skills.Swords.Value; double fenc = m.Skills.Fencing.Value; double mcng = m.Skills.Macing.Value; - double val; sk = SkillName.Swords; - val = swrd; + double val = swrd; if (fenc > val) { @@ -530,12 +521,7 @@ namespace Server.Items if (mcng > val) sk = SkillName.Macing; } else if (WeaponAttributes.MageWeapon != 0) - { - if (m.Skills.Magery.Value > m.Skills[Skill].Value) - sk = SkillName.Magery; - else - sk = Skill; - } + sk = m.Skills.Magery.Value > m.Skills[Skill].Value ? SkillName.Magery : Skill; else { sk = Skill; @@ -792,9 +778,7 @@ namespace Server.Items if (canSwing && attacker.HarmfulCheck(defender)) { attacker.DisruptiveAction(); - - if (attacker.NetState != null) - attacker.Send(new Swing(0, attacker, defender)); + Packets.SendSwing(attacker.NetState, attacker.Serial, defender.Serial); if (attacker is BaseCreature bc) { @@ -1449,7 +1433,7 @@ namespace Server.Items damage = AOS.Scale(damage, 100 + damageBonus); - return damage / 100; + return damage / 100.0; } public virtual CheckSlayerResult CheckSlayers(Mobile attacker, Mobile defender) @@ -1641,65 +1625,32 @@ namespace Server.Items if (!Core.AOS) return 0; - int bonus = 0; - - switch (m_AccuracyLevel) + return m_AccuracyLevel switch { - case WeaponAccuracyLevel.Accurate: - bonus += 02; - break; - case WeaponAccuracyLevel.Surpassingly: - bonus += 04; - break; - case WeaponAccuracyLevel.Eminently: - bonus += 06; - break; - case WeaponAccuracyLevel.Exceedingly: - bonus += 08; - break; - case WeaponAccuracyLevel.Supremely: - bonus += 10; - break; - } - - return bonus; + WeaponAccuracyLevel.Accurate => 2, + WeaponAccuracyLevel.Surpassingly => 4, + WeaponAccuracyLevel.Eminently => 6, + WeaponAccuracyLevel.Exceedingly => 8, + WeaponAccuracyLevel.Supremely => 10, + _ => 0 + }; } - public virtual int GetDamageBonus() - { - int bonus = VirtualDamageBonus; - - switch (m_Quality) + public virtual int GetDamageBonus() => + VirtualDamageBonus + m_Quality switch { - case WeaponQuality.Low: - bonus -= 20; - break; - case WeaponQuality.Exceptional: - bonus += 20; - break; - } - - switch (m_DamageLevel) + WeaponQuality.Low => -20, + WeaponQuality.Exceptional => 20, + _ => 0, + } + m_DamageLevel switch { - case WeaponDamageLevel.Ruin: - bonus += 15; - break; - case WeaponDamageLevel.Might: - bonus += 20; - break; - case WeaponDamageLevel.Force: - bonus += 25; - break; - case WeaponDamageLevel.Power: - bonus += 30; - break; - case WeaponDamageLevel.Vanq: - bonus += 35; - break; - } - - return bonus; - } + WeaponDamageLevel.Ruin => 15, + WeaponDamageLevel.Might => 20, + WeaponDamageLevel.Force => 25, + WeaponDamageLevel.Power => 30, + WeaponDamageLevel.Vanq => 35, + _ => 0, + }; public virtual double ScaleDamageAOS(Mobile attacker, double damage, bool checkSkills) { @@ -2353,10 +2304,7 @@ namespace Server.Items } else if (m_Slayer != SlayerName.None || m_Slayer2 != SlayerName.None || m_DurabilityLevel != WeaponDurabilityLevel.Regular || m_DamageLevel != WeaponDamageLevel.Regular || - m_AccuracyLevel != WeaponAccuracyLevel.Regular) - { - attrs.Add(new EquipInfoAttribute(1038000)); // Unidentified - } + m_AccuracyLevel != WeaponAccuracyLevel.Regular) attrs.Add(new EquipInfoAttribute(1038000)); // Unidentified if (m_Poison != null && m_PoisonCharges > 0) attrs.Add(new EquipInfoAttribute(1017383, m_PoisonCharges)); @@ -2364,21 +2312,15 @@ namespace Server.Items int number; if (Name == null) - { number = LabelNumber; - } else { LabelTo(from, Name); number = 1041000; } - if (attrs.Count == 0 && Crafter == null && Name != null) - return; - - EquipmentInfo eqInfo = new EquipmentInfo(number, m_Crafter, false, attrs.ToArray()); - - from.Send(new DisplayEquipmentInfo(this, eqInfo)); + if (attrs.Count > 0 || Crafter != null || Name == null) + EquipmentPackets.SendDisplayEquipmentInfo(from.NetState, this, number, m_Crafter, false, attrs); } private class ResetEquipTimer : Timer @@ -2918,7 +2860,7 @@ namespace Server.Items double damage = GetAosDamage(attacker, 23, 1, 4); - defender.BoltEffect(0); + defender.BoltEffect(); SpellHelper.Damage(TimeSpan.Zero, defender, attacker, damage, 0, 0, 0, 0, 100); } @@ -3355,8 +3297,7 @@ namespace Server.Items parentMobile.AddSkillMod(m_MageMod); } - if (GetSaveFlag(flags, SaveFlag.PlayerConstructed)) - PlayerConstructed = true; + PlayerConstructed |= GetSaveFlag(flags, SaveFlag.PlayerConstructed); if (GetSaveFlag(flags, SaveFlag.SkillBonuses)) SkillBonuses = new AosSkillBonuses(this, reader); @@ -3508,8 +3449,7 @@ namespace Server.Items if (m_Hits <= 0 && m_MaxHits <= 0) m_Hits = m_MaxHits = Utility.RandomMinMax(InitMinHits, InitMaxHits); - if (version < 6) - PlayerConstructed = true; // we don't know, so, assume it's crafted + PlayerConstructed |= version < 6; // we don't know, so, assume it's crafted } #endregion diff --git a/Projects/Scripts/Items/Weapons/Maces/FireworksWand.cs b/Projects/Scripts/Items/Weapons/Maces/FireworksWand.cs index 37389667e..40f243fee 100644 --- a/Projects/Scripts/Items/Weapons/Maces/FireworksWand.cs +++ b/Projects/Scripts/Items/Weapons/Maces/FireworksWand.cs @@ -71,7 +71,7 @@ namespace Server.Items startLoc.Z + 32); Effects.SendMovingEffect(new Entity(Serial.Zero, startLoc, map), new Entity(Serial.Zero, endLoc, map), - 0x36E4, 5, 0, false, false); + 0x36E4, 5, 0); Timer.DelayCall(TimeSpan.FromSeconds(1.0), () => FinishLaunch(endLoc, map)); } diff --git a/Projects/Scripts/Items/Weapons/Ranged/BaseRanged.cs b/Projects/Scripts/Items/Weapons/Ranged/BaseRanged.cs index 7c87a4199..c9a1283d5 100644 --- a/Projects/Scripts/Items/Weapons/Ranged/BaseRanged.cs +++ b/Projects/Scripts/Items/Weapons/Ranged/BaseRanged.cs @@ -81,7 +81,7 @@ namespace Server.Items if (canSwing && attacker.HarmfulCheck(defender)) { attacker.DisruptiveAction(); - attacker.Send(new Swing(0, attacker, defender)); + Packets.SendSwing(attacker.NetState, attacker.Serial, defender.Serial); if (OnFired(attacker, defender)) { diff --git a/Projects/Scripts/Items/Weapons/Staves/ShepherdsCrook.cs b/Projects/Scripts/Items/Weapons/Staves/ShepherdsCrook.cs index dab5c1bb5..1a17ad5ff 100644 --- a/Projects/Scripts/Items/Weapons/Staves/ShepherdsCrook.cs +++ b/Projects/Scripts/Items/Weapons/Staves/ShepherdsCrook.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using Server.Engines.CannedEvil; using Server.Mobiles; using Server.Network; @@ -117,9 +118,7 @@ namespace Server.Items { Type t = bc.GetType(); - foreach (Type type in m_ChampTamables) - if (type == t) - return true; + return m_ChampTamables.Any(type => type == t); } } @@ -145,7 +144,7 @@ namespace Server.Items if (from.CheckTargetSkill(SkillName.Herding, m_Creature, min, max)) { - if (p != from) + if (!ReferenceEquals(p, from)) p = new Point2D(p.X, p.Y); m_Creature.TargetLocation = p; diff --git a/Projects/Scripts/Misc/AOS.cs b/Projects/Scripts/Misc/AOS.cs index cbf8d4487..2d9fac575 100644 --- a/Projects/Scripts/Misc/AOS.cs +++ b/Projects/Scripts/Misc/AOS.cs @@ -9,7 +9,7 @@ using Server.Spells.Seventh; namespace Server { - public class AOS + public static class AOS { public static void DisableStatInfluences() { @@ -1019,8 +1019,7 @@ namespace Server if (!GetValues(i, out SkillName skill, out double bonus)) continue; - if (m_Mods == null) - m_Mods = new List(); + m_Mods ??= new List(); SkillMod sk = new DefaultSkillMod(skill, true, bonus); sk.ObeyCap = true; diff --git a/Projects/Scripts/Misc/AccountPrompt.cs b/Projects/Scripts/Misc/AccountPrompt.cs index 1c5df4dab..274e5bd9e 100644 --- a/Projects/Scripts/Misc/AccountPrompt.cs +++ b/Projects/Scripts/Misc/AccountPrompt.cs @@ -3,7 +3,7 @@ using Server.Accounting; namespace Server.Misc { - public class AccountPrompt + public static class AccountPrompt { public static void Initialize() { @@ -22,8 +22,7 @@ namespace Server.Misc Console.Write("Password: "); string password = Console.ReadLine(); - Account a = new Account(username, password); - a.AccessLevel = AccessLevel.Owner; + Account a = new Account(username, password) {AccessLevel = AccessLevel.Owner}; Console.WriteLine("Account created."); } @@ -36,4 +35,4 @@ namespace Server.Misc } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/Animations.cs b/Projects/Scripts/Misc/Animations.cs index d4515e671..67de3a56b 100644 --- a/Projects/Scripts/Misc/Animations.cs +++ b/Projects/Scripts/Misc/Animations.cs @@ -1,6 +1,6 @@ namespace Server.Misc { - public class Animations + public static class Animations { public static void Initialize() { @@ -28,4 +28,4 @@ namespace Server.Misc from.Animate(action, 5, 1, true, false, 0); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/AttackMessage.cs b/Projects/Scripts/Misc/AttackMessage.cs index 0687281f7..a58ccf38a 100644 --- a/Projects/Scripts/Misc/AttackMessage.cs +++ b/Projects/Scripts/Misc/AttackMessage.cs @@ -4,7 +4,7 @@ using Server.Network; namespace Server.Misc { - public class AttackMessage + public static class AttackMessage { private const string AggressorFormat = "You are attacking {0}!"; private const string AggressedFormat = "{0} is attacking you!"; @@ -59,4 +59,4 @@ namespace Server.Misc return false; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/AutoSave.cs b/Projects/Scripts/Misc/AutoSave.cs index 1d206f72b..6b538ce56 100644 --- a/Projects/Scripts/Misc/AutoSave.cs +++ b/Projects/Scripts/Misc/AutoSave.cs @@ -141,7 +141,7 @@ namespace Server.Misc string saves = Path.Combine(Core.BaseDirectory, "Saves"); if (Directory.Exists(saves)) - Directory.Move(saves, FormatDirectory(root, m_Backups[m_Backups.Length - 1], GetTimeStamp())); + Directory.Move(saves, FormatDirectory(root, m_Backups[^1], GetTimeStamp())); } private static DirectoryInfo Match(string[] paths, string match) @@ -181,4 +181,4 @@ namespace Server.Misc return $"{now.Day}-{now.Month}-{now.Year} {now.Hour}-{now.Minute:D2}-{now.Second:D2}"; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/Broadcasts.cs b/Projects/Scripts/Misc/Broadcasts.cs index 65d5f79a3..4e4e6b117 100644 --- a/Projects/Scripts/Misc/Broadcasts.cs +++ b/Projects/Scripts/Misc/Broadcasts.cs @@ -1,6 +1,6 @@ namespace Server.Misc { - public class Broadcasts + public static class Broadcasts { public static void Initialize() { diff --git a/Projects/Scripts/Misc/BuffIcons.cs b/Projects/Scripts/Misc/BuffIcons.cs index 6884f63c9..1a4bf64fa 100644 --- a/Projects/Scripts/Misc/BuffIcons.cs +++ b/Projects/Scripts/Misc/BuffIcons.cs @@ -1,4 +1,5 @@ using System; +using Server.Buffers; using Server.Mobiles; using Server.Network; @@ -18,13 +19,11 @@ namespace Server }; } - #region Properties - public BuffIcon ID{ get; } - public int TitleCliloc{ get; } + public int Title{ get; } - public int SecondaryCliloc{ get; } + public TextDefinition Description{ get; } public TimeSpan TimeLength{ get; } @@ -32,50 +31,30 @@ namespace Server public Timer Timer{ get; } - public bool RetainThroughDeath{ get; } + public bool RetainThroughDeath { get; } - public TextDefinition Args{ get; } - - #endregion - - #region Constructors - - public BuffInfo(BuffIcon iconID, int titleCliloc) - : this(iconID, titleCliloc, titleCliloc + 1) + public BuffInfo(BuffIcon iconId, int title, TimeSpan time = default, Mobile m = null) : + this(iconId, title, title + 1, time, m) { } - public BuffInfo(BuffIcon iconID, int titleCliloc, int secondaryCliloc) - { - ID = iconID; - TitleCliloc = titleCliloc; - SecondaryCliloc = secondaryCliloc; - } - - public BuffInfo(BuffIcon iconID, int titleCliloc, TimeSpan length, Mobile m) - : this(iconID, titleCliloc, titleCliloc + 1, length, m) + public BuffInfo(BuffIcon iconId, int title, string args, TimeSpan time = default, Mobile m = null) : + this(iconId, title, title + 1, args, time, m) { } - //Only the timed one needs to Mobile to know when to automagically remove it. - public BuffInfo(BuffIcon iconID, int titleCliloc, int secondaryCliloc, TimeSpan length, Mobile m) - : this(iconID, titleCliloc, secondaryCliloc) + public BuffInfo(BuffIcon iconId, int title, int desc, TimeSpan time = default, Mobile m = null) : + this(iconId, title, desc, null, time, m) { - TimeLength = length; - TimeStart = DateTime.UtcNow; - - Timer = Timer.DelayCall(length, delegate - { - if (!(m is PlayerMobile pm)) - return; - - pm.RemoveBuff(this); - }); } + public BuffInfo(BuffIcon iconId, int title, string args, bool retain, Mobile m = null) : + this(iconId, title, title + 1, args, DateTime.UtcNow, default, retain, m) + { + } - public BuffInfo(BuffIcon iconID, int titleCliloc, TextDefinition args) - : this(iconID, titleCliloc, titleCliloc + 1, args) + public BuffInfo(BuffIcon iconId, int title, int desc, string args, TimeSpan time, Mobile m = null) : + this(iconId, title, new TextDefinition(desc, args), DateTime.UtcNow, time, false, m) { } @@ -83,8 +62,8 @@ namespace Server : this(iconID, titleCliloc, secondaryCliloc) => Args = args; - public BuffInfo(BuffIcon iconID, int titleCliloc, bool retainThroughDeath) - : this(iconID, titleCliloc, titleCliloc + 1, retainThroughDeath) + public BuffInfo(BuffIcon iconId, int title, int desc, string args, TimeSpan time = default, bool retain = false, + Mobile m = null) : this(iconId, title, new TextDefinition(desc, args), DateTime.UtcNow, time, retain, m) { } @@ -92,9 +71,17 @@ namespace Server : this(iconID, titleCliloc, secondaryCliloc) => RetainThroughDeath = retainThroughDeath; - public BuffInfo(BuffIcon iconID, int titleCliloc, TextDefinition args, bool retainThroughDeath) - : this(iconID, titleCliloc, titleCliloc + 1, args, retainThroughDeath) + public BuffInfo(BuffIcon iconId, int title, TextDefinition desc, DateTime start = default, TimeSpan time = default, bool retain = false, + Mobile m = null) { + ID = iconId; + Title = title; + Description = desc; + TimeLength = time; + TimeStart = start; + RetainThroughDeath = retain; + if (m is PlayerMobile pm) + Timer = Timer.DelayCall(time, playermobile => playermobile.RemoveBuff(this), pm); } public BuffInfo(BuffIcon iconID, int titleCliloc, int secondaryCliloc, TextDefinition args, bool retainThroughDeath) @@ -131,20 +118,17 @@ namespace Server public static void AddBuff(Mobile m, BuffInfo b) { - if (m is PlayerMobile pm) - pm.AddBuff(b); + (m as PlayerMobile)?.AddBuff(b); } public static void RemoveBuff(Mobile m, BuffInfo b) { - if (m is PlayerMobile pm) - pm.RemoveBuff(b); + (m as PlayerMobile)?.RemoveBuff(b); } public static void RemoveBuff(Mobile m, BuffIcon b) { - if (m is PlayerMobile pm) - pm.RemoveBuff(b); + (m as PlayerMobile)?.RemoveBuff(b); } #endregion @@ -208,80 +192,68 @@ namespace Server Fly } - public sealed class AddBuffPacket : Packet + public static class BuffPackets { - public AddBuffPacket(Mobile m, BuffInfo info) - : this(m, info.ID, info.TitleCliloc, info.SecondaryCliloc, info.Args, - info.TimeStart != DateTime.MinValue ? info.TimeStart + info.TimeLength - DateTime.UtcNow : TimeSpan.Zero) + public static void SendAddBuff(Mobile m, BuffInfo info) { + SendAddBuff(m.NetState, m.Serial, info.ID, info.Title, info.Description, + info.TimeStart != DateTime.MinValue ? info.TimeStart + info.TimeLength - DateTime.UtcNow : TimeSpan.Zero); + } + public static void SendAddBuff(NetState ns, Serial m, BuffIcon iconID, int title, TextDefinition desc, TimeSpan time) + { + if (ns == null) + return; + + string args = desc?.String ?? ""; + + int length = 44 + args.Length * 2; + + SpanWriter writer = new SpanWriter(stackalloc byte[length]); + writer.Write((byte)0xDF); // Packet ID + writer.Write((ushort)length); // Dynamic Length + + writer.Write(m); + + writer.Write((short)iconID); //ID + writer.Write((short)0x1); //Type 0 for removal. 1 for add 2 for Data + + writer.Position += 4; + + writer.Write((short)iconID); //ID + writer.Write((short)0x01); //Type 0 for removal. 1 for add 2 for Data + + writer.Position += 4; + + writer.Write((short)Math.Max(time.TotalSeconds, 0)); //Time in seconds + + writer.Position += 3; + + writer.Write(title); + writer.Write(desc?.Number ?? 0); + + writer.Position += 5; + writer.Write((byte)0x1); // Start indicator? + writer.Position += 2; + + writer.WriteLittleUniNull(args); + + ns.Send(writer.Span); } - public AddBuffPacket(Mobile mob, BuffIcon iconID, int titleCliloc, int secondaryCliloc, TextDefinition args, - TimeSpan length) - : base(0xDF) + public static void SendRemoveBuffPacket(NetState ns, Serial m, int icon) { - bool hasArgs = args != null; + SpanWriter writer = new SpanWriter(stackalloc byte[13]); + writer.Write((byte)0xDF); // Packet ID + writer.Write((ushort)13); // Dynamic Length - EnsureCapacity(hasArgs ? 48 + args.ToString().Length * 2 : 44); - m_Stream.Write(mob.Serial); + writer.Write(m); + writer.Write((short)icon); //ID + writer.Write((short)0x0); //Type 0 for removal. 1 for add 2 for Data - m_Stream.Write((short)iconID); //ID - m_Stream.Write((short)0x1); //Type 0 for removal. 1 for add 2 for Data + writer.Position += 4; - m_Stream.Fill(4); - - m_Stream.Write((short)iconID); //ID - m_Stream.Write((short)0x01); //Type 0 for removal. 1 for add 2 for Data - - m_Stream.Fill(4); - - if (length < TimeSpan.Zero) - length = TimeSpan.Zero; - - m_Stream.Write((short)length.TotalSeconds); //Time in seconds - - m_Stream.Fill(3); - m_Stream.Write(titleCliloc); - m_Stream.Write(secondaryCliloc); - - if (!hasArgs) - { - //m_Stream.Fill( 2 ); - m_Stream.Fill(10); - } - else - { - m_Stream.Fill(4); - m_Stream.Write((short)0x1); //Unknown -> Possibly something saying 'hey, I have more data!'? - m_Stream.Fill(2); - - //m_Stream.WriteLittleUniNull( "\t#1018280" ); - m_Stream.WriteLittleUniNull($"\t{args}"); - - m_Stream.Write((short)0x1); //Even more Unknown -> Possibly something saying 'hey, I have more data!'? - m_Stream.Fill(2); - } + ns.Send(writer.Span); } } - - public sealed class RemoveBuffPacket : Packet - { - public RemoveBuffPacket(Mobile mob, BuffInfo info) - : this(mob, info.ID) - { - } - - public RemoveBuffPacket(Mobile mob, BuffIcon iconID) - : base(0xDF) - { - EnsureCapacity(13); - m_Stream.Write(mob.Serial); - - m_Stream.Write((short)iconID); //ID - m_Stream.Write((short)0x0); //Type 0 for removal. 1 for add 2 for Data - - m_Stream.Fill(4); - } - } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/CharacterCreation.cs b/Projects/Scripts/Misc/CharacterCreation.cs index 64fcdd999..a234f5e6c 100644 --- a/Projects/Scripts/Misc/CharacterCreation.cs +++ b/Projects/Scripts/Misc/CharacterCreation.cs @@ -7,7 +7,7 @@ using Server.Network; namespace Server.Misc { - public class CharacterCreation + public static class CharacterCreation { private static readonly CityInfo m_NewHavenInfo = new CityInfo("New Haven", "The Bountiful Harvest Inn", 3503, 2574, 14, Map.Trammel); @@ -22,15 +22,8 @@ namespace Server.Misc private static void AddBackpack(Mobile m) { - Container pack = m.Backpack; - - if (pack == null) - { - pack = new Backpack(); - pack.Movable = false; - - m.AddItem(pack); - } + if (m.Backpack == null) + m.AddItem(new Backpack {Movable = false}); PackItem(new RedBook("a book", m.Name, 20, true)); PackItem(new Gold(1000)); // Starting gold can be customized here @@ -52,16 +45,8 @@ namespace Server.Misc item.Location = new Point3D(x, y, 0); } - private static Item MakePotionKeg(PotionEffect type, int hue) - { - PotionKeg keg = new PotionKeg(); - - keg.Held = 100; - keg.Type = type; - keg.Hue = hue; - - return MakeNewbie(keg); - } + private static Item MakePotionKeg(PotionEffect type, int hue) => + MakeNewbie(new PotionKeg {Held = 100, Type = type, Hue = hue}); private static void FillBankAOS(Mobile m) { @@ -75,11 +60,8 @@ namespace Server.Misc m.StatCap = 250; - Container cont; - - // Begin box of money - cont = new WoodenBox(); + Container cont = new WoodenBox(); cont.ItemID = 0xE7D; cont.Hue = 0x489; @@ -97,8 +79,7 @@ namespace Server.Misc // Begin bag of potion kegs - cont = new Backpack(); - cont.Name = "Various Potion Kegs"; + cont = new Backpack {Name = "Various Potion Kegs"}; PlaceItemIn(cont, 45, 149, MakePotionKeg(PotionEffect.CureGreater, 0x2D)); PlaceItemIn(cont, 69, 149, MakePotionKeg(PotionEffect.HealGreater, 0x499)); @@ -113,8 +94,7 @@ namespace Server.Misc // Begin bag of tools - cont = new Bag(); - cont.Name = "Tool Bag"; + cont = new Bag {Name = "Tool Bag"}; PlaceItemIn(cont, 30, 35, new TinkerTools(1000)); PlaceItemIn(cont, 60, 35, new HousePlacementTool()); @@ -145,8 +125,7 @@ namespace Server.Misc // Begin bag of archery ammo - cont = new Bag(); - cont.Name = "Bag Of Archery Ammo"; + cont = new Bag {Name = "Bag Of Archery Ammo"}; PlaceItemIn(cont, 48, 76, new Arrow(5000)); PlaceItemIn(cont, 72, 76, new Bolt(5000)); @@ -156,8 +135,7 @@ namespace Server.Misc // Begin bag of treasure maps - cont = new Bag(); - cont.Name = "Bag Of Treasure Maps"; + cont = new Bag {Name = "Bag Of Treasure Maps"}; PlaceItemIn(cont, 30, 35, new TreasureMap(1, Map.Trammel)); PlaceItemIn(cont, 45, 35, new TreasureMap(2, Map.Trammel)); @@ -181,9 +159,7 @@ namespace Server.Misc // Begin bag of raw materials - cont = new Bag(); - cont.Hue = 0x835; - cont.Name = "Raw Materials Bag"; + cont = new Bag {Hue = 0x835, Name = "Raw Materials Bag"}; PlaceItemIn(cont, 92, 60, new BarbedLeather(5000)); PlaceItemIn(cont, 92, 68, new HornedLeather(5000)); @@ -216,9 +192,7 @@ namespace Server.Misc // Begin bag of spell casting stuff - cont = new Backpack(); - cont.Hue = 0x480; - cont.Name = "Spell Casting Stuff"; + cont = new Backpack {Hue = 0x480, Name = "Spell Casting Stuff"}; PlaceItemIn(cont, 45, 105, new Spellbook(ulong.MaxValue)); PlaceItemIn(cont, 65, 105, new NecromancerSpellbook((ulong)0xFFFF)); @@ -234,8 +208,7 @@ namespace Server.Misc toHue.Hue = 0x2D; PlaceItemIn(cont, 45, 150, toHue); - toHue = new BagOfNecroReagents(150); - toHue.Hue = 0x488; + toHue = new BagOfNecroReagents(150) {Hue = 0x488}; PlaceItemIn(cont, 65, 150, toHue); PlaceItemIn(cont, 140, 150, new BagOfAllReagents(500)); @@ -250,9 +223,7 @@ namespace Server.Misc // Begin bag of ethereals - cont = new Backpack(); - cont.Hue = 0x490; - cont.Name = "Bag Of Ethy's!"; + cont = new Backpack {Hue = 0x490, Name = "Bag Of Ethy's!"}; PlaceItemIn(cont, 45, 66, new EtherealHorse()); PlaceItemIn(cont, 69, 82, new EtherealOstard()); @@ -268,9 +239,7 @@ namespace Server.Misc // Begin first bag of artifacts - cont = new Backpack(); - cont.Hue = 0x48F; - cont.Name = "Bag of Artifacts"; + cont = new Backpack {Hue = 0x48F, Name = "Bag of Artifacts"}; PlaceItemIn(cont, 45, 66, new TitansHammer()); PlaceItemIn(cont, 69, 82, new InquisitorsResolution()); @@ -282,9 +251,7 @@ namespace Server.Misc // Begin second bag of artifacts - cont = new Backpack(); - cont.Hue = 0x48F; - cont.Name = "Bag of Artifacts"; + cont = new Backpack {Hue = 0x48F, Name = "Bag of Artifacts"}; PlaceItemIn(cont, 45, 66, new GauntletsOfNobility()); PlaceItemIn(cont, 69, 82, new MidnightBracers()); @@ -324,10 +291,7 @@ namespace Server.Misc // End second bag of artifacts // Begin bag of minor artifacts - cont = new Backpack(); - cont.Hue = 0x48F; - cont.Name = "Bag of Minor Artifacts"; - + cont = new Backpack {Hue = 0x48F, Name = "Bag of Minor Artifacts"}; PlaceItemIn(cont, 45, 66, new LunaLance()); PlaceItemIn(cont, 69, 82, new VioletCourage()); @@ -368,9 +332,7 @@ namespace Server.Misc if (Core.SE) { - cont = new Bag(); - cont.Hue = 0x501; - cont.Name = "Tokuno Minor Artifacts"; + cont = new Bag {Hue = 0x501, Name = "Tokuno Minor Artifacts"}; PlaceItemIn(cont, 42, 70, new Exiler()); PlaceItemIn(cont, 38, 53, new HanzosBow()); @@ -398,8 +360,7 @@ namespace Server.Misc if (Core.SE) //This bag came only after SE. { - cont = new Bag(); - cont.Name = "Bag of Bows"; + cont = new Bag {Name = "Bag of Bows"}; PlaceItemIn(cont, 31, 84, new Bow()); PlaceItemIn(cont, 78, 74, new CompositeBow()); @@ -432,11 +393,7 @@ namespace Server.Misc bank.DropItem(new BankCheck(1000000)); // Full spellbook - Spellbook book = new Spellbook(); - - book.Content = ulong.MaxValue; - - bank.DropItem(book); + bank.DropItem(new Spellbook {Content = ulong.MaxValue}); Bag bag = new Bag(); @@ -641,10 +598,7 @@ namespace Server.Misc newChar.Female = args.Female; //newChar.Body = newChar.Female ? 0x191 : 0x190; - if (Core.Expansion >= args.Race.RequiredExpansion) - newChar.Race = args.Race; //Sets body - else - newChar.Race = Race.DefaultRace; + newChar.Race = Core.Expansion >= args.Race.RequiredExpansion ? args.Race : Race.DefaultRace; //newChar.Hue = Utility.ClipSkinHue( args.Hue & 0x3FFF ) | 0x8000; newChar.Hue = newChar.Race.ClipSkinHue(args.Hue & 0x3FFF) | 0x8000; @@ -692,12 +646,7 @@ namespace Server.Misc if (TestCenter.Enabled) FillBankbox(newChar); - if (young) - { - NewPlayerTicket ticket = new NewPlayerTicket(); - ticket.Owner = newChar; - newChar.BankBox.DropItem(ticket); - } + if (young) newChar.BankBox.DropItem(new NewPlayerTicket {Owner = newChar}); CityInfo city = GetStartLocation(args, young); @@ -710,19 +659,8 @@ namespace Server.Misc new WelcomeTimer(newChar).Start(); } - public static bool VerifyProfession(int profession) - { - if (profession < 0) - return false; - if (profession < 4) - return true; - if (Core.AOS && profession < 6) - return true; - if (Core.SE && profession < 8) - return true; - - return false; - } + public static bool VerifyProfession(int profession) => + profession >= 0 && (profession < 4 || Core.AOS && profession < 6 || Core.SE && profession < 8); private static CityInfo GetStartLocation(CharacterCreatedEventArgs args, bool isYoung) { @@ -754,9 +692,7 @@ namespace Server.Misc break; } case 5: //Paladin - { return m_NewHavenInfo; - } case 6: //Samurai { if ((flags & ClientFlags.Tokuno) != 0) @@ -795,10 +731,7 @@ namespace Server.Misc } } - if (useHaven) - return m_NewHavenInfo; - - return args.City; + return useHaven ? m_NewHavenInfo : args.City; } private static void FixStats(ref int str, ref int dex, ref int intel, int max) @@ -1164,7 +1097,7 @@ namespace Server.Misc if (m_Mobile?.EquipItem(item) == true) return; - Container pack = m_Mobile.Backpack; + Container pack = m_Mobile?.Backpack; if (!mustEquip && pack != null) pack.DropItem(item); @@ -1177,7 +1110,7 @@ namespace Server.Misc if (!Core.AOS) item.LootType = LootType.Newbied; - Container pack = m_Mobile.Backpack; + Container pack = m_Mobile?.Backpack; if (pack != null) pack.DropItem(item); @@ -1733,18 +1666,18 @@ namespace Server.Misc private class BadStartMessage : Timer { private int m_Message; - private Mobile m_Mobile; + private Mobile m_From; public BadStartMessage(Mobile m, int message) : base(TimeSpan.FromSeconds(3.5)) { - m_Mobile = m; + m_From = m; m_Message = message; Start(); } protected override void OnTick() { - m_Mobile.SendLocalizedMessage(m_Message); + m_From.SendLocalizedMessage(m_Message); } } } diff --git a/Projects/Scripts/Misc/Cleanup.cs b/Projects/Scripts/Misc/Cleanup.cs index 407f1d0a0..4b6f5f9f2 100644 --- a/Projects/Scripts/Misc/Cleanup.cs +++ b/Projects/Scripts/Misc/Cleanup.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Items; -using Server.Mobiles; using Server.Multis; namespace Server.Misc @@ -43,9 +43,7 @@ namespace Server.Misc if (relEntity.Entity is Item item1) validItems.Add(item1); - foreach (VendorInventory inventory in house.VendorInventories) - foreach (Item subItem in inventory.Items) - validItems.Add(subItem); + validItems.AddRange(house.VendorInventories.SelectMany(inventory => inventory.Items)); } else if (item is BankBox box) { diff --git a/Projects/Scripts/Misc/CurrentExpansion.cs b/Projects/Scripts/Misc/CurrentExpansion.cs index 3ff96d7ed..bde778496 100644 --- a/Projects/Scripts/Misc/CurrentExpansion.cs +++ b/Projects/Scripts/Misc/CurrentExpansion.cs @@ -1,4 +1,4 @@ -using Server.Accounting; +using Server.Items; using Server.Network; namespace Server @@ -37,4 +37,4 @@ namespace Server } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/DoorGenerator.cs b/Projects/Scripts/Misc/DoorGenerator.cs index 865160c48..2a1b3fe76 100644 --- a/Projects/Scripts/Misc/DoorGenerator.cs +++ b/Projects/Scripts/Misc/DoorGenerator.cs @@ -390,7 +390,7 @@ namespace Server public static bool IsFrame(int id, int[] list) { - if (id > list[list.Length - 1]) + if (id > list[^1]) return false; for (int i = 0; i < list.Length; ++i) diff --git a/Projects/Scripts/Misc/Email.cs b/Projects/Scripts/Misc/Email.cs index 43d1d99c9..750515f03 100644 --- a/Projects/Scripts/Misc/Email.cs +++ b/Projects/Scripts/Misc/Email.cs @@ -6,17 +6,17 @@ using System.Threading; namespace Server.Misc { - public class Email + public static class Email { /* In order to support emailing, fill in EmailServer and FromAddress: * Example: * public static readonly string EmailServer = "mail.domain.com"; * public static readonly string FromAddress = "runuo@domain.com"; - * + * * If you want to add crash reporting emailing, fill in CrashAddresses: * Example: * public static readonly string CrashAddresses = "first@email.here,second@email.here,third@email.here"; - * + * * If you want to add speech log page emailing, fill in SpeechLogPageAddresses: * Example: * public static readonly string SpeechLogPageAddresses = "first@email.here,second@email.here,third@email.here"; @@ -62,7 +62,7 @@ namespace Server.Misc // .NET relies on the MTA to generate Message-ID header. Not all MTAs will add this header. DateTime now = DateTime.UtcNow; - string messageID = $"<{now.ToString("yyyyMMdd")}.{now.ToString("HHmmssff")}@{EmailServer}>"; + string messageID = $"<{now:yyyyMMdd}.{now:HHmmssff}@{EmailServer}>"; message.Headers.Add("Message-ID", messageID); message.Headers.Add("X-Mailer", "RunUO"); @@ -89,10 +89,8 @@ namespace Server.Misc { MailMessage message = (MailMessage)state; - if (Send(message)) - Console.WriteLine("Sent e-mail '{0}' to '{1}'.", message.Subject, message.To); - else - Console.WriteLine("Failure sending e-mail '{0}' to '{1}'.", message.Subject, message.To); + Console.WriteLine(Send(message) ? "Sent e-mail '{0}' to '{1}'." : "Failure sending e-mail '{0}' to '{1}'.", + message.Subject, message.To); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/Fastwalk.cs b/Projects/Scripts/Misc/Fastwalk.cs index 232986b7a..a9861974c 100644 --- a/Projects/Scripts/Misc/Fastwalk.cs +++ b/Projects/Scripts/Misc/Fastwalk.cs @@ -4,7 +4,7 @@ namespace Server.Misc { // This fastwalk detection is no longer required // As of B36 PlayerMobile implements movement packet throttling which more reliably controls movement speeds - public class Fastwalk + public static class Fastwalk { private static int MaxSteps = 4; // Maximum number of queued steps until fastwalk is detected private static bool Enabled = false; // Is fastwalk detection enabled? @@ -30,4 +30,4 @@ namespace Server.Misc Console.WriteLine("Client: {0}: Fast movement detected (name={1})", e.NetState, e.NetState.Mobile.Name); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/Geometry.cs b/Projects/Scripts/Misc/Geometry.cs index ff3fccdde..639d76896 100644 --- a/Projects/Scripts/Misc/Geometry.cs +++ b/Projects/Scripts/Misc/Geometry.cs @@ -19,26 +19,19 @@ namespace Server.Misc public static Point2D ArcPoint(Point3D loc, int radius, int angle) { - int sideA, sideB; - if (angle < 0) angle = 0; if (angle > 90) angle = 90; - sideA = (int)Math.Round(radius * Math.Sin(DegreesToRadians(angle))); - sideB = (int)Math.Round(radius * Math.Cos(DegreesToRadians(angle))); + int sideA = (int)Math.Round(radius * Math.Sin(DegreesToRadians(angle))); + int sideB = (int)Math.Round(radius * Math.Cos(DegreesToRadians(angle))); return new Point2D(loc.X - sideB, loc.Y - sideA); } - public static void Circle2D(Point3D loc, Map map, int radius, DoEffect_Callback effect) - { - Circle2D(loc, map, radius, effect, 0, 360); - } - - public static void Circle2D(Point3D loc, Map map, int radius, DoEffect_Callback effect, int angleStart, int angleEnd) + public static void Circle2D(Point3D loc, Map map, int radius, DoEffect_Callback effect, int angleStart = 0, int angleEnd = 360) { if (angleStart < 0 || angleStart > 360) angleStart = 0; @@ -147,13 +140,9 @@ namespace Server.Misc withinBounds = false; } else if (pointQuadrant == start.Quadrant && (x < startX || y > startY)) - { withinBounds = false; - } else if (pointQuadrant == end.Quadrant && (x > endX || y < endY)) - { withinBounds = false; - } return opposite ? !withinBounds : withinBounds; } @@ -218,4 +207,4 @@ namespace Server.Misc public int Quadrant{ get; } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/Gifts/Winter2004/PileOfGlacialSnow.cs b/Projects/Scripts/Misc/Gifts/Winter2004/PileOfGlacialSnow.cs index 1c6a17a03..e56ff99e9 100644 --- a/Projects/Scripts/Misc/Gifts/Winter2004/PileOfGlacialSnow.cs +++ b/Projects/Scripts/Misc/Gifts/Winter2004/PileOfGlacialSnow.cs @@ -129,9 +129,7 @@ namespace Server.Items Effects.SendMovingEffect(from, targ, 0x36E4, 7, 0, false, true, 0x47F); } else - { from.SendLocalizedMessage(1005574); // The snow is not ready to be packed yet. Keep trying. - } } else { @@ -140,11 +138,9 @@ namespace Server.Items } } else - { from.SendLocalizedMessage( 1005577); // You can only throw a snowball at something that can throw one back. - } } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/Guild.cs b/Projects/Scripts/Misc/Guild.cs index 9f6f2ec8c..8b70338c6 100644 --- a/Projects/Scripts/Misc/Guild.cs +++ b/Projects/Scripts/Misc/Guild.cs @@ -32,7 +32,7 @@ namespace Server.Guilds public class RankDefinition { - public static RankDefinition[] Ranks = + public static readonly RankDefinition[] Ranks = { new RankDefinition(1062963, 0, RankFlags.None), //Ronin new RankDefinition(1062962, 1, RankFlags.Member), //Member @@ -78,8 +78,8 @@ namespace Server.Guilds public class AllianceInfo { private Guild m_Leader; - private List m_Members; - private List m_PendingMembers; + private readonly List m_Members; + private readonly List m_PendingMembers; public AllianceInfo(Guild leader, string name, Guild partner) { @@ -154,21 +154,9 @@ namespace Server.Guilds } } - public bool IsPendingMember(Guild g) - { - if (g.Alliance != this) - return false; + public bool IsPendingMember(Guild g) => g.Alliance == this && m_PendingMembers.Contains(g); - return m_PendingMembers.Contains(g); - } - - public bool IsMember(Guild g) - { - if (g.Alliance != this) - return false; - - return m_Members.Contains(g); - } + public bool IsMember(Guild g) => g.Alliance == this && m_Members.Contains(g); public void Serialize(GenericWriter writer) { @@ -332,29 +320,18 @@ namespace Server.Guilds public void AllianceChat(Mobile from, int hue, string text) { - Packet p = null; for (int i = 0; i < m_Members.Count; i++) { Guild g = m_Members[i]; for (int j = 0; j < g.Members.Count; j++) { - Mobile m = g.Members[j]; + NetState ns = g.Members[j].NetState; - NetState state = m.NetState; - - if (state != null) - { - if (p == null) - p = Packet.Acquire(new UnicodeMessage(from.Serial, from.Body, MessageType.Alliance, hue, 3, - from.Language, from.Name, text)); - - state.Send(p); - } + if (ns != null) + Packets.SendUnicodeMessage(ns, from.Serial, from.Body, MessageType.Alliance, hue, 3, from.Language, from.Name, text); } } - - Packet.Release(p); } public void AllianceChat(Mobile from, string text) @@ -683,9 +660,7 @@ namespace Server.Guilds Mobile from = e.Mobile; if (arg.Length == 0) - { e.Mobile.Target = new GuildPropsTarget(); - } else { Guild g = uint.TryParse(arg, out uint id) @@ -720,7 +695,7 @@ namespace Server.Guilds if (o is Guildstone stone) { - if (stone?.Guild.Disbanded != false) + if (stone.Guild.Disbanded) { from.SendMessage("The guild associated with that Guildstone no longer exists"); return; @@ -729,9 +704,7 @@ namespace Server.Guilds g = stone.Guild; } else if (o is Mobile mobile) - { g = mobile.Guild as Guild; - } if (g == null) { @@ -773,13 +746,7 @@ namespace Server.Guilds public AllianceInfo Alliance { - get - { - if (m_AllianceInfo != null) - return m_AllianceInfo; - - return m_AllianceLeader?.m_AllianceInfo; - } + get => m_AllianceInfo ?? m_AllianceLeader?.m_AllianceInfo; set { AllianceInfo current = Alliance; @@ -822,10 +789,7 @@ namespace Server.Guilds { AllianceInfo alliance = g.Alliance; - if (alliance?.Leader != null && alliance.IsMember(g)) - return alliance.Leader; - - return g; + return alliance?.Leader != null && alliance.IsMember(g) ? alliance.Leader : g; } #endregion @@ -837,31 +801,9 @@ namespace Server.Guilds public List AcceptedWars{ get; private set; } - public WarDeclaration FindPendingWar(Guild g) - { - for (int i = 0; i < PendingWars.Count; i++) - { - WarDeclaration w = PendingWars[i]; + public WarDeclaration FindPendingWar(Guild g) => PendingWars.FirstOrDefault(w => w.Opponent == g); - if (w.Opponent == g) - return w; - } - - return null; - } - - public WarDeclaration FindActiveWar(Guild g) - { - for (int i = 0; i < AcceptedWars.Count; i++) - { - WarDeclaration w = AcceptedWars[i]; - - if (w.Opponent == g) - return w; - } - - return null; - } + public WarDeclaration FindActiveWar(Guild g) => AcceptedWars.FirstOrDefault(w => w.Opponent == g); public void CheckExpiredWars() { @@ -936,8 +878,7 @@ namespace Server.Guilds if (!NewGuildSystem) return; - if (killer == null) - killer = victim.FindMostRecentDamager(false); + killer ??= victim.FindMostRecentDamager(false); if (killer == null || victim.Guild == null || killer.Guild == null) return; @@ -1148,24 +1089,10 @@ namespace Server.Guilds } } - if (AllyDeclarations == null) - AllyDeclarations = new List(); - - if (AllyInvitations == null) - AllyInvitations = new List(); - - - if (AcceptedWars == null) - AcceptedWars = new List(); - - if (PendingWars == null) - PendingWars = new List(); - - - /* - if ( ( !NewGuildSystem && m_Guildstone == null )|| m_Members.Count == 0 ) - Disband(); - */ + AllyDeclarations ??= new List(); + AllyInvitations ??= new List(); + AcceptedWars ??= new List(); + PendingWars ??= new List(); Timer.DelayCall(TimeSpan.Zero, VerifyGuild_Callback); } @@ -1334,24 +1261,14 @@ namespace Server.Guilds public void GuildChat(Mobile from, int hue, string text) { - Packet p = null; for (int i = 0; i < Members.Count; i++) { - Mobile m = Members[i]; + NetState ns = Members[i].NetState; - NetState state = m.NetState; - - if (state != null) - { - if (p == null) - p = Packet.Acquire(new UnicodeMessage(from.Serial, from.Body, MessageType.Guild, hue, 3, - from.Language, from.Name, text)); - - state.Send(p); - } + if (ns != null) + Packets.SendUnicodeMessage(ns, from.Serial, from.Body, MessageType.Guild, hue, 3, + from.Language, from.Name, text); } - - Packet.Release(p); } public void GuildChat(Mobile from, string text) @@ -1402,17 +1319,12 @@ namespace Server.Guilds Mobile winner = null; int highVotes = 0; - foreach (KeyValuePair kvp in votes) - { - Mobile m = kvp.Key; - int val = kvp.Value; - + foreach ((Mobile m, int val) in votes) if (winner == null || val > highVotes) { winner = m; highVotes = val; } - } if (NewGuildSystem && highVotes * 100 / Math.Max(votingMembers, 1) < MajorityPercentage && !Disbanded && winner != m_Leader && m_Leader.Guild == this) diff --git a/Projects/Scripts/Misc/Keywords.cs b/Projects/Scripts/Misc/Keywords.cs index 6c4ac05e6..71e04ffc4 100644 --- a/Projects/Scripts/Misc/Keywords.cs +++ b/Projects/Scripts/Misc/Keywords.cs @@ -4,7 +4,7 @@ using Server.Mobiles; namespace Server.Misc { - public class Keywords + public static class Keywords { public static void Initialize() { @@ -51,4 +51,4 @@ namespace Server.Misc } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/LanguageStatistics.cs b/Projects/Scripts/Misc/LanguageStatistics.cs index f5cac3106..9a4ce9402 100644 --- a/Projects/Scripts/Misc/LanguageStatistics.cs +++ b/Projects/Scripts/Misc/LanguageStatistics.cs @@ -20,7 +20,7 @@ namespace Server.Misc * enable showing of unicode control chars **/ - public class LanguageStatistics + public static class LanguageStatistics { private static InternationalCode[] InternationalCodes = { @@ -317,13 +317,10 @@ namespace Server.Misc public int Compare(InternationalCodeCounter x, InternationalCodeCounter y) { - string a = null, b = null; - int ca = 0, cb = 0; - - a = x.Code; - ca = x.Count; - b = y.Code; - cb = y.Count; + string a = x?.Code; + int ca = x?.Count ?? 0; + string b = y?.Code; + int cb = y?.Count ?? 0; if (ca > cb) diff --git a/Projects/Scripts/Misc/LightCycle.cs b/Projects/Scripts/Misc/LightCycle.cs index 90155d0fa..14c7b0204 100644 --- a/Projects/Scripts/Misc/LightCycle.cs +++ b/Projects/Scripts/Misc/LightCycle.cs @@ -4,7 +4,7 @@ using Server.Network; namespace Server { - public class LightCycle + public static class LightCycle { public const int DayLevel = 0; public const int NightLevel = 12; @@ -69,12 +69,12 @@ namespace Server Clock.GetTime(from.Map, from.X, from.Y, out int hours, out int minutes); /* OSI times: - * + * * Midnight -> 3:59 AM : Night * 4:00 AM -> 11:59 PM : Day - * + * * RunUO times: - * + * * 10:00 PM -> 11:59 PM : Scale to night * Midnight -> 3:59 AM : Night * 4:00 AM -> 5:59 AM : Scale to day @@ -124,10 +124,10 @@ namespace Server protected override void OnTick() { - m_Owner.EndAction(); + m_Owner.EndAction(); m_Owner.LightLevel = 0; BuffInfo.RemoveBuff(m_Owner, BuffIcon.NightSight); } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/LoginStats.cs b/Projects/Scripts/Misc/LoginStats.cs index 69985c921..54a2fd3de 100644 --- a/Projects/Scripts/Misc/LoginStats.cs +++ b/Projects/Scripts/Misc/LoginStats.cs @@ -2,7 +2,7 @@ using Server.Network; namespace Server.Misc { - public class LoginStats + public static class LoginStats { public static void Initialize() { @@ -27,4 +27,4 @@ namespace Server.Misc mobileCount, mobileCount == 1 ? "" : "s"); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/MapDefinitions.cs b/Projects/Scripts/Misc/MapDefinitions.cs index f0558527a..19d8a1006 100644 --- a/Projects/Scripts/Misc/MapDefinitions.cs +++ b/Projects/Scripts/Misc/MapDefinitions.cs @@ -1,17 +1,16 @@ namespace Server.Misc { - public class MapDefinitions + public static class MapDefinitions { public static void Configure() { /* Here we configure all maps. Some notes: - * + * * 1) The first 32 maps are reserved for core use. * 2) Map 0x7F is reserved for core use. * 3) Map 0xFF is reserved for core use. * 4) Changing or removing any predefined maps may cause server instability. */ - RegisterMap(0, 0, 0, 7168, 4096, 4, "Felucca", MapRules.FeluccaRules); RegisterMap(1, 1, 1, 7168, 4096, 0, "Trammel", MapRules.TrammelRules); RegisterMap(2, 2, 2, 2304, 1600, 1, "Ilshenar", MapRules.TrammelRules); @@ -23,7 +22,7 @@ namespace Server.Misc /* Example of registering a custom map: * RegisterMap( 32, 0, 0, 6144, 4096, 3, "Iceland", MapRules.FeluccaRules ); - * + * * Defined: * RegisterMap( , , , , , , , ); * - : An unreserved unique index for this map @@ -40,7 +39,7 @@ namespace Server.Misc MultiComponentList.PostHSFormat = true; // OSI Client Patch 7.0.9.0 } - public static void RegisterMap(int mapIndex, int mapID, int fileIndex, int width, int height, int season, + public static void RegisterMap(int mapIndex, int mapID, int fileIndex, int width, int height, byte season, string name, MapRules rules) { Map newMap = new Map(mapID, mapIndex, fileIndex, width, height, season, name, rules); @@ -49,4 +48,4 @@ namespace Server.Misc Map.AllMaps.Add(newMap); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/MapUO.cs b/Projects/Scripts/Misc/MapUO.cs index 7263c6530..5ed36e88d 100644 --- a/Projects/Scripts/Misc/MapUO.cs +++ b/Projects/Scripts/Misc/MapUO.cs @@ -1,4 +1,5 @@ using System; +using Server.Buffers; using Server.Engines.PartySystem; using Server.Guilds; using Server.Network; @@ -18,35 +19,12 @@ namespace Server.Misc private static void OnPartyTrack(NetState state, PacketReader pvSrc) { - Mobile from = state.Mobile; - Party party = Party.Get(from); - - if (party != null) - { - Packets.PartyTrack packet = new Packets.PartyTrack(from, party); - - if (packet.UnderlyingStream.Length > 8) - state.Send(packet); - } + MapUOPackets.SendPartyTrack(state, Party.Get(state.Mobile)); } private static void OnGuildTrack(NetState state, PacketReader pvSrc) { - Mobile from = state.Mobile; - - if (from.Guild is Guild guild) - { - bool locations = pvSrc.ReadByte() != 0; - - Packets.GuildTrack packet = new Packets.GuildTrack(from, guild, locations); - - if (packet.UnderlyingStream.Length > (locations ? 9 : 5)) - state.Send(packet); - } - else - { - state.Send(new Packets.GuildTrack()); - } + MapUOPackets.SendGuildTrack(state, state.Mobile.Guild as Guild, pvSrc.ReadBoolean()); } private static class Settings @@ -56,75 +34,97 @@ namespace Server.Misc public const bool GuildHitsPercent = true; } - private static class Packets + private static class MapUOPackets { - public sealed class PartyTrack : ProtocolExtension + public static void SendPartyTrack(NetState ns, Party party) { - public PartyTrack(Mobile from, Party party) : base(0x01, (party.Members.Count - 1) * 9 + 4) + Mobile from = ns.Mobile; + int count = party?.Members.Count ?? 0; + if (count < 2) + return; + + SpanWriter writer = new SpanWriter(stackalloc byte[Math.Max(count - 1, 0) * 9 + 8]); + writer.Write((byte)0xF0); // Packet ID + writer.Position += 2; // Dynamic Length + + writer.Write((byte)0x01); // Command + + count = 0; + for (int i = 0; i < count; ++i) { - for (int i = 0; i < party.Members.Count; ++i) - { - PartyMemberInfo pmi = party.Members[i]; + Mobile mob = party.Members[i]?.Mobile; // if count is greater than 0, then party is not null - if (pmi == null || pmi.Mobile == from) - continue; + if (mob == from || mob?.NetState == null || Utility.InUpdateRange(from, mob) && from.CanSee(mob)) + continue; - Mobile mob = pmi.Mobile; - - if (Utility.InUpdateRange(from, mob) && from.CanSee(mob)) - continue; - - m_Stream.Write(mob.Serial); - m_Stream.Write((short)mob.X); - m_Stream.Write((short)mob.Y); - m_Stream.Write((byte)(mob.Map?.MapID ?? 0)); - } - - m_Stream.Write(0); + count++; + writer.Write(mob.Serial); + writer.Write((short)mob.X); + writer.Write((short)mob.Y); + writer.Write((byte)(mob.Map?.MapID ?? 0)); } + + if (count == 0) + return; + + writer.Position += 4; // Empty Serial + writer.Position = 1; + writer.Write((ushort)writer.WrittenCount); + + ns.Send(writer.Span); } - public sealed class GuildTrack : ProtocolExtension + public static void SendGuildTrack(NetState ns, Guild guild = null, bool locations = false) { - public GuildTrack() : base(0x02, 5) - { - m_Stream.Write((byte)0); - m_Stream.Write(0); - } + Mobile from = ns.Mobile; - public GuildTrack(Mobile from, Guild guild, bool locations) : base(0x02, - (guild.Members.Count - 1) * (locations ? 10 : 4) + 5) - { - m_Stream.Write((byte)(locations ? 1 : 0)); + int count = guild?.Members.Count ?? 0; - for (int i = 0; i < guild.Members.Count; ++i) + if (count < 2) + return; + + SpanWriter writer = new SpanWriter(stackalloc byte[Math.Max(count - 1, 0) * (locations ? 10 : 4) + 9]); + writer.Write((byte)0xF0); // Packet ID + writer.Position += 2; // Dynamic Length + + writer.Write((byte)0x02); // Command + + writer.Write(locations); + + count = 0; + for (int i = 0; i < count; ++i) + { + Mobile mob = guild.Members[i]; // If guild count is above 0, then guild is not null. + + if (mob == from || mob?.NetState == null || locations && Utility.InUpdateRange(from, mob) && from.CanSee(mob)) + continue; + + count++; + writer.Write(mob.Serial); + + if (locations) { - Mobile mob = guild.Members[i]; + writer.Write((short)mob.X); + writer.Write((short)mob.Y); + writer.Write((byte)(mob.Map?.MapID ?? 0)); - if (mob == null || mob == from || mob.NetState == null) - continue; - - if (locations && Utility.InUpdateRange(from, mob) && from.CanSee(mob)) - continue; - - m_Stream.Write(mob.Serial); - - if (locations) - { - m_Stream.Write((short)mob.X); - m_Stream.Write((short)mob.Y); - m_Stream.Write((byte)(mob.Map?.MapID ?? 0)); - - if (Settings.GuildHitsPercent && mob.Alive) - m_Stream.Write((byte)(mob.Hits / Math.Max(mob.HitsMax, 1.0) * 100)); - else - m_Stream.Write((byte)0); - } + if (Settings.GuildHitsPercent && mob.Alive) + writer.Write((byte)(mob.Hits / Math.Max(mob.HitsMax, 1.0) * 100)); + else + writer.Position++; // writer.Write((byte)0); } - - m_Stream.Write(0); } + + if (count == 0) + return; + + writer.Position += 4; // Empty Serial + + writer.Position = 1; + writer.Write((ushort)writer.WrittenCount); + + ns.Send(writer.Span); } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Items/Special/Solen Items/MessageHelper.cs b/Projects/Scripts/Misc/MessageHelper.cs similarity index 58% rename from Projects/Scripts/Items/Special/Solen Items/MessageHelper.cs rename to Projects/Scripts/Misc/MessageHelper.cs index 09f79bf9d..6bf6b001d 100644 --- a/Projects/Scripts/Items/Special/Solen Items/MessageHelper.cs +++ b/Projects/Scripts/Misc/MessageHelper.cs @@ -2,7 +2,7 @@ using Server.Network; namespace Server { - public class MessageHelper + public static class MessageHelper { public static void SendLocalizedMessageTo(Item from, Mobile to, int number, int hue) { @@ -11,12 +11,12 @@ namespace Server public static void SendLocalizedMessageTo(Item from, Mobile to, int number, string args, int hue) { - to.Send(new MessageLocalized(from.Serial, from.ItemID, MessageType.Regular, hue, 3, number, "", args)); + Packets.SendMessageLocalized(to.NetState, from.Serial, from.ItemID, MessageType.Regular, hue, 3, number, "", args); } public static void SendMessageTo(Item from, Mobile to, string text, int hue) { - to.Send(new UnicodeMessage(from.Serial, from.ItemID, MessageType.Regular, hue, 3, "ENU", "", text)); + Packets.SendUnicodeMessage(to.NetState, from.Serial, from.ItemID, MessageType.Regular, hue, 3, "ENU", "", text); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/NameList.cs b/Projects/Scripts/Misc/NameList.cs index 36ba6a249..95c8e89a0 100644 --- a/Projects/Scripts/Misc/NameList.cs +++ b/Projects/Scripts/Misc/NameList.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Xml; namespace Server diff --git a/Projects/Scripts/Misc/NameVerification.cs b/Projects/Scripts/Misc/NameVerification.cs index 44ef8f68e..250b56913 100644 --- a/Projects/Scripts/Misc/NameVerification.cs +++ b/Projects/Scripts/Misc/NameVerification.cs @@ -1,6 +1,6 @@ namespace Server.Misc { - public class NameVerification + public static class NameVerification { public static readonly char[] SpaceDashPeriodQuote = { @@ -148,20 +148,9 @@ namespace Server.Misc exceptCount = 0; } - else - { - bool except = false; - - for (int j = 0; !except && j < exceptions.Length; ++j) - if (c == exceptions[j]) - except = true; - - if (!except || i == 0 && noExceptionsAtStart) - return false; - - if (exceptCount++ == maxExceptions) - return false; - } + else if (exceptCount++ == maxExceptions || exceptions.All(exception => exception != c) || + i == 0 && noExceptionsAtStart) + return false; } for (int i = 0; i < disallowed.Length; ++i) @@ -188,11 +177,7 @@ namespace Server.Misc return false; } - for (int i = 0; i < startDisallowed.Length; ++i) - if (name.StartsWith(startDisallowed[i])) - return false; - - return true; + return startDisallowed.All(t => !name.StartsWith(t)); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/Notoriety.cs b/Projects/Scripts/Misc/Notoriety.cs index ea42bc887..7b528858d 100644 --- a/Projects/Scripts/Misc/Notoriety.cs +++ b/Projects/Scripts/Misc/Notoriety.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Engines.ConPVP; using Server.Engines.PartySystem; using Server.Factions; @@ -12,7 +13,7 @@ using Server.Spells.Seventh; namespace Server.Misc { - public class NotorietyHandlers + public static class NotorietyHandlers { public static void Initialize() { @@ -306,7 +307,7 @@ namespace Server.Misc } /* Must be thread-safe */ - public static int MobileNotoriety(Mobile source, Mobile target) + public static byte MobileNotoriety(Mobile source, Mobile target) { BaseCreature bcTarg = target as BaseCreature; @@ -429,27 +430,12 @@ namespace Server.Misc public static bool IsSummoned(BaseCreature c) => c?.Summoned == true; - public static bool CheckAggressor(List list, Mobile target) - { - for (int i = 0; i < list.Count; ++i) - if (list[i].Attacker == target) - return true; + public static bool IsSummoned(BaseCreature c) => c?.Summoned == true; - return false; - } + public static bool CheckAggressor(IEnumerable list, Mobile target) => list.Any(t => t.Attacker == target); - public static bool CheckAggressed(List list, Mobile target) - { - for (int i = 0; i < list.Count; ++i) - { - AggressorInfo info = list[i]; - - if (!info.CriminalAggression && info.Defender == target) - return true; - } - - return false; - } + public static bool CheckAggressed(IEnumerable list, Mobile target) => + list.Any(info => !info.CriminalAggression && info.Defender == target); private enum GuildStatus { diff --git a/Projects/Scripts/Misc/Paperdoll.cs b/Projects/Scripts/Misc/Paperdoll.cs index 4ba425c74..8ad46e846 100644 --- a/Projects/Scripts/Misc/Paperdoll.cs +++ b/Projects/Scripts/Misc/Paperdoll.cs @@ -3,7 +3,7 @@ using Server.Network; namespace Server.Misc { - public class Paperdoll + public static class Paperdoll { public static void Initialize() { @@ -13,21 +13,22 @@ namespace Server.Misc public static void EventSink_PaperdollRequest(PaperdollRequestEventArgs e) { Mobile beholder = e.Beholder; + NetState ns = beholder.NetState; Mobile beheld = e.Beheld; - beholder.Send(new DisplayPaperdoll(beheld, Titles.ComputeTitle(beholder, beheld), - beheld.AllowEquipFrom(beholder))); + Packets.SendDisplayPaperdoll(ns, beholder, Titles.ComputeTitle(beholder, beheld), + beheld.AllowEquipFrom(beholder)); if (ObjectPropertyList.Enabled) { List items = beheld.Items; for (int i = 0; i < items.Count; ++i) - beholder.Send(items[i].OPLPacket); + items[i].PropertyList.SendOPLInfo(ns); // NOTE: OSI sends MobileUpdate when opening your own paperdoll. // It has a very bad rubber-banding affect. What positive affects does it have? } } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/ProfanityProtection.cs b/Projects/Scripts/Misc/ProfanityProtection.cs index 514589214..0f6ebb23e 100644 --- a/Projects/Scripts/Misc/ProfanityProtection.cs +++ b/Projects/Scripts/Misc/ProfanityProtection.cs @@ -99,10 +99,7 @@ namespace Server.Misc return false; } default: - case ProfanityAction.Other: // TODO: Provide custom implementation if this is chosen - { return true; - } } } @@ -118,4 +115,4 @@ namespace Server.Misc e.Blocked = !OnProfanityDetected(from, e.Speech); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/Profile.cs b/Projects/Scripts/Misc/Profile.cs index 98731f549..c87afd5eb 100644 --- a/Projects/Scripts/Misc/Profile.cs +++ b/Projects/Scripts/Misc/Profile.cs @@ -4,7 +4,7 @@ using Server.Network; namespace Server.Misc { - public class Profile + public static class Profile { public static void Initialize() { @@ -48,12 +48,9 @@ namespace Server.Misc if (footer.Length == 0 && beholder == beheld) footer = GetAccountDuration(beheld); - string body = beheld.Profile; + string body = beheld.Profile ?? ""; - if (body == null || body.Length <= 0) - body = ""; - - beholder.Send(new DisplayProfile(beholder != beheld || !beheld.ProfileLocked, beheld, header, body, footer)); + Packets.SendDisplayProfile(beholder.NetState, beholder != beheld || !beheld.ProfileLocked ? beheld.Serial : Serial.Zero, header, body, footer); } private static string GetAccountDuration(Mobile m) @@ -72,10 +69,7 @@ namespace Server.Misc if (Format(ts.TotalMinutes, "This account is {0} minute{1} old.", out v)) return v; - if (Format(ts.TotalSeconds, "This account is {0} second{1} old.", out v)) - return v; - - return ""; + return Format(ts.TotalSeconds, "This account is {0} second{1} old.", out v) ? v : ""; } public static bool Format(double value, string format, out string op) @@ -90,4 +84,4 @@ namespace Server.Misc return false; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/ProtocolExtensions.cs b/Projects/Scripts/Misc/ProtocolExtensions.cs index 5aeee0a96..6b3e3290e 100644 --- a/Projects/Scripts/Misc/ProtocolExtensions.cs +++ b/Projects/Scripts/Misc/ProtocolExtensions.cs @@ -3,9 +3,9 @@ using Server.Network; namespace Server.Misc { - public class ProtocolExtensions + public static class ProtocolExtensions { - private static PacketHandler[] m_Handlers = new PacketHandler[0x100]; + private static readonly PacketHandler[] m_Handlers = new PacketHandler[0x100]; public static void Initialize() { @@ -17,48 +17,34 @@ namespace Server.Misc m_Handlers[packetID] = new PacketHandler(packetID, 0, ingame, onReceive); } - public static PacketHandler GetHandler(int packetID) - { - if (packetID >= 0 && packetID < m_Handlers.Length) - return m_Handlers[packetID]; - - return null; - } + public static PacketHandler GetHandler(int packetID) => packetID >= 0 && packetID < m_Handlers.Length ? m_Handlers[packetID] : null; public static void DecodeBundledPacket(NetState state, PacketReader pvSrc) { int packetID = pvSrc.ReadByte(); PacketHandler ph = GetHandler(packetID); + if (ph == null) + return; - if (ph != null) + if (ph.Ingame) { - if (ph.Ingame && state.Mobile == null) + if (state.Mobile == null) { Console.WriteLine( - "Client: {0}: Sent ingame packet (0xF0x{1:X2}) before having been attached to a mobile", state, - packetID); + "Client: {0}: Sent ingame packet (0xF0x{1:X2}) before having been attached to a mobile", state, packetID); state.Dispose(); + return; } - else if (ph.Ingame && state.Mobile.Deleted) + + if (state.Mobile.Deleted) { state.Dispose(); - } - else - { - ph.OnReceive(state, pvSrc); + return; } } + + ph.OnReceive(state, pvSrc); } } - - public abstract class ProtocolExtension : Packet - { - public ProtocolExtension(int packetID, int capacity) : base(0xF0) - { - EnsureCapacity(4 + capacity); - - m_Stream.Write((byte)packetID); - } - } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/RaceDefinitions.cs b/Projects/Scripts/Misc/RaceDefinitions.cs index eb9720308..7f3c4aaa6 100644 --- a/Projects/Scripts/Misc/RaceDefinitions.cs +++ b/Projects/Scripts/Misc/RaceDefinitions.cs @@ -1,3 +1,5 @@ +using System.Linq; + namespace Server.Misc { public class RaceDefinitions @@ -30,22 +32,9 @@ namespace Server.Misc { } - public override bool ValidateHair(bool female, int itemID) - { - if (itemID == 0) - return true; - - if (female && itemID == 0x2048 || !female && itemID == 0x2046) - return false; //Buns & Receding Hair - - if (itemID >= 0x203B && itemID <= 0x203D) - return true; - - if (itemID >= 0x2044 && itemID <= 0x204A) - return true; - - return false; - } + public override bool ValidateHair(bool female, int itemID) => + itemID == 0 || (!female || itemID != 0x2048) && (female || itemID != 0x2046) && + (itemID >= 0x203B && itemID <= 0x203D || itemID >= 0x2044 && itemID <= 0x204A); public override int RandomHair(bool female) //Random hair doesn't include baldness { @@ -90,32 +79,18 @@ namespace Server.Misc return (rand < 4 ? 0x203E : 0x2047) + rand; } - public override int ClipSkinHue(int hue) - { - if (hue < 1002) - return 1002; - if (hue > 1058) - return 1058; - return hue; - } + public override int ClipSkinHue(int hue) => hue < 1002 ? 1002 : hue > 1058 ? 1058 : hue; public override int RandomSkinHue() => Utility.Random(1002, 57) | 0x8000; - public override int ClipHairHue(int hue) - { - if (hue < 1102) - return 1102; - if (hue > 1149) - return 1149; - return hue; - } + public override int ClipHairHue(int hue) => hue < 1102 ? 1102 : hue > 1149 ? 1149 : hue; public override int RandomHairHue() => Utility.Random(1102, 48); } private class Elf : Race { - private static int[] m_SkinHues = + private static readonly int[] m_SkinHues = { 0x0BF, 0x24D, 0x24E, 0x24F, 0x353, 0x361, 0x367, 0x374, 0x375, 0x376, 0x381, 0x382, 0x383, 0x384, 0x385, 0x389, @@ -123,7 +98,7 @@ namespace Server.Misc 0x51D, 0x53F, 0x579, 0x76B, 0x76C, 0x76D, 0x835, 0x903 }; - private static int[] m_HairHues = + private static readonly int[] m_HairHues = { 0x034, 0x035, 0x036, 0x037, 0x038, 0x039, 0x058, 0x08E, 0x08F, 0x090, 0x091, 0x092, 0x101, 0x159, 0x15A, 0x15B, @@ -139,10 +114,10 @@ namespace Server.Misc { } - public override bool ValidateHair(bool female, int itemID) - { - if (itemID == 0) - return true; + public override bool ValidateHair(bool female, int itemID) => + itemID == 0 || (!female || itemID != 0x2FCD && itemID != 0x2FBF) && + (female || itemID != 0x2FCC && itemID != 0x2FD0) && + (itemID >= 0x2FBF && itemID <= 0x2FC2 || itemID >= 0x2FCC && itemID <= 0x2FD1); if (female && (itemID == 0x2FCD || itemID == 0x2FBF) || !female && (itemID == 0x2FCC || itemID == 0x2FD0)) return false; @@ -186,14 +161,9 @@ namespace Server.Misc public override int RandomSkinHue() => m_SkinHues[Utility.Random(m_SkinHues.Length)] | 0x8000; - public override int ClipHairHue(int hue) - { - for (int i = 0; i < m_HairHues.Length; i++) - if (m_HairHues[i] == hue) - return hue; + public override int RandomSkinHue() => m_SkinHues[Utility.Random(m_SkinHues.Length)] | 0x8000; - return m_HairHues[0]; - } + public override int ClipHairHue(int hue) => m_HairHues.Any(t => t == hue) ? hue : m_HairHues[0]; public override int RandomHairHue() => m_HairHues[Utility.Random(m_HairHues.Length)]; } @@ -225,13 +195,11 @@ namespace Server.Misc { } - public override bool ValidateHair(bool female, int itemID) - { - if (female == false) return itemID >= 0x4258 && itemID <= 0x425F; - - return itemID == 0x4261 || itemID == 0x4262 || itemID >= 0x4273 && itemID <= 0x4275 || itemID == 0x42B0 || - itemID == 0x42B1 || itemID == 0x42AA || itemID == 0x42AB; - } + public override bool ValidateHair(bool female, int itemID) => + female == false + ? itemID >= 0x4258 && itemID <= 0x425F + : itemID == 0x4261 || itemID == 0x4262 || itemID >= 0x4273 && itemID <= 0x4275 || itemID == 0x42B0 || + itemID == 0x42B1 || itemID == 0x42AA || itemID == 0x42AB; public override int RandomHair(bool female) { @@ -262,14 +230,9 @@ namespace Server.Misc public override int RandomSkinHue() => m_BodyHues[Utility.Random(m_BodyHues.Length)] | 0x8000; - public override int ClipHairHue(int hue) - { - for (int i = 0; i < m_HornHues.Length; i++) - if (m_HornHues[i] == hue) - return hue; + public override int RandomSkinHue() => m_BodyHues[Utility.Random(m_BodyHues.Length)] | 0x8000; - return m_HornHues[0]; - } + public override int ClipHairHue(int hue) => m_HornHues.Any(t => t == hue) ? hue : m_HornHues[0]; public override int RandomHairHue() => m_HornHues[Utility.Random(m_HornHues.Length)]; } diff --git a/Projects/Scripts/Misc/ServerList.cs b/Projects/Scripts/Misc/ServerList.cs index 469fc8d84..885d3f8fb 100644 --- a/Projects/Scripts/Misc/ServerList.cs +++ b/Projects/Scripts/Misc/ServerList.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; @@ -9,18 +10,18 @@ namespace Server.Misc { public class ServerList { - /* + /* * The default setting for Address, a value of 'null', will use your local IP address. If all of your local IP addresses * are private network addresses and AutoDetect is 'true' then RunUO will attempt to discover your public IP address * for you automatically. * * If you do not plan on allowing clients outside of your LAN to connect, you can set AutoDetect to 'false' and leave * Address set to 'null'. - * + * * If your public IP address cannot be determined, you must change the value of Address to your public IP address * manually to allow clients outside of your LAN to connect to your server. Address can be either an IP address or * a hostname that will be resolved when RunUO starts. - * + * * If you want players outside your LAN to be able to connect to your server and you are behind a router, you must also * forward TCP port 2593 to your private IP address. The procedure for doing this varies by manufacturer but generally * involves configuration of the router through your web browser. @@ -32,7 +33,7 @@ namespace Server.Misc * properly and fully supports listening on multiple ports. If a client with a public IP address is connecting to a * locally private address, the server will direct the client to either the AutoDetected IP address or the manually entered * IP address or hostname, whichever is applicable. Loopback clients will be directed to loopback. - * + * * If you would like to listen on additional ports (i.e. 22, 23, 80, for clients behind highly restrictive egress * firewalls) or specific IP adddresses you can do so by modifying the file SocketOptions.cs found in this directory. */ @@ -111,7 +112,7 @@ namespace Server.Misc IPHostEntry iphe = Dns.GetHostEntry(addr); if (iphe.AddressList.Length > 0) - outValue = iphe.AddressList[iphe.AddressList.Length - 1]; + outValue = iphe.AddressList[^1]; } catch { @@ -119,65 +120,23 @@ namespace Server.Misc } } - private static bool HasPublicIPAddress() - { - NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); + private static bool HasPublicIPAddress() => + NetworkInterface.GetAllNetworkInterfaces().Select(adapter => adapter.GetIPProperties()) + .Any(properties => properties.UnicastAddresses.Select(unicast => unicast.Address) + .Any(ip => !IPAddress.IsLoopback(ip) && ip.AddressFamily != AddressFamily.InterNetworkV6 && !IsPrivateNetwork(ip))); - foreach (NetworkInterface adapter in adapters) - { - IPInterfaceProperties properties = adapter.GetIPProperties(); - - foreach (IPAddressInformation unicast in properties.UnicastAddresses) - { - IPAddress ip = unicast.Address; - - if (!IPAddress.IsLoopback(ip) && ip.AddressFamily != AddressFamily.InterNetworkV6 && - !IsPrivateNetwork(ip)) - return true; - } - } - - return false; - - - /* - IPHostEntry iphe = Dns.GetHostEntry( Dns.GetHostName() ); - - IPAddress[] ips = iphe.AddressList; - - for ( int i = 0; i < ips.Length; ++i ) - { - if ( ips[i].AddressFamily != AddressFamily.InterNetworkV6 && !IsPrivateNetwork( ips[i] ) ) - return true; - } - - return false; - */ - } - - private static bool IsPrivateNetwork(IPAddress ip) - { - // 10.0.0.0/8 - // 172.16.0.0/12 - // 192.168.0.0/16 - // 169.254.0.0/16 - // 100.64.0.0/10 RFC 6598 - - if (ip.AddressFamily == AddressFamily.InterNetworkV6) - return false; - - if (Utility.IPMatch("192.168.*", ip)) - return true; - if (Utility.IPMatch("10.*", ip)) - return true; - if (Utility.IPMatch("172.16-31.*", ip)) - return true; - if (Utility.IPMatch("169.254.*", ip)) - return true; - if (Utility.IPMatch("100.64-127.*", ip)) - return true; - return false; - } + // 10.0.0.0/8 + // 172.16.0.0/12 + // 192.168.0.0/16 + // 169.254.0.0/16 + // 100.64.0.0/10 RFC 6598 + private static bool IsPrivateNetwork(IPAddress ip) => + ip.AddressFamily != AddressFamily.InterNetworkV6 && + (Utility.IPMatch("192.168.*", ip) || + Utility.IPMatch("10.*", ip) || + Utility.IPMatch("172.16-31.*", ip) || + Utility.IPMatch("169.254.*", ip) || + Utility.IPMatch("100.64-127.*", ip)); private static IPAddress FindPublicAddress() { @@ -193,7 +152,7 @@ namespace Server.Misc StreamReader sr = new StreamReader(s); - IPAddress ip = IPAddress.Parse(sr.ReadLine()); + IPAddress ip = IPAddress.Parse(sr.ReadLine() ?? ""); sr.Close(); s.Close(); diff --git a/Projects/Scripts/Misc/ShardPoller.cs b/Projects/Scripts/Misc/ShardPoller.cs index 2e94a58c2..484c60db9 100644 --- a/Projects/Scripts/Misc/ShardPoller.cs +++ b/Projects/Scripts/Misc/ShardPoller.cs @@ -4,7 +4,6 @@ using System.Net; using System.Text.RegularExpressions; using Server.Gumps; using Server.Network; -using Server.Prompts; namespace Server.Misc { @@ -465,9 +464,7 @@ namespace Server.Misc public void QueuePoll(ShardPoller poller) { - if (m_Polls == null) - m_Polls = new Queue(4); - + m_Polls ??= new Queue(4); m_Polls.Enqueue(poller); } diff --git a/Projects/Scripts/Misc/SkillCheck.cs b/Projects/Scripts/Misc/SkillCheck.cs index c0ead7ea3..b1ca705b0 100644 --- a/Projects/Scripts/Misc/SkillCheck.cs +++ b/Projects/Scripts/Misc/SkillCheck.cs @@ -224,7 +224,7 @@ namespace Server.Misc Skills skills = from.Skills; - if (from.Player && skills.Total / skills.Cap >= Utility.RandomDouble()) //( skills.Total >= skills.Cap ) + if (from.Player && skills.Total / (double)skills.Cap >= Utility.RandomDouble()) //( skills.Total >= skills.Cap ) for (int i = 0; i < skills.Length; ++i) { Skill toLower = skills[i]; diff --git a/Projects/Scripts/Misc/Titles.cs b/Projects/Scripts/Misc/Titles.cs index 2ff78569f..ee2d50860 100644 --- a/Projects/Scripts/Misc/Titles.cs +++ b/Projects/Scripts/Misc/Titles.cs @@ -373,8 +373,7 @@ namespace Server.Misc { int fp = Math.Min(skill.BaseFixedPoint, 1200); - return (fp - 300) / 100; - } + private static int GetTableIndex(Skill skill) => (Math.Min(skill.BaseFixedPoint, 1200) - 300) / 100; } public class FameEntry diff --git a/Projects/Scripts/Misc/TreasureMapProtection.cs b/Projects/Scripts/Misc/TreasureMapProtection.cs index 16f3951bc..bdc79fdbb 100644 --- a/Projects/Scripts/Misc/TreasureMapProtection.cs +++ b/Projects/Scripts/Misc/TreasureMapProtection.cs @@ -19,7 +19,7 @@ namespace Server public static void Initialize() { string filePath = Path.Combine(Core.BaseDirectory, "Data/treasure.cfg"); - int i = 0, x = 0, y = 0; + int i = 0; if (File.Exists(filePath)) { @@ -69,4 +69,4 @@ namespace Server m.SendMessage("You have left a protected treasure map area."); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Misc/VendorGenerator.cs b/Projects/Scripts/Misc/VendorGenerator.cs index 40451ac82..204f6a6da 100644 --- a/Projects/Scripts/Misc/VendorGenerator.cs +++ b/Projects/Scripts/Misc/VendorGenerator.cs @@ -347,8 +347,6 @@ namespace Server private static bool CanFit(Map map, int x, int y, int z) { - bool hasSurface = false; - LandTile lt = map.Tiles.GetLandTile(x, y); int lowZ = 0, avgZ = 0, topZ = 0; @@ -357,8 +355,8 @@ namespace Server if ((landFlags & TileFlag.Impassable) != 0 && topZ > z && z + 16 > lowZ) return false; - if ((landFlags & TileFlag.Impassable) == 0 && z == avgZ && !lt.Ignored) - hasSurface = true; + + bool hasSurface = (landFlags & TileFlag.Impassable) == 0 && z == avgZ && !lt.Ignored; StaticTile[] staticTiles = map.Tiles.GetStaticTiles(x, y); @@ -376,8 +374,8 @@ namespace Server if ((surface || impassable) && staticTiles[i].Z + id.CalcHeight > z && z + 16 > staticTiles[i].Z) return false; - if (surface && !impassable && z == staticTiles[i].Z + id.CalcHeight) - hasSurface = true; + + hasSurface |= surface && !impassable && z == staticTiles[i].Z + id.CalcHeight; } Sector sector = map.GetSector(x, y); @@ -395,8 +393,8 @@ namespace Server if ((surface || impassable) && item.Z + id.CalcHeight > z && z + 16 > item.Z) return false; - if (surface && !impassable && z == item.Z + id.CalcHeight) - hasSurface = true; + + hasSurface |= surface && !impassable && z == item.Z + id.CalcHeight; } } @@ -413,9 +411,9 @@ namespace Server floor.Add(p); for (int xo = -1; xo <= 1; ++xo) - for (int yo = -1; yo <= 1; ++yo) - if ((xo != 0 || yo != 0) && IsFloor(map, x + xo, y + yo, false)) - RecurseFindFloor(map, x + xo, y + yo, floor); + for (int yo = -1; yo <= 1; ++yo) + if ((xo != 0 || yo != 0) && IsFloor(map, x + xo, y + yo, false)) + RecurseFindFloor(map, x + xo, y + yo, floor); } [Flags] diff --git a/Projects/Scripts/Misc/Weather.cs b/Projects/Scripts/Misc/Weather.cs index 34d3aa2c4..c9ff68246 100644 --- a/Projects/Scripts/Misc/Weather.cs +++ b/Projects/Scripts/Misc/Weather.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Items; using Server.Network; diff --git a/Projects/Scripts/Misc/WeightOverloading.cs b/Projects/Scripts/Misc/WeightOverloading.cs index 27704df0a..b09a9e653 100644 --- a/Projects/Scripts/Misc/WeightOverloading.cs +++ b/Projects/Scripts/Misc/WeightOverloading.cs @@ -23,21 +23,12 @@ namespace Server.Misc public static void FatigueOnDamage(Mobile m, int damage) { - double fatigue = 0.0; - - switch (DFA) + double fatigue = DFA switch { - case DFAlgorithm.Standard: - { - fatigue = damage * (100.0 / m.Hits) * ((double)m.Stam / 100) - 5.0; - break; - } - case DFAlgorithm.PainSpike: - { - fatigue = damage * (100.0 / m.Hits + (50.0 + m.Stam) / 100 - 1.0) - 5.0; - break; - } - } + DFAlgorithm.Standard => damage * (100.0 / m.Hits) * ((double)m.Stam / 100) - 5.0, + DFAlgorithm.PainSpike => damage * (100.0 / m.Hits + (50.0 + m.Stam) / 100 - 1.0) - 5.0, + _ => 0.0, + }; if (fatigue > 0) m.Stam -= (int)fatigue; @@ -117,4 +108,4 @@ namespace Server.Misc return Mobile.BodyWeight + m.TotalWeight > GetMaxWeight(m) + OverloadAllowance; } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/AI/AnimalAI.cs b/Projects/Scripts/Mobiles/AI/AnimalAI.cs index 9cc4585ea..90ad332d5 100644 --- a/Projects/Scripts/Mobiles/AI/AnimalAI.cs +++ b/Projects/Scripts/Mobiles/AI/AnimalAI.cs @@ -1,5 +1,5 @@ // Ideas -// When you run on animals the panic +// When you run on animals they panic // When if ( distance < 8 && Utility.RandomDouble() * Math.Sqrt( (8 - distance) / 6 ) >= incoming.Skills.AnimalTaming.Value ) // More your close, the more it can panic /* diff --git a/Projects/Scripts/Mobiles/AI/BaseAI.cs b/Projects/Scripts/Mobiles/AI/BaseAI.cs index 801a02665..5ecb9dafc 100644 --- a/Projects/Scripts/Mobiles/AI/BaseAI.cs +++ b/Projects/Scripts/Mobiles/AI/BaseAI.cs @@ -12,7 +12,6 @@ using Server.Regions; using Server.Spells; using Server.Spells.Spellweaving; using Server.Targets; -using MoveImpl = Server.Movement.MovementImpl; namespace Server.Mobiles { @@ -111,18 +110,7 @@ namespace Server.Mobiles m_Timer = new AITimer(this); - bool activate; - - if (!m.PlayerRangeSensitive) - activate = true; - else if (World.Loading) - activate = false; - else if (m.Map == null || m.Map == Map.Internal || !m.Map.GetSector(m).Active) - activate = false; - else - activate = true; - - if (activate) + if (!(m.PlayerRangeSensitive || World.Loading || m.Map == null || m.Map == Map.Internal || !m.Map.GetSector(m).Active)) m_Timer.Start(); Action = ActionType.Wander; @@ -1689,20 +1677,17 @@ namespace Server.Mobiles bool isPassive = delay == m_Mobile.PassiveSpeed; bool isControlled = m_Mobile.Controlled || m_Mobile.Summoned; - if (delay == 0.2) - delay = 0.3; - else if (delay == 0.25) - delay = 0.45; - else if (delay == 0.3) - delay = 0.6; - else if (delay == 0.4) - delay = 0.9; - else if (delay == 0.5) - delay = 1.05; - else if (delay == 0.6) - delay = 1.2; - else if (delay == 0.8) - delay = 1.5; + delay = delay switch + { + 0.2 => 0.3, + 0.25 => 0.45, + 0.3 => 0.6, + 0.4 => 0.9, + 0.5 => 1.05, + 0.6 => 1.2, + 0.8 => 1.5, + _ => delay + }; if (isPassive) delay += 0.2; @@ -1782,13 +1767,13 @@ namespace Server.Mobiles m_Mobile.Pushing = false; - MoveImpl.IgnoreMovableImpassables = m_Mobile.CanMoveOverObstacles && !m_Mobile.CanDestroyObstacles; + MovementImpl.IgnoreMovableImpassables = m_Mobile.CanMoveOverObstacles && !m_Mobile.CanDestroyObstacles; if ((m_Mobile.Direction & Direction.Mask) != (d & Direction.Mask)) { bool v = m_Mobile.Move(d); - MoveImpl.IgnoreMovableImpassables = false; + MovementImpl.IgnoreMovableImpassables = false; return v ? MoveResult.Success : MoveResult.Blocked; } @@ -1810,7 +1795,7 @@ namespace Server.Mobiles if (map != null) { int x = m_Mobile.X, y = m_Mobile.Y; - Movement.Movement.Offset(d, ref x, ref y); + Movement.Offset(d, ref x, ref y); int destroyables = 0; @@ -1899,20 +1884,20 @@ namespace Server.Mobiles if (m_Mobile.Move(m_Mobile.Direction)) { - MoveImpl.IgnoreMovableImpassables = false; + MovementImpl.IgnoreMovableImpassables = false; return MoveResult.SuccessAutoTurn; } } - MoveImpl.IgnoreMovableImpassables = false; + MovementImpl.IgnoreMovableImpassables = false; return wasPushing ? MoveResult.BadState : MoveResult.Blocked; } - MoveImpl.IgnoreMovableImpassables = false; + MovementImpl.IgnoreMovableImpassables = false; return MoveResult.Success; } - MoveImpl.IgnoreMovableImpassables = false; + MovementImpl.IgnoreMovableImpassables = false; return MoveResult.Success; } @@ -2022,9 +2007,9 @@ namespace Server.Mobiles return true; } - if (m_Path?.Goal == m) + if (ReferenceEquals(m_Path?.Goal, m)) { - if (m_Path.Follow(run, 1)) + if (m_Path?.Follow(run, 1) == true) { m_Path = null; return true; @@ -2032,8 +2017,7 @@ namespace Server.Mobiles } else if (!DoMove(m_Mobile.GetDirectionTo(m), true)) { - m_Path = new PathFollower(m_Mobile, m); - m_Path.Mover = DoMoveImpl; + m_Path = new PathFollower(m_Mobile, m) {Mover = DoMoveImpl}; if (m_Path.Follow(run, 1)) { @@ -2075,30 +2059,23 @@ namespace Server.Mobiles if (iCurrDist < iWantDistMin || iCurrDist > iWantDistMax) { bool needCloser = iCurrDist > iWantDistMax; - bool needFurther = !needCloser; - if (needCloser && m_Path != null && m_Path.Goal == m) + if (needCloser && m_Path != null && ReferenceEquals(m_Path.Goal, m)) { if (m_Path.Follow(bRun, 1)) m_Path = null; } else { - Direction dirTo; - - if (iCurrDist > iWantDistMax) - dirTo = m_Mobile.GetDirectionTo(m); - else - dirTo = m.GetDirectionTo(m_Mobile); + Direction dirTo = iCurrDist > iWantDistMax ? m_Mobile.GetDirectionTo(m) : m.GetDirectionTo(m_Mobile); // Add the run flag if (bRun) - dirTo = dirTo | Direction.Running; + dirTo |= Direction.Running; if (!DoMove(dirTo, true) && needCloser) { - m_Path = new PathFollower(m_Mobile, m); - m_Path.Mover = DoMoveImpl; + m_Path = new PathFollower(m_Mobile, m) {Mover = DoMoveImpl}; if (m_Path.Follow(bRun, 1)) m_Path = null; @@ -2704,13 +2681,9 @@ namespace Server.Mobiles } if (m_Owner.m_Mobile.BardPacified) - { m_Owner.DoBardPacified(); - } else if (m_Owner.m_Mobile.BardProvoked) - { m_Owner.DoBardProvoked(); - } else { if (!m_Owner.m_Mobile.Controlled) diff --git a/Projects/Scripts/Mobiles/AI/HealerAI.cs b/Projects/Scripts/Mobiles/AI/HealerAI.cs index f5fe4f341..68c51964a 100644 --- a/Projects/Scripts/Mobiles/AI/HealerAI.cs +++ b/Projects/Scripts/Mobiles/AI/HealerAI.cs @@ -1,3 +1,4 @@ +using System.Linq; using Server.Spells; using Server.Spells.First; using Server.Spells.Fourth; @@ -116,19 +117,16 @@ namespace Server.Mobiles if (!m_Mobile.CanSee(m) || !(m is BaseCreature) || ((BaseCreature)m).Team != m_Mobile.Team) continue; - for (int i = 0; i < funcs.Length; ++i) - if (funcs[i](m)) + if (funcs.Any(t => t(m))) + { + double val = -m_Mobile.GetDistanceToSqrt(m); + + if (found == null || val > prio) { - double val = -m_Mobile.GetDistanceToSqrt(m); - - if (found == null || val > prio) - { - prio = val; - found = m; - } - - break; + prio = val; + found = m; } + } } return found; diff --git a/Projects/Scripts/Mobiles/AI/MageAI.cs b/Projects/Scripts/Mobiles/AI/MageAI.cs index e4f9e69a5..0cc8875f6 100644 --- a/Projects/Scripts/Mobiles/AI/MageAI.cs +++ b/Projects/Scripts/Mobiles/AI/MageAI.cs @@ -339,18 +339,17 @@ namespace Server.Mobiles if (m_Mobile.Skills.Magery.Value >= 80.0 && Utility.RandomBool()) return new ManaVampireSpell(m_Mobile); - return new ManaDrainSpell(m_Mobile); - } + public virtual Spell GetRandomManaDrainSpell() => + m_Mobile.Skills.Magery.Value >= 80.0 && Utility.RandomBool() + ? (Spell)new ManaVampireSpell(m_Mobile) + : new ManaDrainSpell(m_Mobile); public virtual Spell DoDispel(Mobile toDispel) { if (!SmartAI) - { - if (ScaleBySkill(DispelChance, SkillName.Magery) > Utility.RandomDouble()) - return new DispelSpell(m_Mobile); - - return ChooseSpell(toDispel); - } + return ScaleBySkill(DispelChance, SkillName.Magery) > Utility.RandomDouble() + ? new DispelSpell(m_Mobile) + : ChooseSpell(toDispel); Spell spell = CheckCastHealingSpell(); diff --git a/Projects/Scripts/Mobiles/Animals/Mounts/Ethereals.cs b/Projects/Scripts/Mobiles/Animals/Mounts/Ethereals.cs index b2e2a7995..6478c7d68 100644 --- a/Projects/Scripts/Mobiles/Animals/Mounts/Ethereals.cs +++ b/Projects/Scripts/Mobiles/Animals/Mounts/Ethereals.cs @@ -364,13 +364,8 @@ namespace Server.Mobiles Disturb(DisturbType.Hurt, false); } - public override bool CheckDisturb(DisturbType type, bool checkFirst, bool resistable) - { - if (type == DisturbType.EquipRequest || type == DisturbType.UseRequest /* || type == DisturbType.Hurt*/) - return false; - - return true; - } + public override bool CheckDisturb(DisturbType type, bool checkFirst, bool resistable) => + type != DisturbType.EquipRequest && type != DisturbType.UseRequest; public override void DoHurtFizzle() { diff --git a/Projects/Scripts/Mobiles/Animals/Mounts/Kirin.cs b/Projects/Scripts/Mobiles/Animals/Mounts/Kirin.cs index 650e1194a..1e5d70fd5 100644 --- a/Projects/Scripts/Mobiles/Animals/Mounts/Kirin.cs +++ b/Projects/Scripts/Mobiles/Animals/Mounts/Kirin.cs @@ -78,7 +78,7 @@ namespace Server.Mobiles if (Rider.Hits - damage < 30 && Rider.Map == attacker.Map && Rider.InRange(attacker, 18) ) //Range and map checked here instead of other base fuction because of abiliites that don't need to check this { - attacker.BoltEffect(0); + attacker.BoltEffect(); // 35~100 damage, unresistable, by the Ki-rin. attacker.Damage(Utility.RandomMinMax(35, 100), this, false); //Don't inform mount about this damage, Still unsure wether or not it's flagged as the mount doing damage or the player. If changed to player, without the extra bool it'd be an infinite loop diff --git a/Projects/Scripts/Mobiles/BaseCreature.cs b/Projects/Scripts/Mobiles/BaseCreature.cs index 26d7e716d..927e57603 100644 --- a/Projects/Scripts/Mobiles/BaseCreature.cs +++ b/Projects/Scripts/Mobiles/BaseCreature.cs @@ -327,6 +327,7 @@ namespace Server.Mobiles { if (m_Paragon == value) return; + if (value) Paragon.Convert(this); else @@ -915,7 +916,7 @@ namespace Server.Mobiles return (double)chance / 1000; } - public override void Damage(int amount, Mobile from) + public override void Damage(int amount, Mobile from = null, bool informMount = true) { int oldHits = Hits; @@ -930,10 +931,10 @@ namespace Server.Mobiles if (oath == this) { amount = (int)(amount * 1.1); - from.Damage(amount, from); + from?.Damage(amount, from); } - base.Damage(amount, from); + base.Damage(amount, from, informMount); if (SubdueBeforeTame && !Controlled && oldHits > HitsMax / 10 && Hits <= HitsMax / 10) PublicOverheadMessage(MessageType.Regular, 0x3B2, false, @@ -2110,9 +2111,7 @@ namespace Server.Mobiles } } else if (ReacquireOnMovement) - { ForceReacquire(); - } InhumanSpeech speechType = SpeechType; @@ -2133,10 +2132,7 @@ namespace Server.Mobiles if (MLQuestSystem.Enabled && CanShout && m is PlayerMobile mobile) CheckShout(mobile, oldLocation); - if (m_NoDupeGuards == m) - return; - - if (!Body.IsHuman || Kills >= 5 || AlwaysMurderer || AlwaysAttackable || m.Kills < 5 || + if (m_NoDupeGuards == m || !Body.IsHuman || Kills >= 5 || AlwaysMurderer || AlwaysAttackable || m.Kills < 5 || !m.InRange(Location, 12) || !m.Alive) return; @@ -3056,7 +3052,12 @@ namespace Server.Mobiles IsDeadPet = false; - Effects.SendPacket(Location, Map, new BondedStatus(0, Serial, 0)); + IPooledEnumerable eable = Map.GetClientsInRange(Location); + + foreach (NetState ns in eable) + Packets.SendBondStatus(ns, Serial, false); + + eable.Free(); SendIncomingPacket(); SendIncomingPacket(); @@ -3100,10 +3101,7 @@ namespace Server.Mobiles m_ReturnQueued = true; } - else if (PlayerRangeSensitive) - { - AIObject?.Deactivate(); - } + else if (PlayerRangeSensitive) AIObject?.Deactivate(); base.OnSectorDeactivate(); } @@ -3237,15 +3235,11 @@ namespace Server.Mobiles { if (m_MLQuests == null) { - if (StaticMLQuester) - m_MLQuests = MLQuestSystem.FindQuestList(GetType()); - else - m_MLQuests = ConstructQuestList(); + m_MLQuests = StaticMLQuester ? MLQuestSystem.FindQuestList(GetType()) : ConstructQuestList(); + // return EmptyList, but don't cache it (run construction again next time) if (m_MLQuests == null) - return - MLQuestSystem - .EmptyList; // return EmptyList, but don't cache it (run construction again next time) + return MLQuestSystem.EmptyList; } return m_MLQuests; @@ -3269,9 +3263,7 @@ namespace Server.Mobiles if (m_MLNextShout > DateTime.UtcNow || pm.Hidden || !pm.Alive) return; - int shoutRange = ShoutRange; - - if (!InRange(pm.Location, shoutRange) || InRange(oldLocation, shoutRange) || !CanSee(pm) || !InLOS(pm)) + if (!InRange(pm.Location, ShoutRange) || InRange(oldLocation, ShoutRange) || !CanSee(pm) || !InLOS(pm)) return; MLQuestContext context = MLQuestSystem.GetContext(pm); @@ -3314,16 +3306,7 @@ namespace Server.Mobiles public Spawner MySpawner => Spawner as Spawner; [CommandProperty(AccessLevel.GameMaster)] - public Mobile LastOwner - { - get - { - if (Owners == null || Owners.Count == 0) - return null; - - return Owners[Owners.Count - 1]; - } - } + public Mobile LastOwner => Owners?.Count > 0 ? Owners[^1] : null; [CommandProperty(AccessLevel.GameMaster)] public bool IsBonded @@ -3732,9 +3715,7 @@ namespace Server.Mobiles public virtual void AddPetFriend(Mobile m) { - if (Friends == null) - Friends = new List(); - + Friends ??= new List(); Friends.Add(m); } @@ -3865,28 +3846,13 @@ namespace Server.Mobiles typeof(Gold) }; - public virtual bool CheckFoodPreference(Item f) - { - if (CheckFoodPreference(f, FoodType.Eggs, m_Eggs)) - return true; - - if (CheckFoodPreference(f, FoodType.Fish, m_Fish)) - return true; - - if (CheckFoodPreference(f, FoodType.GrainsAndHay, m_GrainsAndHay)) - return true; - - if (CheckFoodPreference(f, FoodType.Meat, m_Meat)) - return true; - - if (CheckFoodPreference(f, FoodType.FruitsAndVegies, m_FruitsAndVegies)) - return true; - - if (CheckFoodPreference(f, FoodType.Gold, m_Gold)) - return true; - - return false; - } + public virtual bool CheckFoodPreference(Item f) => + CheckFoodPreference(f, FoodType.Eggs, m_Eggs) || + CheckFoodPreference(f, FoodType.Fish, m_Fish) || + CheckFoodPreference(f, FoodType.GrainsAndHay, m_GrainsAndHay) || + CheckFoodPreference(f, FoodType.Meat, m_Meat) || + CheckFoodPreference(f, FoodType.FruitsAndVegies, m_FruitsAndVegies) || + CheckFoodPreference(f, FoodType.Gold, m_Gold); public virtual bool CheckFoodPreference(Item fed, FoodType type, Type[] types) { @@ -3904,82 +3870,79 @@ namespace Server.Mobiles public virtual bool CheckFeed(Mobile from, Item dropped) { - if (!IsDeadPet && Controlled && (ControlMaster == from || IsPetFriend(from))) + if (IsDeadPet || !Controlled || ControlMaster != from && !IsPetFriend(from)) + return false; + + Item f = dropped; + + if (!CheckFoodPreference(f)) + return false; + + int amount = f.Amount; + + if (amount <= 0) + return false; + + int stamGain; + + if (f is Gold) + stamGain = amount - 50; + else + stamGain = amount * 15 - 50; + + if (stamGain > 0) + Stam += stamGain; + + if (Core.SE) { - Item f = dropped; + if (m_Loyalty < MaxLoyalty) + m_Loyalty = MaxLoyalty; + } + else + for (int i = 0; i < amount; ++i) + if (m_Loyalty < MaxLoyalty && 0.5 >= Utility.RandomDouble()) + m_Loyalty += 10; - if (CheckFoodPreference(f)) + /* if ( happier )*/ + // looks like in OSI pets say they are happier even if they are at maximum loyalty + SayTo(from, 502060); // Your pet looks happier. + + if (Body.IsAnimal) + Animate(3, 5, 1, true, false, 0); + else if (Body.IsMonster) + Animate(17, 5, 1, true, false, 0); + + if (IsBondable && !IsBonded) + { + Mobile master = m_ControlMaster; + + if (master != null && master == from) //So friends can't start the bonding process { - int amount = f.Amount; - - if (amount > 0) + if (MinTameSkill <= 29.1 || master.Skills.AnimalTaming.Base >= MinTameSkill || + OverrideBondingReqs() || + Core.ML && master.Skills.AnimalTaming.Value >= MinTameSkill) { - int stamGain; - - if (f is Gold) - stamGain = amount - 50; - else - stamGain = amount * 15 - 50; - - if (stamGain > 0) - Stam += stamGain; - - if (Core.SE) + if (BondingBegin == DateTime.MinValue) { - if (m_Loyalty < MaxLoyalty) m_Loyalty = MaxLoyalty; + BondingBegin = DateTime.UtcNow; } - else + else if (BondingBegin + BondingDelay <= DateTime.UtcNow) { - for (int i = 0; i < amount; ++i) - if (m_Loyalty < MaxLoyalty && 0.5 >= Utility.RandomDouble()) - m_Loyalty += 10; + IsBonded = true; + BondingBegin = DateTime.MinValue; + from.SendLocalizedMessage(1049666); // Your pet has bonded with you! } - - /* if ( happier )*/ - // looks like in OSI pets say they are happier even if they are at maximum loyalty - SayTo(from, 502060); // Your pet looks happier. - - if (Body.IsAnimal) - Animate(3, 5, 1, true, false, 0); - else if (Body.IsMonster) - Animate(17, 5, 1, true, false, 0); - - if (IsBondable && !IsBonded) - { - Mobile master = m_ControlMaster; - - if (master != null && master == from) //So friends can't start the bonding process - { - if (MinTameSkill <= 29.1 || master.Skills.AnimalTaming.Base >= MinTameSkill || - OverrideBondingReqs() || - Core.ML && master.Skills.AnimalTaming.Value >= MinTameSkill) - { - if (BondingBegin == DateTime.MinValue) - { - BondingBegin = DateTime.UtcNow; - } - else if (BondingBegin + BondingDelay <= DateTime.UtcNow) - { - IsBonded = true; - BondingBegin = DateTime.MinValue; - from.SendLocalizedMessage(1049666); // Your pet has bonded with you! - } - } - else if (Core.ML) - { - from.SendLocalizedMessage( - 1075268); // Your pet cannot form a bond with you until your animal taming ability has risen. - } - } - } - - dropped.Delete(); - return true; + } + else if (Core.ML) + { + from.SendLocalizedMessage( + 1075268); // Your pet cannot form a bond with you until your animal taming ability has risen. } } } - return false; + dropped.Delete(); + return true; } #endregion @@ -4032,23 +3995,10 @@ namespace Server.Mobiles public virtual bool CanTeach => false; - public virtual bool CheckTeach(SkillName skill, Mobile from) - { - if (!CanTeach) - return false; - - if (skill == SkillName.Stealth && from.Skills.Hiding.Base < Stealth.HidingRequirement) - return false; - - if (skill == SkillName.RemoveTrap && (from.Skills.Lockpicking.Base < 50.0 || - from.Skills.DetectHidden.Base < 50.0)) - return false; - - if (!Core.AOS && (skill == SkillName.Focus || skill == SkillName.Chivalry || skill == SkillName.Necromancy)) - return false; - - return true; - } + public virtual bool CheckTeach(SkillName skill, Mobile from) => + CanTeach && (skill != SkillName.Stealth || !(from.Skills.Hiding.Base < Stealth.HidingRequirement)) && + (skill != SkillName.RemoveTrap || !(from.Skills.Lockpicking.Base < 50.0) && !(from.Skills.DetectHidden.Base < 50.0)) && + (Core.AOS || skill != SkillName.Focus && skill != SkillName.Chivalry && skill != SkillName.Necromancy); public enum TeachResult { @@ -4158,16 +4108,8 @@ namespace Server.Mobiles return TeachResult.Success; } - public virtual bool CheckTeachingMatch(Mobile m) - { - if (m_Teaching == (SkillName)(-1)) - return false; - - if (m is PlayerMobile mobile) - return mobile.Learning == m_Teaching; - - return true; - } + public virtual bool CheckTeachingMatch(Mobile m) => + m_Teaching != (SkillName)(-1) && (!(m is PlayerMobile mobile) || mobile.Learning == m_Teaching); private SkillName m_Teaching = (SkillName)(-1); @@ -5112,9 +5054,7 @@ namespace Server.Mobiles if (c.Loyalty <= 0) lock (toRelease) - { toRelease.Add(c); - } } } @@ -5122,18 +5062,12 @@ namespace Server.Mobiles if (!c.Controlled && !c.IsStabled && (c.Region.IsPartOf() && c.CanBeDamaged() || c.RemoveIfUntamed && c.Spawner == null)) { - c.RemoveStep++; - - if (c.RemoveStep >= 20) + if (c.RemoveStep++ >= 20) lock (toRemove) - { toRemove.Add(c); - } } else - { c.RemoveStep = 0; - } }); // TODO: Parallelize this diff --git a/Projects/Scripts/Mobiles/Familiars/HordeMinion.cs b/Projects/Scripts/Mobiles/Familiars/HordeMinion.cs index 8012f81be..fb2205a74 100644 --- a/Projects/Scripts/Mobiles/Familiars/HordeMinion.cs +++ b/Projects/Scripts/Mobiles/Familiars/HordeMinion.cs @@ -73,11 +73,11 @@ namespace Server.Mobiles if (pack == null) return; - IEnumerable eable = GetItemsInRange(2).Where(item => item.Movable && item.Stackable); + IPooledEnumerable eable = GetItemsInRange(2); int pickedUp = 0; - foreach (Item item in eable) + foreach (Item item in eable.Where(item => item.Movable && item.Stackable)) { if (!pack.CheckHold(this, item, false, true)) return; @@ -94,6 +94,8 @@ namespace Server.Mobiles if (++pickedUp == 3) break; } + + eable.Free(); } private void ConfirmRelease_Callback(Mobile from, bool okay) diff --git a/Projects/Scripts/Mobiles/Guards/ArcherGuard.cs b/Projects/Scripts/Mobiles/Guards/ArcherGuard.cs index 6560b2652..ac3f11045 100644 --- a/Projects/Scripts/Mobiles/Guards/ArcherGuard.cs +++ b/Projects/Scripts/Mobiles/Guards/ArcherGuard.cs @@ -261,7 +261,7 @@ namespace Server.Mobiles { // TeleportTo(target); - target.BoltEffect(0); + target.BoltEffect(); if (target is BaseCreature creature) creature.NoKillAwards = true; diff --git a/Projects/Scripts/Mobiles/Guards/BaseGuard.cs b/Projects/Scripts/Mobiles/Guards/BaseGuard.cs index 187318cd8..5d8a5c59e 100644 --- a/Projects/Scripts/Mobiles/Guards/BaseGuard.cs +++ b/Projects/Scripts/Mobiles/Guards/BaseGuard.cs @@ -27,7 +27,9 @@ namespace Server.Mobiles if (target?.Deleted != false) return; - foreach (Mobile m in target.GetMobilesInRange(15)) + IPooledEnumerable eable = target.GetMobilesInRange(15); + + foreach (Mobile m in eable) if (m is BaseGuard g) { if (g.Focus == null) // idling @@ -42,6 +44,8 @@ namespace Server.Mobiles } } + eable.Free(); + while (amount-- > 0) caller.Region.MakeGuard(target); } @@ -72,4 +76,4 @@ namespace Server.Mobiles int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/Guards/WarriorGuard.cs b/Projects/Scripts/Mobiles/Guards/WarriorGuard.cs index 1cad91a09..909a8dd27 100644 --- a/Projects/Scripts/Mobiles/Guards/WarriorGuard.cs +++ b/Projects/Scripts/Mobiles/Guards/WarriorGuard.cs @@ -292,7 +292,7 @@ namespace Server.Mobiles { // TeleportTo(target); - target.BoltEffect(0); + target.BoltEffect(); if (target is BaseCreature creature) creature.NoKillAwards = true; diff --git a/Projects/Scripts/Mobiles/Monsters/Humanoid/Magic/SavageShaman.cs b/Projects/Scripts/Mobiles/Monsters/Humanoid/Magic/SavageShaman.cs index 63bf68194..c2df17252 100644 --- a/Projects/Scripts/Mobiles/Monsters/Humanoid/Magic/SavageShaman.cs +++ b/Projects/Scripts/Mobiles/Monsters/Humanoid/Magic/SavageShaman.cs @@ -151,7 +151,7 @@ namespace Server.Mobiles return; IPooledEnumerable eable = GetMobilesInRange(8); - + switch (Utility.Random(3)) { case 0: /* greater heal */ @@ -208,7 +208,7 @@ namespace Server.Mobiles damage = Utility.Random(12, 9); } - m.BoltEffect(0); + m.BoltEffect(); SpellHelper.Damage(TimeSpan.FromSeconds(0.25), m, this, damage, 0, 0, 0, 0, 100); } @@ -260,7 +260,7 @@ namespace Server.Mobiles break; } } - + eable.Free(); } @@ -276,4 +276,4 @@ namespace Server.Mobiles int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunRevenant.cs b/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunRevenant.cs index 5bb6064aa..b56c8a0a5 100644 --- a/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunRevenant.cs +++ b/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunRevenant.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Server.Items; namespace Server.Mobiles @@ -79,13 +80,9 @@ namespace Server.Mobiles if (lastKiller is BaseCreature creature) lastKiller = creature.GetMaster(); - if (IsInsideKhaldun(m) && IsInsideKhaldun(lastKiller) && lastKiller.Player && !m_Set.Contains(lastKiller)) - foreach (AggressorInfo ai in m.Aggressors) - if (ai.Attacker == lastKiller && ai.CanReportMurder) - { - SummonRevenant(m, lastKiller); - break; - } + if (IsInsideKhaldun(m) && IsInsideKhaldun(lastKiller) && lastKiller.Player && + !m_Set.Contains(lastKiller) && m.Aggressors.Any(ai => ai.Attacker == lastKiller && ai.CanReportMurder)) + SummonRevenant(m, lastKiller); } public static void SummonRevenant(Mobile victim, Mobile killer) diff --git a/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunSummoner.cs b/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunSummoner.cs index 5eceebcba..7829cb1ae 100644 --- a/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunSummoner.cs +++ b/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunSummoner.cs @@ -104,7 +104,7 @@ namespace Server.Mobiles } Effects.PlaySound(this, Map, GetDeathSound()); - Effects.SendLocationEffect(Location, Map, 0x3709, 30, 10, 0x835, 0); + Effects.SendLocationEffect(Location, Map, 0x3709, 30, 10, 0x835); rm.MoveToWorld(Location, Map); Delete(); diff --git a/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunZealot.cs b/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunZealot.cs index b01f3900e..733d9df4f 100644 --- a/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunZealot.cs +++ b/Projects/Scripts/Mobiles/Monsters/Humanoid/Melee/KhaldunZealot.cs @@ -113,7 +113,7 @@ namespace Server.Mobiles } Effects.PlaySound(this, Map, GetDeathSound()); - Effects.SendLocationEffect(Location, Map, 0x3709, 30, 10, 0x835, 0); + Effects.SendLocationEffect(Location, Map, 0x3709, 30, 10, 0x835); rm.MoveToWorld(Location, Map); Delete(); diff --git a/Projects/Scripts/Mobiles/Monsters/ML/Special/Ilhenir.cs b/Projects/Scripts/Mobiles/Monsters/ML/Special/Ilhenir.cs index 0d05094af..ede677bb7 100644 --- a/Projects/Scripts/Mobiles/Monsters/ML/Special/Ilhenir.cs +++ b/Projects/Scripts/Mobiles/Monsters/ML/Special/Ilhenir.cs @@ -217,7 +217,7 @@ namespace Server.Mobiles { if (to.Alive && to.Player && !UnderCacophonicAttack(to)) { - to.Send(SpeedControl.WalkSpeed); + Packets.SendSpeedControlWalk(to.NetState); to.SendLocalizedMessage(1072069); // A cacophonic sound lambastes you, suppressing your ability to move. to.PlaySound(0x584); @@ -229,7 +229,7 @@ namespace Server.Mobiles public virtual void CacophonicEnd(Mobile from) { m_Table.Remove(from); - from.Send(SpeedControl.Disable); + Packets.SendSpeedControlDisabled(from.NetState); } public static bool UnderCacophonicAttack(Mobile from) => m_Table.Contains(from); diff --git a/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueBeastLord.cs b/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueBeastLord.cs index 848713e48..d64a16c67 100644 --- a/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueBeastLord.cs +++ b/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueBeastLord.cs @@ -76,8 +76,7 @@ namespace Server.Mobiles { OpenedBy = from; - if (m_Timer == null) - m_Timer = new DecayTimer(this); + m_Timer ??= new DecayTimer(this); if (!m_Timer.Running) m_Timer.Start(); diff --git a/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueSpawn.cs b/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueSpawn.cs index 40eeebf38..e479247af 100644 --- a/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueSpawn.cs +++ b/Projects/Scripts/Mobiles/Monsters/Misc/Melee/PlagueSpawn.cs @@ -35,8 +35,7 @@ namespace Server.Mobiles Body = 0x15; BaseSoundID = 0xDB; break; - default: - case 5: // slime + default: // slime Body = 51; BaseSoundID = 456; break; diff --git a/Projects/Scripts/Mobiles/Monsters/SE/DeathWatchBeetle.cs b/Projects/Scripts/Mobiles/Monsters/SE/DeathWatchBeetle.cs index 72b4bb73e..a3b7a0179 100644 --- a/Projects/Scripts/Mobiles/Monsters/SE/DeathWatchBeetle.cs +++ b/Projects/Scripts/Mobiles/Monsters/SE/DeathWatchBeetle.cs @@ -98,7 +98,7 @@ namespace Server.Mobiles { if (Utility.RandomBool() && Mana > 14 && to != null) { - damage = damage + damage / 2; + damage += damage / 2; to.SendLocalizedMessage(1060091); // You take extra damage from the crushing attack! to.PlaySound(0x1E1); to.FixedParticles(0x377A, 1, 32, 0x26da, 0, 0, 0); diff --git a/Projects/Scripts/Mobiles/Monsters/SE/FanDancer.cs b/Projects/Scripts/Mobiles/Monsters/SE/FanDancer.cs index 998623e31..31ce55213 100644 --- a/Projects/Scripts/Mobiles/Monsters/SE/FanDancer.cs +++ b/Projects/Scripts/Mobiles/Monsters/SE/FanDancer.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using Server.Engines.Plants; using Server.Items; -using Server.Network; namespace Server.Mobiles { @@ -85,9 +84,7 @@ namespace Server.Mobiles * Effect: - To: "0x57D4F5B" - ItemId: "0x27A3" - ItemIdName: "Tessen" - FromLocation: "(992 299, 24)" - ToLocation: "(992 308, 22)" - Speed: "10" - Duration: "0" - FixedDirection: "False" - Explode: "False" - Hue: "0x0" - Render: "0x0" * Damage: 50-65 */ - Effects.SendPacket(attacker, attacker.Map, - new HuedEffect(EffectType.Moving, Serial.Zero, Serial.Zero, 0x27A3, Location, attacker.Location, 10, 0, - false, false, 0, 0)); + Effects.SendMovingEffect(Location, attacker.Location, attacker.Map, 0x27A3, 10); AOS.Damage(attacker, this, Utility.RandomMinMax(50, 65), 100, 0, 0, 0, 0); } } @@ -102,9 +99,7 @@ namespace Server.Mobiles * Effect: - To: "0x57D4F5B" - ItemId: "0x27A3" - ItemIdName: "Tessen" - FromLocation: "(992 299, 24)" - ToLocation: "(992 308, 22)" - Speed: "10" - Duration: "0" - FixedDirection: "False" - Explode: "False" - Hue: "0x0" - Render: "0x0" * Damage: 50-65 */ - Effects.SendPacket(attacker, attacker.Map, - new HuedEffect(EffectType.Moving, Serial.Zero, Serial.Zero, 0x27A3, Location, attacker.Location, 10, 0, - false, false, 0, 0)); + Effects.SendMovingEffect(Location, attacker.Location, attacker.Map, 0x27A3, 10); AOS.Damage(attacker, this, Utility.RandomMinMax(50, 65), 100, 0, 0, 0, 0); } } diff --git a/Projects/Scripts/Mobiles/PlayerMobile.cs b/Projects/Scripts/Mobiles/PlayerMobile.cs index b38ba71bb..0e02156ee 100644 --- a/Projects/Scripts/Mobiles/PlayerMobile.cs +++ b/Projects/Scripts/Mobiles/PlayerMobile.cs @@ -18,7 +18,6 @@ using Server.Guilds; using Server.Gumps; using Server.Items; using Server.Misc; -using Server.Movement; using Server.Multis; using Server.Network; using Server.Regions; @@ -204,16 +203,7 @@ namespace Server.Mobiles SkillName.TasteID }; - public override double RacialSkillBonus - { - get - { - if (Core.ML && Race == Race.Human) - return 20.0; - - return 0; - } - } + public override double RacialSkillBonus => Core.ML && Race == Race.Human ? 20.0 : 0; public List EquipSnapshot{ get; private set; } @@ -302,15 +292,7 @@ namespace Server.Mobiles public DateTime SessionStart{ get; private set; } [CommandProperty(AccessLevel.GameMaster)] - public TimeSpan GameTime - { - get - { - if (NetState != null) - return m_GameTime + (DateTime.UtcNow - SessionStart); - return m_GameTime; - } - } + public TimeSpan GameTime => NetState != null ? m_GameTime + (DateTime.UtcNow - SessionStart) : m_GameTime; public override bool NewGuildDisplay => Guilds.Guild.NewGuildSystem; @@ -365,13 +347,9 @@ namespace Server.Mobiles BlockMountType type = MountBlockReason; if (!Alive) - { SendLocalizedMessage(1113082); // You may not fly while dead. - } else if (IsBodyMod && !(BodyMod == 666 || BodyMod == 667)) - { SendLocalizedMessage(1112453); // You can't fly in your current form! - } else if (type != BlockMountType.None) { switch (type) @@ -548,10 +526,9 @@ namespace Server.Mobiles private static void CheckPets() { foreach (Mobile m in World.Mobiles.Values) - if (m is PlayerMobile pm) - if ((!pm.Mounted || pm.Mount is EtherealMount) && pm.AllFollowers.Count > pm.AutoStabled.Count || - pm.Mounted && pm.AllFollowers.Count > pm.AutoStabled.Count + 1) - pm.AutoStablePets(); /* autostable checks summons, et al: no need here */ + if (m is PlayerMobile pm && ((!pm.Mounted || pm.Mount is EtherealMount) && pm.AllFollowers.Count > pm.AutoStabled.Count || + pm.Mounted && pm.AllFollowers.Count > pm.AutoStabled.Count + 1)) + pm.AutoStablePets(); /* autostable checks summons, et al: no need here */ } private static bool CheckBlock(MountBlock block) => block?.m_Timer.Running == true; @@ -632,8 +609,8 @@ namespace Server.Mobiles m_LastGlobalLight = global; m_LastPersonalLight = personal; - ns.Send(GlobalLightLevel.Instantiate(global)); - ns.Send(new PersonalLightLevel(this, personal)); + Packets.SendGlobalLightLevel(ns, (sbyte)global); + Packets.SendPersonalLightLevel(ns, Serial, (sbyte)personal); } public override int GetMinResistance(ResistanceType type) @@ -677,23 +654,17 @@ namespace Server.Mobiles if (!(from.Account is Account acct) || !acct.HasAccess(from.NetState)) { - if (from.AccessLevel == AccessLevel.Player) - notice = "The server is currently under lockdown. No players are allowed to log in at this time."; - else - notice = - "The server is currently under lockdown. You do not have sufficient access level to connect."; + notice = from.AccessLevel == AccessLevel.Player ? + "The server is currently under lockdown. No players are allowed to log in at this time." : + "The server is currently under lockdown. You do not have sufficient access level to connect."; - Timer.DelayCall(TimeSpan.FromSeconds(1.0), () => from.NetState?.Dispose()); + Timer.DelayCall(TimeSpan.FromSeconds(1.0), ns => ns?.Dispose(), from.NetState); } else if (from.AccessLevel >= AccessLevel.Administrator) - { notice = "The server is currently under lockdown. As you are an administrator, you may change this from the [Admin gump."; - } else - { notice = "The server is currently under lockdown. You have sufficient access level to connect."; - } from.SendGump(new NoticeGump(1060637, 30720, notice, 0xFFC000, 300, 140)); return; @@ -1050,13 +1021,9 @@ namespace Server.Mobiles return base.CanBeHarmful(target, message, ignoreOurBlessedness); } - public override bool CanBeBeneficial(Mobile target, bool message, bool allowDead) - { - if (DesignContext != null || target is PlayerMobile mobile && mobile.DesignContext != null) - return false; - - return base.CanBeBeneficial(target, message, allowDead); - } + public override bool CanBeBeneficial(Mobile target, bool message, bool allowDead) => + DesignContext == null && (!(target is PlayerMobile mobile) || mobile.DesignContext == null) && + base.CanBeBeneficial(target, message, allowDead); public override bool CheckContextMenuDisplay(IEntity target) => DesignContext == null; @@ -1116,12 +1083,10 @@ namespace Server.Mobiles int speed = ComputeMovementSpeed(d); - bool res; - if (!Alive) MovementImpl.IgnoreMovableImpassables = true; - res = base.Move(d); + bool res = base.Move(d); MovementImpl.IgnoreMovableImpassables = false; @@ -1145,7 +1110,7 @@ namespace Server.Mobiles newZ = foundation.Z + HouseFoundation.GetLevelZ(context.Level, context.Foundation); int newX = X, newY = Y; - Movement.Movement.Offset(d, ref newX, ref newY); + Movement.Offset(d, ref newX, ref newY); int startX = foundation.X + foundation.Components.Min.X + 1; int startY = foundation.Y + foundation.Components.Min.Y + 1; @@ -1882,7 +1847,7 @@ namespace Server.Mobiles pointsToGain += (int)Math.Sqrt(GameTime.TotalSeconds * 4); pointsToGain *= 5; - pointsToGain += (int)Math.Pow(Skills.Total / 250, 2); + pointsToGain += (int)Math.Pow(Skills.Total / 250.0, 2); if (VirtueHelper.Award(m, VirtueName.Justice, pointsToGain, ref gainedPath)) { @@ -1894,7 +1859,7 @@ namespace Server.Mobiles m.FixedParticles(0x375A, 9, 20, 5027, EffectLayer.Waist); m.PlaySound(0x1F7); - m_NextJustAward = DateTime.UtcNow + TimeSpan.FromMinutes(pointsToGain / 3); + m_NextJustAward = DateTime.UtcNow + TimeSpan.FromMinutes(pointsToGain / 3.0); } } } @@ -1931,16 +1896,8 @@ namespace Server.Mobiles #endregion if (m_BuffTable != null) - { - List list = new List(); - - foreach (BuffInfo buff in m_BuffTable.Values) - if (!buff.RetainThroughDeath) - list.Add(buff); - - for (int i = 0; i < list.Count; i++) - RemoveBuff(list[i]); - } + foreach(var buff in m_BuffTable.Values.Where(buff => !buff.RetainThroughDeath)) + RemoveBuff(buff); } public override bool MutateSpeech(List hears, ref string text, ref object context) @@ -1951,14 +1908,8 @@ namespace Server.Mobiles if (Core.ML && Skills.SpiritSpeak.Value >= 100.0) return false; - if (Core.AOS) - for (int i = 0; i < hears.Count; ++i) - { - Mobile m = hears[i]; - - if (m != this && m.Skills.SpiritSpeak.Value >= 100.0) - return false; - } + if (Core.AOS && hears.Any(m => m != this && m.Skills.SpiritSpeak.Value >= 100.0)) + return false; return base.MutateSpeech(hears, ref text, ref context); } @@ -1968,65 +1919,48 @@ namespace Server.Mobiles if (Guilds.Guild.NewGuildSystem && (type == MessageType.Guild || type == MessageType.Alliance)) { if (!(Guild is Guild g)) - { SendLocalizedMessage(1063142); // You are not in a guild! - } else if (type == MessageType.Alliance) { if (g.Alliance?.IsMember(g) == true) { //g.Alliance.AllianceTextMessage( hue, "[Alliance][{0}]: {1}", this.Name, text ); g.Alliance.AllianceChat(this, text); - SendToStaffMessage(this, "[Alliance]: {0}", text); + SendToStaffMessage(this, $"[Alliance]: {text}"); AllianceMessageHue = hue; } else - { SendLocalizedMessage(1071020); // You are not in an alliance! - } } else //Type == MessageType.Guild { GuildMessageHue = hue; g.GuildChat(this, text); - SendToStaffMessage(this, "[Guild]: {0}", text); + SendToStaffMessage(this, $"[Guild]: {text}"); } } else - { base.DoSpeech(text, keywords, type, hue); - } } private static void SendToStaffMessage(Mobile from, string text) { - Packet p = null; - - foreach (NetState ns in from.GetClientsInRange(8)) + IPooledEnumerable eable = from.GetClientsInRange(8); + foreach (NetState ns in eable) { Mobile mob = ns.Mobile; if (mob?.AccessLevel >= AccessLevel.GameMaster && mob.AccessLevel > from.AccessLevel) - { - if (p == null) - p = Packet.Acquire(new UnicodeMessage(from.Serial, from.Body, MessageType.Regular, from.SpeechHue, 3, - from.Language, from.Name, text)); - - ns.Send(p); - } + Packets.SendUnicodeMessage(ns, from.Serial, from.Body, MessageType.Regular, from.SpeechHue, 3, + from.Language, from.Name, text); } - Packet.Release(p); + eable.Free(); } - private static void SendToStaffMessage(Mobile from, string format, params object[] args) - { - SendToStaffMessage(from, string.Format(format, args)); - } - - public override void Damage(int amount, Mobile from) + public override void Damage(int amount, Mobile from = null, bool informMount = true) { if (EvilOmenSpell.TryEndEffect(this)) amount = (int)(amount * 1.25); @@ -2049,16 +1983,15 @@ namespace Server.Mobiles from.Damage(amount, this); } - if (from != null && Talisman is BaseTalisman talisman) - if (talisman.Protection != null && talisman.Protection.Type != null) - { - Type type = talisman.Protection.Type; + if (from != null && Talisman is BaseTalisman talisman && talisman.Protection != null && talisman.Protection.Type != null) + { + Type type = talisman.Protection.Type; - if (type.IsInstanceOfType(from)) - amount = (int)(amount * (1 - (double)talisman.Protection.Amount / 100)); - } + if (type.IsInstanceOfType(from)) + amount = (int)(amount * (1 - (double)talisman.Protection.Amount / 100)); + } - base.Damage(amount, from); + base.Damage(amount, from, informMount); } public override bool IsHarmfulCriminal(Mobile target) @@ -2358,32 +2291,23 @@ namespace Server.Mobiles } } - if (RecentlyReported == null) - RecentlyReported = new List(); + RecentlyReported ??= new List(); // Professions weren't verified on 1.0 RC0 if (!CharacterCreation.VerifyProfession(Profession)) Profession = 0; - if (PermaFlags == null) - PermaFlags = new List(); + PermaFlags ??= new List(); + JusticeProtectors ??= new List(); + BOBFilter ??= new BOBFilter(); - if (JusticeProtectors == null) - JusticeProtectors = new List(); - - if (BOBFilter == null) - BOBFilter = new BOBFilter(); - - if (m_GuildRank == null) - m_GuildRank = - RankDefinition - .Member; //Default to member if going from older version to new version (only time it should be null) + //Default to member if going from older version to new version (only time it should be null) + m_GuildRank ??= RankDefinition.Member; if (LastOnline == DateTime.MinValue && Account != null) LastOnline = ((Account)Account).LastLogin; - if (ChampionTitles == null) - ChampionTitles = new ChampionTitleInfo(); + ChampionTitles ??= new ChampionTitleInfo(); if (AccessLevel > AccessLevel.Player) m_IgnoreMobiles = true; @@ -2797,9 +2721,10 @@ namespace Server.Mobiles for (int i = AutoStabled.Count - 1; i >= 0; --i) { - BaseCreature pet = AutoStabled[i] as BaseCreature; + if (!(AutoStabled[i] is BaseCreature pet)) + return; - if (pet?.Deleted == true) + if (pet.Deleted) { pet.IsStabled = false; pet.StabledBy = null; @@ -2831,10 +2756,8 @@ namespace Server.Mobiles Stabled.Remove(pet); } else - { SendLocalizedMessage(1049612, pet.Name); // ~1_NAME~ remained in the stables because you have too many followers. - } } AutoStabled.Clear(); @@ -2902,7 +2825,7 @@ namespace Server.Mobiles public bool NinjaWepCooldown{ get; set; } - public List AllFollowers => m_AllFollowers ?? (m_AllFollowers = new List()); + public List AllFollowers => m_AllFollowers ??= new List(); public RankDefinition GuildRank { @@ -3083,14 +3006,14 @@ namespace Server.Mobiles if (!Core.SE || !Alive) return; - foreach (KeyValuePair kvp in RecoverableAmmo) - if (kvp.Value > 0) + foreach (var (key, value) in RecoverableAmmo) + if (value > 0) { Item ammo = null; try { - ammo = Activator.CreateInstance(kvp.Key) as Item; + ammo = Activator.CreateInstance(key) as Item; } catch { @@ -3100,7 +3023,7 @@ namespace Server.Mobiles if (ammo == null) continue; string name = ammo.Name; - ammo.Amount = kvp.Value; + ammo.Amount = value; if (name == null) { @@ -3180,39 +3103,21 @@ namespace Server.Mobiles [CommandProperty(AccessLevel.GameMaster)] public override int Str { - get - { - if (Core.ML && AccessLevel == AccessLevel.Player) - return Math.Min(base.Str, 150); - - return base.Str; - } + get => Core.ML && AccessLevel == AccessLevel.Player ? Math.Min(base.Str, 150) : base.Str; set => base.Str = value; } [CommandProperty(AccessLevel.GameMaster)] public override int Int { - get - { - if (Core.ML && AccessLevel == AccessLevel.Player) - return Math.Min(base.Int, 150); - - return base.Int; - } + get => Core.ML && AccessLevel == AccessLevel.Player ? Math.Min(base.Int, 150) : base.Int; set => base.Int = value; } [CommandProperty(AccessLevel.GameMaster)] public override int Dex { - get - { - if (Core.ML && AccessLevel == AccessLevel.Player) - return Math.Min(base.Dex, 150); - - return base.Dex; - } + get => Core.ML && AccessLevel == AccessLevel.Player ? Math.Min(base.Dex, 150) : base.Dex; set => base.Dex = value; } @@ -3231,36 +3136,16 @@ namespace Server.Mobiles SendLocalizedMessage(1060868); // Target the item you wish to toggle insurance status on to cancel } - private bool CanInsure(Item item) - { - if (item is Container && !(item is BaseQuiver) || item is BagOfSending || item is KeyRing || item is PotionKeg || - item is Sigil) - return false; - - if (item.Stackable) - return false; - - if (item.LootType == LootType.Cursed) - return false; - - if (item.ItemID == 0x204E) // death shroud - return false; - - if (item.Layer == Layer.Mount) - return false; - - if (item.LootType == LootType.Blessed || item.LootType == LootType.Newbied || item.BlessedFor == this) - return false; - - return true; - } + private bool CanInsure(Item item) => + (!(item is Container) || item is BaseQuiver) && !(item is BagOfSending) && !(item is KeyRing) && + !(item is PotionKeg) && !(item is Sigil) && !item.Stackable && item.LootType != LootType.Cursed && + item.ItemID != 0x204E && item.Layer != Layer.Mount && item.LootType != LootType.Blessed && + item.LootType != LootType.Newbied && item.BlessedFor != this; private void ToggleItemInsurance_Callback(Mobile from, object obj) { - if (!CheckAlive()) - return; - - ToggleItemInsurance_Callback(from, obj as Item, true); + if (CheckAlive()) + ToggleItemInsurance_Callback(from, obj as Item, true); } private void ToggleItemInsurance_Callback(Mobile from, Item item, bool target) @@ -3390,9 +3275,7 @@ namespace Server.Mobiles m_Player.AutoRenewInsurance = false; } else - { m_Player.SendLocalizedMessage(1042021); // Cancelled. - } if (m_InsuranceGump != null) m_Player.SendGump(m_InsuranceGump.NewInstance()); @@ -3404,11 +3287,7 @@ namespace Server.Mobiles if (!CheckAlive()) return; - List items = new List(); - - foreach (Item item in Items) - if (DisplayInItemInsuranceGump(item)) - items.Add(item); + List items = Items.Where(DisplayInItemInsuranceGump).ToList(); Container pack = Backpack; @@ -3479,11 +3358,7 @@ namespace Server.Mobiles AddHtmlLocalized(400, 54, 70, 20, 1114311, 0x7FFF); // Insured int balance = Banker.GetBalance(from); - int cost = 0; - - for (int i = 0; i < items.Length; ++i) - if (insure[i]) - cost += GetInsuranceCost(items[i]); + int cost = items.Where((t, i) => insure[i]).Sum(GetInsuranceCost); AddHtmlLocalized(15, 420, 300, 20, 1114310, 0x7FFF); // GOLD AVAILABLE: AddLabel(215, 420, 0x481, balance.ToString()); @@ -3702,20 +3577,12 @@ namespace Server.Mobiles private DateTime[] m_StuckMenuUses; - public bool CanUseStuckMenu() - { - if (m_StuckMenuUses == null) return true; - - for (int i = 0; i < m_StuckMenuUses.Length; ++i) - if (DateTime.UtcNow - m_StuckMenuUses[i] > TimeSpan.FromDays(1.0)) - return true; - - return false; - } + public bool CanUseStuckMenu() => + m_StuckMenuUses?.Any(t => DateTime.UtcNow - t > TimeSpan.FromDays(1.0)) != false; public void UsedStuckMenu() { - if (m_StuckMenuUses == null) m_StuckMenuUses = new DateTime[2]; + m_StuckMenuUses ??= new DateTime[2]; for (int i = 0; i < m_StuckMenuUses.Length; ++i) if (DateTime.UtcNow - m_StuckMenuUses[i] > TimeSpan.FromDays(1.0)) @@ -3779,10 +3646,7 @@ namespace Server.Mobiles m_DuelPlayer = value; - if (m_DuelPlayer == null) - DuelContext = null; - else - DuelContext = m_DuelPlayer.Participant.Context; + DuelContext = m_DuelPlayer?.Participant.Context; bool isInTourney = DuelContext?.Finished == false && DuelContext.m_Tournament != null; @@ -3945,22 +3809,14 @@ namespace Server.Mobiles private void DeltaEnemies(Type oldType, Type newType) { + NetState ns = NetState; + foreach (Mobile m in GetMobilesInRange(18)) { Type t = m.GetType(); if (t == oldType || t == newType) - { - NetState ns = NetState; - - if (ns != null) - { - if (ns.StygianAbyss) - ns.Send(new MobileMoving(m, Notoriety.Compute(this, m))); - else - ns.Send(new MobileMovingOld(m, Notoriety.Compute(this, m))); - } - } + Packets.SendMobileMoving(NetState, m, Notoriety.Compute(this, m)); } } @@ -4120,13 +3976,8 @@ namespace Server.Mobiles return base.ApplyNameSuffix(suffix); } - public override TimeSpan GetLogoutDelay() - { - if (Young || BedrollLogout || TestCenter.Enabled) - return TimeSpan.Zero; - - return base.GetLogoutDelay(); - } + public override TimeSpan GetLogoutDelay() => + Young || BedrollLogout || TestCenter.Enabled ? TimeSpan.Zero : base.GetLogoutDelay(); private DateTime m_LastYoungMessage = DateTime.MinValue; @@ -4167,7 +4018,7 @@ namespace Server.Mobiles return false; } - private static Point3D[] m_TrammelDeathDestinations = + private static readonly Point3D[] m_TrammelDeathDestinations = { new Point3D(1481, 1612, 20), new Point3D(2708, 2153, 0), @@ -4186,7 +4037,7 @@ namespace Server.Mobiles new Point3D(3665, 2587, 0) }; - private static Point3D[] m_IlshenarDeathDestinations = + private static readonly Point3D[] m_IlshenarDeathDestinations = { new Point3D(1216, 468, -13), new Point3D(723, 1367, -60), @@ -4199,13 +4050,13 @@ namespace Server.Mobiles new Point3D(1722, 219, 96) }; - private static Point3D[] m_MalasDeathDestinations = + private static readonly Point3D[] m_MalasDeathDestinations = { new Point3D(2079, 1376, -70), new Point3D(944, 519, -71) }; - private static Point3D[] m_TokunoDeathDestinations = + private static readonly Point3D[] m_TokunoDeathDestinations = { new Point3D(1166, 801, 27), new Point3D(782, 1228, 25), @@ -4285,9 +4136,7 @@ namespace Server.Mobiles { if (SpeechLog.Enabled && NetState != null) { - if (SpeechLog == null) - SpeechLog = new SpeechLog(); - + SpeechLog ??= new SpeechLog(); SpeechLog.Add(e.Mobile, e.Speech); } } @@ -4435,8 +4284,7 @@ namespace Server.Mobiles if (m_Values == null || index < 0 || index >= m_Values.Length) return 0; - if (m_Values[index] == null) - m_Values[index] = new TitleInfo(); + m_Values[index] ??= new TitleInfo(); return m_Values[index].Value; } @@ -4446,16 +4294,14 @@ namespace Server.Mobiles if (m_Values == null || index < 0 || index >= m_Values.Length) return DateTime.MinValue; - if (m_Values[index] == null) - m_Values[index] = new TitleInfo(); + m_Values[index] ??= new TitleInfo(); return m_Values[index].LastDecay; } public void SetValue(int index, int value) { - if (m_Values == null) - m_Values = new TitleInfo[ChampionSpawnInfo.Table.Length]; + m_Values ??= new TitleInfo[ChampionSpawnInfo.Table.Length]; if (value < 0) value = 0; @@ -4463,36 +4309,31 @@ namespace Server.Mobiles if (index < 0 || index >= m_Values.Length) return; - if (m_Values[index] == null) - m_Values[index] = new TitleInfo(); + m_Values[index] ??= new TitleInfo(); m_Values[index].Value = value; } public void Award(int index, int value) { - if (m_Values == null) - m_Values = new TitleInfo[ChampionSpawnInfo.Table.Length]; + m_Values ??= new TitleInfo[ChampionSpawnInfo.Table.Length]; if (index < 0 || index >= m_Values.Length || value <= 0) return; - if (m_Values[index] == null) - m_Values[index] = new TitleInfo(); + m_Values[index] ??= new TitleInfo(); m_Values[index].Value += value; } public void Atrophy(int index, int value) { - if (m_Values == null) - m_Values = new TitleInfo[ChampionSpawnInfo.Table.Length]; + m_Values ??= new TitleInfo[ChampionSpawnInfo.Table.Length]; if (index < 0 || index >= m_Values.Length || value <= 0) return; - if (m_Values[index] == null) - m_Values[index] = new TitleInfo(); + m_Values[index] ??= new TitleInfo(); int before = m_Values[index].Value; @@ -4518,9 +4359,7 @@ namespace Server.Mobiles for (int i = 0; i < length; i++) { - if (titles.m_Values[i] == null) - titles.m_Values[i] = new TitleInfo(); - + titles.m_Values[i] ??= new TitleInfo(); TitleInfo.Serialize(writer, titles.m_Values[i]); } } @@ -4531,8 +4370,7 @@ namespace Server.Mobiles if (t == null) return; - if (t.m_Values == null) - t.m_Values = new TitleInfo[ChampionSpawnInfo.Table.Length]; + t.m_Values ??= new TitleInfo[ChampionSpawnInfo.Table.Length]; for (int i = 0; i < t.m_Values.Length; i++) if (t.GetLastDecay(i) + LossDelay < DateTime.UtcNow) @@ -4546,16 +4384,8 @@ namespace Server.Mobiles if (t == null) return; - if (t.m_Values == null) - t.m_Values = new TitleInfo[ChampionSpawnInfo.Table.Length]; - - int count = 1; - - for (int i = 0; i < t.m_Values.Length; i++) - if (t.m_Values[i].Value > 900) - count++; - - t.Harrower = Math.Max(count, t.Harrower); //Harrower titles never decay. + t.m_Values ??= new TitleInfo[ChampionSpawnInfo.Table.Length]; + t.Harrower = Math.Max(1 + t.m_Values.Count(t1 => t1.Value > 900), t.Harrower); //Harrower titles never decay. } private class TitleInfo @@ -4611,9 +4441,7 @@ namespace Server.Mobiles public virtual void AcquireRecipe(int recipeID) { - if (m_AcquiredRecipes == null) - m_AcquiredRecipes = new Dictionary(); - + m_AcquiredRecipes ??= new Dictionary(); m_AcquiredRecipes[recipeID] = true; } @@ -4631,12 +4459,11 @@ namespace Server.Mobiles public void ResendBuffs() { - if (!BuffInfo.Enabled || m_BuffTable == null) + if (!BuffInfo.Enabled || m_BuffTable == null || NetState?.BuffIcon != true) return; - if (NetState?.BuffIcon == true) - foreach (BuffInfo info in m_BuffTable.Values) - NetState.Send(new AddBuffPacket(this, info)); + foreach (BuffInfo info in m_BuffTable.Values) + BuffPackets.SendAddBuff(this, info); } private Dictionary m_BuffTable; @@ -4654,7 +4481,7 @@ namespace Server.Mobiles m_BuffTable.Add(b.ID, b); if (NetState?.BuffIcon == true) - NetState.Send(new AddBuffPacket(this, b)); + BuffPackets.SendAddBuff(this, b); } public void RemoveBuff(BuffInfo b) @@ -4678,7 +4505,7 @@ namespace Server.Mobiles m_BuffTable.Remove(b); if (NetState?.BuffIcon == true) - NetState.Send(new RemoveBuffPacket(this, b)); + BuffPackets.SendRemoveBuffPacket(NetState, Serial, (int)b); if (m_BuffTable.Count <= 0) m_BuffTable = null; diff --git a/Projects/Scripts/Mobiles/Special/ChaosGuard.cs b/Projects/Scripts/Mobiles/Special/ChaosGuard.cs index a7ad50117..0c96e9297 100644 --- a/Projects/Scripts/Mobiles/Special/ChaosGuard.cs +++ b/Projects/Scripts/Mobiles/Special/ChaosGuard.cs @@ -1,4 +1,3 @@ -using Server.Guilds; using Server.Items; namespace Server.Mobiles diff --git a/Projects/Scripts/Mobiles/Special/Harrower.cs b/Projects/Scripts/Mobiles/Special/Harrower.cs index 59a0bf1a7..863ed402c 100644 --- a/Projects/Scripts/Mobiles/Special/Harrower.cs +++ b/Projects/Scripts/Mobiles/Special/Harrower.cs @@ -398,24 +398,24 @@ namespace Server.Mobiles Dictionary validEntries = new Dictionary(); - foreach (KeyValuePair kvp in m_DamageEntries) - if (IsEligible(kvp.Key, artifact)) + foreach (var (key, value) in m_DamageEntries) + if (IsEligible(key, artifact)) { - validEntries.Add(kvp.Key, kvp.Value); - totalDamage += kvp.Value; + validEntries.Add(key, value); + totalDamage += value; } int randomDamage = Utility.RandomMinMax(1, totalDamage); totalDamage = 0; - foreach (KeyValuePair kvp in validEntries) + foreach (var (key, value) in validEntries) { - totalDamage += kvp.Value; + totalDamage += value; if (totalDamage >= randomDamage) { - GiveArtifact(kvp.Key, artifact); + GiveArtifact(key, artifact); return; } } diff --git a/Projects/Scripts/Mobiles/Special/Mephitis.cs b/Projects/Scripts/Mobiles/Special/Mephitis.cs index 2c80b0802..13fb0d633 100644 --- a/Projects/Scripts/Mobiles/Special/Mephitis.cs +++ b/Projects/Scripts/Mobiles/Special/Mephitis.cs @@ -68,12 +68,7 @@ namespace Server.Mobiles AddLoot(LootPack.UltraRich, 4); } - public override void OnGotMeleeAttack(Mobile attacker) - { - base.OnGotMeleeAttack(attacker); - - // TODO: Web ability - } + // TODO: Web Ability public override void Serialize(GenericWriter writer) { @@ -89,4 +84,4 @@ namespace Server.Mobiles int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/Special/OrderGuard.cs b/Projects/Scripts/Mobiles/Special/OrderGuard.cs index e3db5a597..b46e23ce0 100644 --- a/Projects/Scripts/Mobiles/Special/OrderGuard.cs +++ b/Projects/Scripts/Mobiles/Special/OrderGuard.cs @@ -1,4 +1,3 @@ -using Server.Guilds; using Server.Items; namespace Server.Mobiles diff --git a/Projects/Scripts/Mobiles/Special/Semidar.cs b/Projects/Scripts/Mobiles/Special/Semidar.cs index 4f01a0747..c4f6dc568 100644 --- a/Projects/Scripts/Mobiles/Special/Semidar.cs +++ b/Projects/Scripts/Mobiles/Special/Semidar.cs @@ -71,8 +71,7 @@ namespace Server.Mobiles public override void CheckReflect(Mobile caster, ref bool reflect) { - if (caster.Body.IsMale) - reflect = true; // Always reflect if caster isn't female + reflect |= caster.Body.IsMale; // Always reflect if caster isn't female } public override void AlterDamageScalarFrom(Mobile caster, ref double scalar) diff --git a/Projects/Scripts/Mobiles/Townfolk/Banker.cs b/Projects/Scripts/Mobiles/Townfolk/Banker.cs index 1d7d3c6f8..84daa5cd0 100644 --- a/Projects/Scripts/Mobiles/Townfolk/Banker.cs +++ b/Projects/Scripts/Mobiles/Townfolk/Banker.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Server.Accounting; using Server.ContextMenus; using Server.Items; using Server.Network; @@ -284,22 +283,16 @@ namespace Server.Mobiles break; if (!Core.ML && amount > 5000 || Core.ML && amount > 60000) - { Say(500381); // Thou canst not withdraw so much at one time! - } else if (pack?.Deleted != false || !(pack.TotalWeight < pack.MaxWeight) || !(pack.TotalItems < pack.MaxItems)) - { Say(1048147); // Your backpack can't hold anything else. - } else if (amount > 0) { BankBox box = e.Mobile.FindBankNoCreate(); if (box == null || !Withdraw(e.Mobile, amount)) - { Say(500384); // Ah, art thou trying to fool me? Thou hast not so much gold! - } else { pack.DropItem(new Gold(amount)); @@ -365,13 +358,9 @@ namespace Server.Mobiles break; if (amount < 5000) - { Say(1010006); // We cannot create checks for such a paltry amount of gold! - } else if (amount > 1000000) - { Say(1010007); // Our policies prevent us from creating checks worth that much! - } else { BankCheck check = new BankCheck(amount); diff --git a/Projects/Scripts/Mobiles/Townfolk/BrideGroom.cs b/Projects/Scripts/Mobiles/Townfolk/BrideGroom.cs index 027273089..40f372cd4 100644 --- a/Projects/Scripts/Mobiles/Townfolk/BrideGroom.cs +++ b/Projects/Scripts/Mobiles/Townfolk/BrideGroom.cs @@ -50,10 +50,7 @@ namespace Server.Mobiles else AddItem(new Boots(lowHue)); - if (Utility.RandomBool()) - HairItemID = 0x203B; - else - HairItemID = 0x203C; + HairItemID = Utility.RandomBool() ? 0x203B : 0x203C; HairHue = Race.RandomHairHue(); @@ -74,4 +71,4 @@ namespace Server.Mobiles int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/Townfolk/EscortableMage.cs b/Projects/Scripts/Mobiles/Townfolk/EscortableMage.cs index b97d80c54..624dea558 100644 --- a/Projects/Scripts/Mobiles/Townfolk/EscortableMage.cs +++ b/Projects/Scripts/Mobiles/Townfolk/EscortableMage.cs @@ -68,4 +68,4 @@ namespace Server.Mobiles int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/Townfolk/Merchant.cs b/Projects/Scripts/Mobiles/Townfolk/Merchant.cs index e80c8faa6..159f6557c 100644 --- a/Projects/Scripts/Mobiles/Townfolk/Merchant.cs +++ b/Projects/Scripts/Mobiles/Townfolk/Merchant.cs @@ -77,4 +77,4 @@ namespace Server.Mobiles int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/Townfolk/Messenger.cs b/Projects/Scripts/Mobiles/Townfolk/Messenger.cs index 69a8e6908..5c909af23 100644 --- a/Projects/Scripts/Mobiles/Townfolk/Messenger.cs +++ b/Projects/Scripts/Mobiles/Townfolk/Messenger.cs @@ -66,4 +66,4 @@ namespace Server.Mobiles int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/Townfolk/Noble.cs b/Projects/Scripts/Mobiles/Townfolk/Noble.cs index 994996a55..b603bc051 100644 --- a/Projects/Scripts/Mobiles/Townfolk/Noble.cs +++ b/Projects/Scripts/Mobiles/Townfolk/Noble.cs @@ -78,4 +78,4 @@ namespace Server.Mobiles int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/Townfolk/Peasant.cs b/Projects/Scripts/Mobiles/Townfolk/Peasant.cs index 61619ac87..4658c9c01 100644 --- a/Projects/Scripts/Mobiles/Townfolk/Peasant.cs +++ b/Projects/Scripts/Mobiles/Townfolk/Peasant.cs @@ -71,4 +71,4 @@ namespace Server.Mobiles int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/Townfolk/SeekerOfAdventure.cs b/Projects/Scripts/Mobiles/Townfolk/SeekerOfAdventure.cs index 2d34b17a7..a8da80d46 100644 --- a/Projects/Scripts/Mobiles/Townfolk/SeekerOfAdventure.cs +++ b/Projects/Scripts/Mobiles/Townfolk/SeekerOfAdventure.cs @@ -26,12 +26,7 @@ namespace Server.Mobiles public override bool ClickTitle => false; // Do not display 'the seeker of adventure' when single-clicking - public override string[] GetPossibleDestinations() - { - if (Core.ML) - return m_MLDestinations; - return m_Dungeons; - } + public override string[] GetPossibleDestinations() => Core.ML ? m_MLDestinations : m_Dungeons; private static int GetRandomHue() { @@ -89,4 +84,4 @@ namespace Server.Mobiles int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Projects/Scripts/Mobiles/Townfolk/TownCrier.cs b/Projects/Scripts/Mobiles/Townfolk/TownCrier.cs index b151f5da7..41f9c7a1c 100644 --- a/Projects/Scripts/Mobiles/Townfolk/TownCrier.cs +++ b/Projects/Scripts/Mobiles/Townfolk/TownCrier.cs @@ -4,7 +4,6 @@ using System.Text; using Server.Gumps; using Server.Items; using Server.Network; -using Server.Prompts; namespace Server.Mobiles { @@ -20,7 +19,7 @@ namespace Server.Mobiles { private static GlobalTownCrierEntryList m_Instance; - public static GlobalTownCrierEntryList Instance => m_Instance ?? (m_Instance = new GlobalTownCrierEntryList()); + public static GlobalTownCrierEntryList Instance => m_Instance ??= new GlobalTownCrierEntryList(); public bool IsEmpty => Entries == null || Entries.Count == 0; @@ -50,8 +49,7 @@ namespace Server.Mobiles public TownCrierEntry AddEntry(string[] lines, TimeSpan duration) { - if (Entries == null) - Entries = new List(); + Entries ??= new List