From 6bce4eea148ad55fa07f497c5cfa47a3aa165eda Mon Sep 17 00:00:00 2001 From: Kurt Date: Sun, 14 Mar 2021 16:16:55 -0700 Subject: [PATCH] Minor clean Annotations (nullable), some switch cases for readability --- PKHeX.Core/Editing/Saves/BoxManipUtil.cs | 2 +- .../Saves/Editors/EventWork/EventWorkUtil.cs | 18 ++++--- .../Editing/Saves/Slots/Info/SlotInfoMisc.cs | 7 ++- PKHeX.Core/Legality/Areas/EncounterArea2.cs | 7 ++- PKHeX.Core/Legality/BinLinker.cs | 3 +- .../Legality/Encounters/Data/Encounters6.cs | 8 +-- .../EncounterStatic/EncounterStatic7.cs | 2 +- .../Specific/EncounterSlotGenerator.cs | 24 ++++----- .../Legality/Evolutions/EvolutionTree.cs | 2 +- PKHeX.Core/Legality/MoveListSuggest.cs | 26 +++++----- PKHeX.Core/Legality/RNG/Frame/SlotRange.cs | 44 ++++++++-------- PKHeX.Core/Legality/RNG/PIDGenerator.cs | 2 +- PKHeX.Core/Legality/RNG/RaidRNG.cs | 13 +++-- PKHeX.Core/MysteryGifts/MysteryGift.cs | 5 -- PKHeX.Core/MysteryGifts/MysteryUtil.cs | 29 ++++++----- PKHeX.Core/MysteryGifts/WC7.cs | 8 +-- PKHeX.Core/PKM/PKM.cs | 17 +++---- PKHeX.Core/PKM/Searching/SearchUtil.cs | 13 ++--- PKHeX.Core/PKM/Shared/GBPKM.cs | 14 ++--- PKHeX.Core/PKM/Util/PKMConverter.cs | 3 ++ PKHeX.Core/Saves/SAV4.cs | 2 +- PKHeX.Core/Saves/SAV4BR.cs | 1 - PKHeX.Core/Saves/SAV4DP.cs | 1 + PKHeX.Core/Saves/SAV4HGSS.cs | 1 + PKHeX.Core/Saves/SAV4Pt.cs | 1 + PKHeX.Core/Saves/SaveFile.cs | 7 +-- .../Gen3/EReaderBerrySettings.cs | 22 ++++---- .../Substructures/Gen3/PokeBlock3Color.cs | 4 +- .../Substructures/Gen4/SAV4BlockDetection.cs | 6 +-- PKHeX.Core/Saves/Substructures/Gen6/PSS6.cs | 2 +- .../Saves/Substructures/Gen6/RecordBlock6.cs | 34 ++++++++----- .../Substructures/Inventory/InventoryPouch.cs | 12 +++-- PKHeX.Core/Saves/Substructures/Mail/Mail5.cs | 13 ++--- .../Saves/Substructures/PokeDex/Zukan4.cs | 4 +- PKHeX.Core/Saves/Substructures/Records.cs | 12 ++--- PKHeX.Core/Util/NetUtil.cs | 5 +- PKHeX.Core/Util/ResourceUtil.cs | 4 +- PKHeX.Core/Util/UpdateUtil.cs | 2 +- PKHeX.Core/Util/ValueTypeTypeConverter.cs | 14 +++-- .../Controls/PKM Editor/PKMEditor.cs | 20 +++++--- .../Controls/SAV Editor/PartyEditor.cs | 13 +++-- PKHeX.WinForms/Controls/Slots/SlotUtil.cs | 11 ++-- PKHeX.WinForms/MainWindow/Main.cs | 13 +++-- PKHeX.WinForms/MainWindow/PluginLoader.cs | 2 +- PKHeX.WinForms/Subforms/SAV_MysteryGiftDB.cs | 6 ++- .../Save Editors/Gen7/SAV_Capture7GG.cs | 4 +- .../Save Editors/Gen7/SAV_FestivalPlaza.cs | 4 +- .../Subforms/Save Editors/SAV_MailBox.cs | 8 +-- .../Subforms/Save Editors/SAV_Wondercard.cs | 51 +++++++++---------- .../Subforms/Save Editors/TrainerStat.cs | 6 +-- .../Saves/MemeCrypto/MemeCryptoTests.cs | 8 +-- 51 files changed, 285 insertions(+), 255 deletions(-) diff --git a/PKHeX.Core/Editing/Saves/BoxManipUtil.cs b/PKHeX.Core/Editing/Saves/BoxManipUtil.cs index 5afb27d9b..31d9f6786 100644 --- a/PKHeX.Core/Editing/Saves/BoxManipUtil.cs +++ b/PKHeX.Core/Editing/Saves/BoxManipUtil.cs @@ -29,7 +29,7 @@ public static class BoxManipUtil /// /// Manipulation type. /// Reference to . - public static IBoxManip GetManip(this BoxManipType type) => ManipCategories.SelectMany(c => c).FirstOrDefault(m => m.Type == type); + public static IBoxManip GetManip(this BoxManipType type) => ManipCategories.SelectMany(c => c).First(m => m.Type == type); /// /// Gets the corresponding name from for the requested . diff --git a/PKHeX.Core/Editing/Saves/Editors/EventWork/EventWorkUtil.cs b/PKHeX.Core/Editing/Saves/Editors/EventWork/EventWorkUtil.cs index d20908071..4adb16d6b 100644 --- a/PKHeX.Core/Editing/Saves/Editors/EventWork/EventWorkUtil.cs +++ b/PKHeX.Core/Editing/Saves/Editors/EventWork/EventWorkUtil.cs @@ -20,18 +20,20 @@ public static class EventWorkUtil private static bool GetIndex(string l, out int index, out EventVarType type) { - if (!TypeDict.TryGetValue(l[0], out type)) + var typeChar = l[0]; + if (!TypeDict.TryGetValue(typeChar, out type)) { - Debug.WriteLine($"Rejected line due to bad type. {l[0]}"); + Debug.WriteLine($"Rejected line due to bad type: {typeChar}"); index = -1; return false; } - if (!int.TryParse(l.Substring(1), out index)) - { - Debug.WriteLine($"Rejected line due to bad index. {l[0]}"); - return false; - } - return true; + + var indexString = l.Substring(1); + if (int.TryParse(indexString, out index)) + return true; + + Debug.WriteLine($"Rejected line due to bad index: {indexString}"); + return false; } /// diff --git a/PKHeX.Core/Editing/Saves/Slots/Info/SlotInfoMisc.cs b/PKHeX.Core/Editing/Saves/Slots/Info/SlotInfoMisc.cs index 952030803..d36d8ae2d 100644 --- a/PKHeX.Core/Editing/Saves/Slots/Info/SlotInfoMisc.cs +++ b/PKHeX.Core/Editing/Saves/Slots/Info/SlotInfoMisc.cs @@ -19,7 +19,12 @@ public SlotInfoMisc(SaveFile sav, int slot, int offset, bool party = false) Slot = slot; Offset = offset; PartyFormat = party; - Data = sav is SAV4 s ? s.General : sav is SAV3 s3 ? s3.Large : sav.Data; + Data = sav switch + { + SAV4 s => s.General, + SAV3 s3 => s3.Large, + _ => sav.Data + }; } public SlotInfoMisc(byte[] data, int slot, int offset, bool party = false) diff --git a/PKHeX.Core/Legality/Areas/EncounterArea2.cs b/PKHeX.Core/Legality/Areas/EncounterArea2.cs index c49af61ad..8d1153a1a 100644 --- a/PKHeX.Core/Legality/Areas/EncounterArea2.cs +++ b/PKHeX.Core/Legality/Areas/EncounterArea2.cs @@ -50,7 +50,12 @@ private EncounterArea2(byte[] data, GameVersion game) : base(game) const int size = 4; int count = (data.Length - 4) / size; - Rates = type == SlotType.BugContest ? BCC_SlotRates : (type == SlotType.Grass) ? RatesGrass : RatesSurf; + Rates = type switch + { + SlotType.BugContest => BCC_SlotRates, + SlotType.Grass => RatesGrass, + _ => RatesSurf + }; Slots = ReadSlots(data, count, 4); } } diff --git a/PKHeX.Core/Legality/BinLinker.cs b/PKHeX.Core/Legality/BinLinker.cs index a38374ba8..03878bf02 100644 --- a/PKHeX.Core/Legality/BinLinker.cs +++ b/PKHeX.Core/Legality/BinLinker.cs @@ -12,12 +12,13 @@ public static class BinLinker /// Unpacked array containing all files that were packed. public static byte[][] Unpack(byte[] fileData, string identifier) { +#if DEBUG if (fileData.Length < 4) throw new ArgumentException(nameof(fileData)); if (identifier[0] != fileData[0] || identifier[1] != fileData[1]) throw new ArgumentException(nameof(identifier)); - +#endif int count = BitConverter.ToUInt16(fileData, 2); int ctr = 4; int start = BitConverter.ToInt32(fileData, ctr); ctr += 4; byte[][] returnData = new byte[count][]; diff --git a/PKHeX.Core/Legality/Encounters/Data/Encounters6.cs b/PKHeX.Core/Legality/Encounters/Data/Encounters6.cs index 421a4118c..092c2879a 100644 --- a/PKHeX.Core/Legality/Encounters/Data/Encounters6.cs +++ b/PKHeX.Core/Legality/Encounters/Data/Encounters6.cs @@ -9,10 +9,10 @@ namespace PKHeX.Core internal static class Encounters6 { private static readonly EncounterArea6XY FriendSafari = new(); - internal static readonly EncounterArea6XY[] SlotsX = EncounterArea6XY.GetAreas(Get("x", "xy"), GameVersion.X, FriendSafari); - internal static readonly EncounterArea6XY[] SlotsY = EncounterArea6XY.GetAreas(Get("y", "xy"), GameVersion.Y, FriendSafari); - internal static readonly EncounterArea6AO[] SlotsA = EncounterArea6AO.GetAreas(Get("a", "ao"), GameVersion.AS); - internal static readonly EncounterArea6AO[] SlotsO = EncounterArea6AO.GetAreas(Get("o", "ao"), GameVersion.OR); + internal static readonly EncounterArea6XY[] SlotsX = EncounterArea6XY.GetAreas(Get("x", "xy"), X, FriendSafari); + internal static readonly EncounterArea6XY[] SlotsY = EncounterArea6XY.GetAreas(Get("y", "xy"), Y, FriendSafari); + internal static readonly EncounterArea6AO[] SlotsA = EncounterArea6AO.GetAreas(Get("a", "ao"), AS); + internal static readonly EncounterArea6AO[] SlotsO = EncounterArea6AO.GetAreas(Get("o", "ao"), OR); private static byte[][] Get(string resource, string ident) => BinLinker.Unpack(Util.GetBinaryResource($"encounter_{resource}.pkl"), ident); static Encounters6() diff --git a/PKHeX.Core/Legality/Encounters/EncounterStatic/EncounterStatic7.cs b/PKHeX.Core/Legality/Encounters/EncounterStatic/EncounterStatic7.cs index d24a4d808..8101da2a3 100644 --- a/PKHeX.Core/Legality/Encounters/EncounterStatic/EncounterStatic7.cs +++ b/PKHeX.Core/Legality/Encounters/EncounterStatic/EncounterStatic7.cs @@ -26,7 +26,7 @@ protected override bool IsMatchForm(PKM pkm, DexLevel evo) if (SkipFormCheck) return true; - if (FormInfo.IsTotemForm(Species, Form, Generation)) + if (FormInfo.IsTotemForm(Species, Form, 7)) { var expectForm = pkm.Format == 7 ? Form : FormInfo.GetTotemBaseForm(Species, Form); return expectForm == evo.Form; diff --git a/PKHeX.Core/Legality/Encounters/Generator/Specific/EncounterSlotGenerator.cs b/PKHeX.Core/Legality/Encounters/Generator/Specific/EncounterSlotGenerator.cs index e9f509bf8..6e6872249 100644 --- a/PKHeX.Core/Legality/Encounters/Generator/Specific/EncounterSlotGenerator.cs +++ b/PKHeX.Core/Legality/Encounters/Generator/Specific/EncounterSlotGenerator.cs @@ -21,7 +21,7 @@ namespace PKHeX.Core { public static class EncounterSlotGenerator { - public static IEnumerable GetPossible(PKM pkm, IReadOnlyList chain, GameVersion gameSource = GameVersion.Any) + public static IEnumerable GetPossible(PKM pkm, IReadOnlyList chain, GameVersion gameSource = Any) { var possibleAreas = GetAreasByGame(pkm, gameSource); return possibleAreas.SelectMany(area => area.Slots).Where(z => chain.Any(v => v.Species == z.Species)); @@ -55,9 +55,9 @@ private static IEnumerable GetRawEncounterSlots(PKM pkm, IReadOnl } } - public static IEnumerable GetValidWildEncounters34(PKM pkm, IReadOnlyList chain, GameVersion gameSource = GameVersion.Any) + public static IEnumerable GetValidWildEncounters34(PKM pkm, IReadOnlyList chain, GameVersion gameSource = Any) { - if (gameSource == GameVersion.Any) + if (gameSource == Any) gameSource = (GameVersion)pkm.Version; var slots = GetRawEncounterSlots(pkm, chain, gameSource); @@ -65,37 +65,37 @@ public static IEnumerable GetValidWildEncounters34(PKM pkm, IRead return slots; // defer deferrals to the method consuming this collection } - public static IEnumerable GetValidWildEncounters12(PKM pkm, IReadOnlyList chain, GameVersion gameSource = GameVersion.Any) + public static IEnumerable GetValidWildEncounters12(PKM pkm, IReadOnlyList chain, GameVersion gameSource = Any) { - if (gameSource == GameVersion.Any) + if (gameSource == Any) gameSource = (GameVersion)pkm.Version; return GetRawEncounterSlots(pkm, chain, gameSource); } - public static IEnumerable GetValidWildEncounters(PKM pkm, IReadOnlyList chain, GameVersion gameSource = GameVersion.Any) + public static IEnumerable GetValidWildEncounters(PKM pkm, IReadOnlyList chain, GameVersion gameSource = Any) { - if (gameSource == GameVersion.Any) + if (gameSource == Any) gameSource = (GameVersion)pkm.Version; return GetRawEncounterSlots(pkm, chain, gameSource); } - public static IEnumerable GetEncounterSlots(PKM pkm, GameVersion gameSource = GameVersion.Any) + public static IEnumerable GetEncounterSlots(PKM pkm, GameVersion gameSource = Any) { - if (gameSource == GameVersion.Any) + if (gameSource == Any) gameSource = (GameVersion)pkm.Version; return GetEncounterTable(pkm, gameSource); } - private static IEnumerable GetEncounterAreas(PKM pkm, GameVersion gameSource = GameVersion.Any) + private static IEnumerable GetEncounterAreas(PKM pkm, GameVersion gameSource = Any) { - if (gameSource == GameVersion.Any) + if (gameSource == Any) gameSource = (GameVersion)pkm.Version; var slots = GetEncounterSlots(pkm, gameSource: gameSource); - bool noMet = !pkm.HasOriginalMetLocation || (pkm.Format == 2 && gameSource != GameVersion.C); + bool noMet = !pkm.HasOriginalMetLocation || (pkm.Format == 2 && gameSource != C); if (noMet) return slots; var metLocation = pkm.Met_Location; diff --git a/PKHeX.Core/Legality/Evolutions/EvolutionTree.cs b/PKHeX.Core/Legality/Evolutions/EvolutionTree.cs index 009236edd..86ee95f2f 100644 --- a/PKHeX.Core/Legality/Evolutions/EvolutionTree.cs +++ b/PKHeX.Core/Legality/Evolutions/EvolutionTree.cs @@ -194,7 +194,7 @@ private void BanEvo(int species, int form, Func func) public List GetValidPreEvolutions(PKM pkm, int maxLevel, int maxSpeciesOrigin = -1, bool skipChecks = false, int minLevel = 1) { if (maxSpeciesOrigin <= 0) - maxSpeciesOrigin = Legal.GetMaxSpeciesOrigin(pkm); + maxSpeciesOrigin = GetMaxSpeciesOrigin(pkm); if (pkm.IsEgg && !skipChecks) { return new List(1) diff --git a/PKHeX.Core/Legality/MoveListSuggest.cs b/PKHeX.Core/Legality/MoveListSuggest.cs index deb3436c5..e73b66be5 100644 --- a/PKHeX.Core/Legality/MoveListSuggest.cs +++ b/PKHeX.Core/Legality/MoveListSuggest.cs @@ -11,20 +11,20 @@ private static int[] GetSuggestedMoves(PKM pkm, IReadOnlyList= 7 ? pkm.Met_Level : pkm.CurrentLevel; - var ver = enc.Version; - return MoveLevelUp.GetEncounterMoves(enc.Species, 0, lvl, ver); - } + if (types != MoveSourceType.None) + return GetValidMoves(pkm, evoChains, types).Skip(1).ToArray(); // skip move 0 - if (pkm.Species == enc.Species) - { - return MoveLevelUp.GetEncounterMoves(pkm.Species, pkm.Form, pkm.CurrentLevel, (GameVersion)pkm.Version); - } + // try to give current moves + if (enc.Generation <= 2) + { + var lvl = pkm.Format >= 7 ? pkm.Met_Level : pkm.CurrentLevel; + var ver = enc.Version; + return MoveLevelUp.GetEncounterMoves(enc.Species, 0, lvl, ver); + } + + if (pkm.Species == enc.Species) + { + return MoveLevelUp.GetEncounterMoves(pkm.Species, pkm.Form, pkm.CurrentLevel, (GameVersion)pkm.Version); } return GetValidMoves(pkm, evoChains, types).Skip(1).ToArray(); // skip move 0 diff --git a/PKHeX.Core/Legality/RNG/Frame/SlotRange.cs b/PKHeX.Core/Legality/RNG/Frame/SlotRange.cs index 3c60be237..85ac3f992 100644 --- a/PKHeX.Core/Legality/RNG/Frame/SlotRange.cs +++ b/PKHeX.Core/Legality/RNG/Frame/SlotRange.cs @@ -144,31 +144,29 @@ public static bool GetCanEncounter(EncounterSlot slot, FrameType frameType, int return proc < 60; if (frameType == FrameType.MethodH) return true; // fishing encounters are disjointed by the hooked message. - - // fishing - if (stype == SlotType.Old_Rod) - { - if (proc < 25) - return true; - if (proc < 50) - return lead == LeadRequired.None; - } - else if (stype == SlotType.Good_Rod) - { - if (proc < 50) - return true; - if (proc < 75) - return lead == LeadRequired.None; - } - else if (stype == SlotType.Super_Rod) - { - if (proc < 75) - return true; - return lead == LeadRequired.None; // < 100 always true - } - return false; // shouldn't hit here + return GetCanEncounterFish(lead, stype, proc); } + private static bool GetCanEncounterFish(LeadRequired lead, SlotType stype, int proc) => stype switch + { + // Lead:None => can be suction cups + SlotType.Old_Rod => proc switch + { + < 25 => true, + < 50 => lead == LeadRequired.None, + _ => false + }, + SlotType.Good_Rod => proc switch + { + < 50 => true, + < 75 => lead == LeadRequired.None, + _ => false + }, + SlotType.Super_Rod => proc < 75 || lead == LeadRequired.None, + + _ => false + }; + /// /// Checks both Static and Magnet Pull ability type selection encounters to see if the encounter can be selected. /// diff --git a/PKHeX.Core/Legality/RNG/PIDGenerator.cs b/PKHeX.Core/Legality/RNG/PIDGenerator.cs index 9ea960cea..90b2d1086 100644 --- a/PKHeX.Core/Legality/RNG/PIDGenerator.cs +++ b/PKHeX.Core/Legality/RNG/PIDGenerator.cs @@ -203,7 +203,7 @@ public static void SetRandomPokeSpotPID(PKM pk, int nature, int gender, int abil while (true) { var seed = Util.Rand32(); - if (!MethodFinder.IsPokeSpotActivation(slot, seed, out var _)) + if (!MethodFinder.IsPokeSpotActivation(slot, seed, out _)) continue; var rng = RNG.XDRNG; diff --git a/PKHeX.Core/Legality/RNG/RaidRNG.cs b/PKHeX.Core/Legality/RNG/RaidRNG.cs index d82fc8b65..09ff0d8a5 100644 --- a/PKHeX.Core/Legality/RNG/RaidRNG.cs +++ b/PKHeX.Core/Legality/RNG/RaidRNG.cs @@ -102,13 +102,12 @@ private static bool Verify(PKM pk, ulong seed, int[] ivs, int iv_count, int abil if (pk.IV_SPE != ivs[5]) return false; - int abil; - if (ability_param == 254) - abil = (int)rng.NextInt(3); - else if (ability_param == 255) - abil = (int)rng.NextInt(2); - else - abil = ability_param; + int abil = ability_param switch + { + 254 => (int)rng.NextInt(3), + 255 => (int)rng.NextInt(2), + _ => ability_param + }; abil <<= 1; // 1/2/4 var current = pk.AbilityNumber; diff --git a/PKHeX.Core/MysteryGifts/MysteryGift.cs b/PKHeX.Core/MysteryGifts/MysteryGift.cs index 3e95c396a..e1249ec5e 100644 --- a/PKHeX.Core/MysteryGifts/MysteryGift.cs +++ b/PKHeX.Core/MysteryGifts/MysteryGift.cs @@ -122,11 +122,6 @@ public virtual GameVersion Version public virtual int Quantity { get => 1; set { } } public virtual bool Empty => false; - public virtual bool IsBP { get => false; set { } } - public virtual int BP { get => 0; set { } } - public virtual bool IsBean { get => false; set { } } - public virtual int Bean { get => 0; set { } } - public virtual string CardHeader => (CardID > 0 ? $"Card #: {CardID:0000}" : "N/A") + $" - {CardTitle.Replace('\u3000',' ').Trim()}"; // Search Properties diff --git a/PKHeX.Core/MysteryGifts/MysteryUtil.cs b/PKHeX.Core/MysteryGifts/MysteryUtil.cs index 5c2763488..4cfd56418 100644 --- a/PKHeX.Core/MysteryGifts/MysteryUtil.cs +++ b/PKHeX.Core/MysteryGifts/MysteryUtil.cs @@ -63,21 +63,26 @@ public static IEnumerable GetDescription(this MysteryGift gift, IBasicSt catch { result.Add(MsgMysteryGiftParseFail); } #pragma warning restore CA1031 // Do not catch general exception types } - else if (gift.IsBP) + else switch (gift) { - result.Add($"BP: {gift.BP}"); + case WC7 { IsBP: true } w7bp: + result.Add($"BP: {w7bp.BP}"); + break; + case WC7 { IsBean: true } w7bean: + result.Add($"Bean ID: {w7bean.Bean}"); + result.Add($"Quantity: {w7bean.Quantity}"); + break; + default: + result.Add(MsgMysteryGiftParseTypeUnknown); + break; } - else if (gift.IsBean) + switch (gift) { - result.Add($"Bean ID: {gift.Bean}"); - result.Add($"Quantity: {gift.Quantity}"); - } - else { result.Add(MsgMysteryGiftParseTypeUnknown); } - if (gift is WC7 w7) - { - result.Add($"Repeatable: {w7.GiftRepeatable}"); - result.Add($"Collected: {w7.GiftUsed}"); - result.Add($"Once Per Day: {w7.GiftOncePerDay}"); + case WC7 w7: + result.Add($"Repeatable: {w7.GiftRepeatable}"); + result.Add($"Collected: {w7.GiftUsed}"); + result.Add($"Once Per Day: {w7.GiftOncePerDay}"); + break; } return result; } diff --git a/PKHeX.Core/MysteryGifts/WC7.cs b/PKHeX.Core/MysteryGifts/WC7.cs index 3aa512b65..5b991d097 100644 --- a/PKHeX.Core/MysteryGifts/WC7.cs +++ b/PKHeX.Core/MysteryGifts/WC7.cs @@ -114,12 +114,12 @@ private uint Day public bool MultiObtain { get => Data[0x53] == 1; set => Data[0x53] = value ? 1 : 0; } // BP Properties - public override bool IsBP { get => CardType == 3; set { if (value) CardType = 3; } } - public override int BP { get => ItemID; set => ItemID = value; } + public bool IsBP { get => CardType == 3; set { if (value) CardType = 3; } } + public int BP { get => ItemID; set => ItemID = value; } // Bean (Mame) Properties - public override bool IsBean { get => CardType == 2; set { if (value) CardType = 2; } } - public override int Bean { get => ItemID; set => ItemID = value; } + public bool IsBean { get => CardType == 2; set { if (value) CardType = 2; } } + public int Bean { get => ItemID; set => ItemID = value; } // Item Properties public override bool IsItem { get => CardType == 1; set { if (value) CardType = 1; } } diff --git a/PKHeX.Core/PKM/PKM.cs b/PKHeX.Core/PKM/PKM.cs index 2f950927a..57129b2b3 100644 --- a/PKHeX.Core/PKM/PKM.cs +++ b/PKHeX.Core/PKM/PKM.cs @@ -719,18 +719,13 @@ public virtual void RefreshAbility(int n) /// Gets the IV Judge Rating value. /// /// IV Judge scales his response 0 (worst) to 3 (best). - public int PotentialRating + public int PotentialRating => IVTotal switch { - get - { - int ivTotal = IVTotal; - if (ivTotal <= 90) - return 0; - if (ivTotal <= 120) - return 1; - return ivTotal <= 150 ? 2 : 3; - } - } + <= 90 => 0, + <= 120 => 1, + <= 150 => 2, + _ => 3 + }; /// /// Gets the current Battle Stats. diff --git a/PKHeX.Core/PKM/Searching/SearchUtil.cs b/PKHeX.Core/PKM/Searching/SearchUtil.cs index 72a98ad1b..7d10a724a 100644 --- a/PKHeX.Core/PKM/Searching/SearchUtil.cs +++ b/PKHeX.Core/PKM/Searching/SearchUtil.cs @@ -24,12 +24,13 @@ public static IEnumerable FilterByFormat(IEnumerable res, int format, return res; /* Do nothing */ } - if (format <= 2) // 1-2 - return res.Where(pk => pk.Format <= 2); - if (format <= 6) // 3-6 - return res.Where(pk => pk.Format >= 3); - - return res; + // Might need to clamp down further for generations that cannot exist in the current format. + return format switch + { + <= 2 => res.Where(pk => pk.Format <= 2), // 1-2 + <= 6 => res.Where(pk => pk.Format >= 3), // 3-6 + _ => res + }; } public static IEnumerable FilterByGeneration(IEnumerable res, int generation) => generation switch diff --git a/PKHeX.Core/PKM/Shared/GBPKM.cs b/PKHeX.Core/PKM/Shared/GBPKM.cs index e5e7d12ee..227470817 100644 --- a/PKHeX.Core/PKM/Shared/GBPKM.cs +++ b/PKHeX.Core/PKM/Shared/GBPKM.cs @@ -96,13 +96,13 @@ public sealed override int Gender get { int gv = PersonalInfo.Gender; - if (gv == 255) - return 2; - if (gv == 254) - return 1; - if (gv == 0) - return 0; - return IV_ATK > gv >> 4 ? 0 : 1; + return gv switch + { + 255 => 2, + 254 => 1, + 0 => 0, + _ => IV_ATK > gv >> 4 ? 0 : 1 + }; } set { } } diff --git a/PKHeX.Core/PKM/Util/PKMConverter.cs b/PKHeX.Core/PKM/Util/PKMConverter.cs index ec95ebce2..d3515e308 100644 --- a/PKHeX.Core/PKM/Util/PKMConverter.cs +++ b/PKHeX.Core/PKM/Util/PKMConverter.cs @@ -439,6 +439,9 @@ public static PKM GetBlank(Type type) public static PKM GetBlank(int gen) { var type = Type.GetType($"PKHeX.Core.PK{gen}"); + if (type is null) + throw new InvalidCastException($"Unable to get the type for PK{gen}."); + return GetBlank(type); } } diff --git a/PKHeX.Core/Saves/SAV4.cs b/PKHeX.Core/Saves/SAV4.cs index 08f1834bf..3553d1cce 100644 --- a/PKHeX.Core/Saves/SAV4.cs +++ b/PKHeX.Core/Saves/SAV4.cs @@ -94,7 +94,7 @@ public override void CopyChangesFrom(SaveFile sav) public override int MaxMoveID => Legal.MaxMoveID_4; public override int MaxSpeciesID => Legal.MaxSpeciesID_4; - public override int MaxItemID => Version == GameVersion.HGSS ? Legal.MaxItemID_4_HGSS : Version == GameVersion.Pt ? Legal.MaxItemID_4_Pt : Legal.MaxItemID_4_DP; + // MaxItemID public override int MaxAbilityID => Legal.MaxAbilityID_4; public override int MaxBallID => Legal.MaxBallID_4; public override int MaxGameID => Legal.MaxGameID_4; // Colo/XD diff --git a/PKHeX.Core/Saves/SAV4BR.cs b/PKHeX.Core/Saves/SAV4BR.cs index d13030fc8..6a02ac20b 100644 --- a/PKHeX.Core/Saves/SAV4BR.cs +++ b/PKHeX.Core/Saves/SAV4BR.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; namespace PKHeX.Core { diff --git a/PKHeX.Core/Saves/SAV4DP.cs b/PKHeX.Core/Saves/SAV4DP.cs index 201375468..c2b0ab84a 100644 --- a/PKHeX.Core/Saves/SAV4DP.cs +++ b/PKHeX.Core/Saves/SAV4DP.cs @@ -25,6 +25,7 @@ public SAV4DP(byte[] data) : base(data) protected override SAV4 CloneInternal4() => State.Exportable ? new SAV4DP(Data) : new SAV4DP(); public override PersonalTable Personal => PersonalTable.DP; public override IReadOnlyList HeldItems => Legal.HeldItems_DP; + public override int MaxItemID => Legal.MaxItemID_4_DP; protected override int GeneralSize => 0xC100; protected override int StorageSize => 0x121E0; // Start 0xC100, +4 starts box data diff --git a/PKHeX.Core/Saves/SAV4HGSS.cs b/PKHeX.Core/Saves/SAV4HGSS.cs index 2e428f237..ebb6b27c9 100644 --- a/PKHeX.Core/Saves/SAV4HGSS.cs +++ b/PKHeX.Core/Saves/SAV4HGSS.cs @@ -25,6 +25,7 @@ public SAV4HGSS(byte[] data) : base(data) public override PersonalTable Personal => PersonalTable.HGSS; public override IReadOnlyList HeldItems => Legal.HeldItems_HGSS; + public override int MaxItemID => Legal.MaxItemID_4_HGSS; protected override int GeneralSize => 0xF628; protected override int StorageSize => 0x12310; // Start 0xF700, +0 starts box data protected override int StorageStart => 0xF700; // unused section right after GeneralSize, alignment? diff --git a/PKHeX.Core/Saves/SAV4Pt.cs b/PKHeX.Core/Saves/SAV4Pt.cs index a8227b434..0fe3c4029 100644 --- a/PKHeX.Core/Saves/SAV4Pt.cs +++ b/PKHeX.Core/Saves/SAV4Pt.cs @@ -23,6 +23,7 @@ public SAV4Pt(byte[] data) : base(data) protected override SAV4 CloneInternal4() => State.Exportable ? new SAV4Pt(Data) : new SAV4Pt(); public override PersonalTable Personal => PersonalTable.Pt; public override IReadOnlyList HeldItems => Legal.HeldItems_Pt; + public override int MaxItemID => Legal.MaxItemID_4_Pt; protected override int GeneralSize => 0xCF2C; protected override int StorageSize => 0x121E4; // Start 0xCF2C, +4 starts box data diff --git a/PKHeX.Core/Saves/SaveFile.cs b/PKHeX.Core/Saves/SaveFile.cs index aeca54eb6..5fdc6439d 100644 --- a/PKHeX.Core/Saves/SaveFile.cs +++ b/PKHeX.Core/Saves/SaveFile.cs @@ -295,11 +295,10 @@ public IList PartyData { if (value.Count is 0 or > 6) throw new ArgumentException($"Expected 1-6, got {value.Count}"); - if (value.Any(pk => PKMType != pk.GetType())) - throw new ArgumentException($"Not {PKMType} array."); +#if DEBUG if (value[0].Species == 0) Debug.WriteLine($"Empty first slot, received {value.Count}."); - +#endif int ctr = 0; foreach (var exist in value.Where(pk => pk.Species != 0)) SetPartySlot(exist, PartyBuffer, GetPartyOffset(ctr++)); @@ -521,8 +520,6 @@ public IList BoxData { if (value.Count != BoxCount * BoxSlotCount) throw new ArgumentException($"Expected {BoxCount * BoxSlotCount}, got {value.Count}"); - if (value.Any(pk => PKMType != pk.GetType())) - throw new ArgumentException($"Not {PKMType} array."); for (int b = 0; b < BoxCount; b++) SetBoxData(value, b, b * BoxSlotCount); diff --git a/PKHeX.Core/Saves/Substructures/Gen3/EReaderBerrySettings.cs b/PKHeX.Core/Saves/Substructures/Gen3/EReaderBerrySettings.cs index de6182516..48dcfb088 100644 --- a/PKHeX.Core/Saves/Substructures/Gen3/EReaderBerrySettings.cs +++ b/PKHeX.Core/Saves/Substructures/Gen3/EReaderBerrySettings.cs @@ -27,21 +27,23 @@ public static EReaderBerryMatch GetStatus() var matchUSA = EReaderBerriesNames_USA.Contains(Name); if (matchUSA) { - if (Language <= 0) - return ValidAny; - if (Language != 1) - return ValidUSA; - return InvalidUSA; + return Language switch + { + <= 0 => ValidAny, + not 1 => ValidUSA, + _ => InvalidUSA + }; } var matchJP = EReaderBerriesNames_JP.Contains(Name); if (matchJP) { - if (Language <= 0) - return ValidAny; - if (Language == 1) - return ValidJPN; - return InvalidJPN; + return Language switch + { + <= 0 => ValidAny, + 1 => ValidJPN, + _ => InvalidJPN + }; } return NoMatch; diff --git a/PKHeX.Core/Saves/Substructures/Gen3/PokeBlock3Color.cs b/PKHeX.Core/Saves/Substructures/Gen3/PokeBlock3Color.cs index e781645e4..cc0cf9649 100644 --- a/PKHeX.Core/Saves/Substructures/Gen3/PokeBlock3Color.cs +++ b/PKHeX.Core/Saves/Substructures/Gen3/PokeBlock3Color.cs @@ -17,5 +17,5 @@ public enum PokeBlock3Color : byte Black = 12, White = 13, Gold = 14, - }; -} \ No newline at end of file + } +} diff --git a/PKHeX.Core/Saves/Substructures/Gen4/SAV4BlockDetection.cs b/PKHeX.Core/Saves/Substructures/Gen4/SAV4BlockDetection.cs index eaf20b9d1..13a1947fd 100644 --- a/PKHeX.Core/Saves/Substructures/Gen4/SAV4BlockDetection.cs +++ b/PKHeX.Core/Saves/Substructures/Gen4/SAV4BlockDetection.cs @@ -21,10 +21,8 @@ public static int CompareFooters(byte[] data, int offset1, int offset2) var major1 = BitConverter.ToUInt32(data, offset1); var major2 = BitConverter.ToUInt32(data, offset2); var result1 = CompareCounters(major1, major2); - if (result1 == First) - return First; - if (result1 == Second) - return Second; + if (result1 != Same) + return result1; // Minor Counters var minor1 = BitConverter.ToUInt32(data, offset1 + 4); diff --git a/PKHeX.Core/Saves/Substructures/Gen6/PSS6.cs b/PKHeX.Core/Saves/Substructures/Gen6/PSS6.cs index f5bbb8c10..4d4595dcf 100644 --- a/PKHeX.Core/Saves/Substructures/Gen6/PSS6.cs +++ b/PKHeX.Core/Saves/Substructures/Gen6/PSS6.cs @@ -6,7 +6,7 @@ namespace PKHeX.Core public static class PSS6 { private const string Header = "PSS List"; - private static readonly string[] headers = { "PSS Data - Friends", "PSS Data - Acquaintances", "PSS Data - Passerby", }; + private static readonly string[] headers = { "PSS Data - Friends", "PSS Data - Acquaintances", "PSS Data - Passerby" }; public static List GetPSSParse(SAV6 SAV) { diff --git a/PKHeX.Core/Saves/Substructures/Gen6/RecordBlock6.cs b/PKHeX.Core/Saves/Substructures/Gen6/RecordBlock6.cs index 03e225272..394400f86 100644 --- a/PKHeX.Core/Saves/Substructures/Gen6/RecordBlock6.cs +++ b/PKHeX.Core/Saves/Substructures/Gen6/RecordBlock6.cs @@ -42,12 +42,16 @@ public RecordBlock6(SAV7USUM sav, int offset) : base(sav) public override int GetRecord(int recordID) { int ofs = Records.GetOffset(Offset, recordID); - if (recordID < 100) - return BitConverter.ToInt32(Data, ofs); - if (recordID < 200) - return BitConverter.ToInt16(Data, ofs); - Trace.Fail(nameof(recordID)); - return 0; + switch (recordID) + { + case < 100: + return BitConverter.ToInt32(Data, ofs); + case < 200: + return BitConverter.ToInt16(Data, ofs); + default: + Trace.Fail(nameof(recordID)); + return 0; + } } public override void SetRecord(int recordID, int value) @@ -58,12 +62,18 @@ public override void SetRecord(int recordID, int value) int max = GetRecordMax(recordID); if (value > max) value = max; - if (recordID < 100) - BitConverter.GetBytes(value).CopyTo(Data, ofs); - else if (recordID < 200) - BitConverter.GetBytes((ushort)value).CopyTo(Data, ofs); - else - Trace.Fail(nameof(recordID)); + switch (recordID) + { + case < 100: + BitConverter.GetBytes(value).CopyTo(Data, ofs); + break; + case < 200: + BitConverter.GetBytes((ushort)value).CopyTo(Data, ofs); + break; + default: + Trace.Fail(nameof(recordID)); + break; + } } } } \ No newline at end of file diff --git a/PKHeX.Core/Saves/Substructures/Inventory/InventoryPouch.cs b/PKHeX.Core/Saves/Substructures/Inventory/InventoryPouch.cs index e64efa682..f853b9662 100644 --- a/PKHeX.Core/Saves/Substructures/Inventory/InventoryPouch.cs +++ b/PKHeX.Core/Saves/Substructures/Inventory/InventoryPouch.cs @@ -220,11 +220,13 @@ public bool IsValidItemAndCount(ITrainerInfo sav, int item, bool HasNew, bool Ha { if (HaX && sav.Generation != 7) // Gen7 has true cap at 1023, keep 999 cap. { - // Cap at absolute maximum - if (sav.Generation <= 2 && count > byte.MaxValue) - count = byte.MaxValue; - else if (sav.Generation >= 3 && count > ushort.MaxValue) - count = ushort.MaxValue; + count = sav.Generation switch + { + // Cap at absolute maximum + <= 2 when count > byte.MaxValue => byte.MaxValue, + >= 3 when count > ushort.MaxValue => ushort.MaxValue, + _ => count + }; return true; } diff --git a/PKHeX.Core/Saves/Substructures/Mail/Mail5.cs b/PKHeX.Core/Saves/Substructures/Mail/Mail5.cs index 910bd6ab2..2468b19cc 100644 --- a/PKHeX.Core/Saves/Substructures/Mail/Mail5.cs +++ b/PKHeX.Core/Saves/Substructures/Mail/Mail5.cs @@ -46,15 +46,12 @@ private void ResetData() public override ushort GetMessage(int index1, int index2) => BitConverter.ToUInt16(Data, 0x20 + (((index1 * 4) + index2) * 2)); public override void SetMessage(int index1, int index2, ushort value) => BitConverter.GetBytes(value).CopyTo(Data, 0x20 + (((index1 * 4) + index2) * 2)); - public override bool? IsEmpty + public override bool? IsEmpty => MailType switch { - get - { - if (MailType == 0xFF) return true; - if (MailType <= 11) return false; - return null; - } - } + 0xFF => true, + <= 11 => false, + _ => null + }; public override void SetBlank() => SetBlank(null, null); public void SetBlank(byte? lang, byte? ver) => new Mail5(lang: lang, ver: ver).Data.CopyTo(Data, 0); diff --git a/PKHeX.Core/Saves/Substructures/PokeDex/Zukan4.cs b/PKHeX.Core/Saves/Substructures/PokeDex/Zukan4.cs index ccc981aee..13c44c2f1 100644 --- a/PKHeX.Core/Saves/Substructures/PokeDex/Zukan4.cs +++ b/PKHeX.Core/Saves/Substructures/PokeDex/Zukan4.cs @@ -279,9 +279,7 @@ public void AddUnownForm(int form) public override void SetDex(PKM pkm) { int species = pkm.Species; - if (species == 0) - return; - if (species > Legal.MaxSpeciesID_4) + if (species is 0 or > Legal.MaxSpeciesID_4) return; var gender = pkm.Gender; diff --git a/PKHeX.Core/Saves/Substructures/Records.cs b/PKHeX.Core/Saves/Substructures/Records.cs index 285cc52f5..11b804492 100644 --- a/PKHeX.Core/Saves/Substructures/Records.cs +++ b/PKHeX.Core/Saves/Substructures/Records.cs @@ -24,14 +24,12 @@ public static int GetMax(int recordID, IReadOnlyList maxes) return MaxByType[maxes[recordID]]; } - public static int GetOffset(int baseOfs, int recordID) + public static int GetOffset(int baseOfs, int recordID) => recordID switch { - if (recordID < LargeRecordCount) - return baseOfs + (recordID * sizeof(int)); - if (recordID < Count) - return baseOfs + (LargeRecordCount * sizeof(int)) + ((recordID - LargeRecordCount) * sizeof(ushort)); // first 100 are 4bytes, so bias the difference - return -1; - } + < LargeRecordCount => baseOfs + (recordID * sizeof(int)), + < Count => baseOfs + (LargeRecordCount * sizeof(int)) + ((recordID - LargeRecordCount) * sizeof(ushort)), + _ => -1 + }; private static readonly int[] MaxByType = {999_999_999, 9_999_999, 999_999, 99_999, 65535, 9_999, 999, 7}; diff --git a/PKHeX.Core/Util/NetUtil.cs b/PKHeX.Core/Util/NetUtil.cs index e4e16090c..555284231 100644 --- a/PKHeX.Core/Util/NetUtil.cs +++ b/PKHeX.Core/Util/NetUtil.cs @@ -12,6 +12,9 @@ public static class NetUtil try { var stream = GetStreamFromURL(url); + if (stream == null) + return null; + using var reader = new StreamReader(stream); return reader.ReadToEnd(); } @@ -25,7 +28,7 @@ public static class NetUtil } } - private static Stream GetStreamFromURL(string url) + private static Stream? GetStreamFromURL(string url) { var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); diff --git a/PKHeX.Core/Util/ResourceUtil.cs b/PKHeX.Core/Util/ResourceUtil.cs index d385a211d..1c6ab7e54 100644 --- a/PKHeX.Core/Util/ResourceUtil.cs +++ b/PKHeX.Core/Util/ResourceUtil.cs @@ -159,6 +159,8 @@ public static string[] LoadStringList(string file, string? txt) public static byte[] GetBinaryResource(string name) { using var resource = thisAssembly.GetManifestResourceStream($"PKHeX.Core.Resources.byte.{name}"); + if (resource is null) + return Array.Empty(); var buffer = new byte[resource.Length]; resource.Read(buffer, 0, (int)resource.Length); return buffer; @@ -176,7 +178,7 @@ public static byte[] GetBinaryResource(string name) } using var resource = thisAssembly.GetManifestResourceStream(resourceName); - if (resource == null) + if (resource is null) return null; using var reader = new StreamReader(resource); return reader.ReadToEnd(); diff --git a/PKHeX.Core/Util/UpdateUtil.cs b/PKHeX.Core/Util/UpdateUtil.cs index fc234ceec..142fe8d61 100644 --- a/PKHeX.Core/Util/UpdateUtil.cs +++ b/PKHeX.Core/Util/UpdateUtil.cs @@ -15,7 +15,7 @@ public static class UpdateUtil { const string apiEndpoint = "https://api.github.com/repos/kwsch/pkhex/releases/latest"; var responseJson = NetUtil.GetStringFromURL(apiEndpoint); - if (string.IsNullOrEmpty(responseJson)) + if (responseJson is null) return null; // Using a regex to get the tag to avoid importing an entire JSON parsing library diff --git a/PKHeX.Core/Util/ValueTypeTypeConverter.cs b/PKHeX.Core/Util/ValueTypeTypeConverter.cs index f30074170..95b7bb82f 100644 --- a/PKHeX.Core/Util/ValueTypeTypeConverter.cs +++ b/PKHeX.Core/Util/ValueTypeTypeConverter.cs @@ -11,12 +11,16 @@ public sealed class ValueTypeTypeConverter : ExpandableObjectConverter { public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) => true; - public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) + public override object? CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { - object boxed = context.PropertyDescriptor.GetValue(context.Instance); + var pd = context.PropertyDescriptor; + if (pd is null) + return null; + + object? boxed = pd.GetValue(context.Instance); foreach (DictionaryEntry entry in propertyValues) { - var pi = context.PropertyDescriptor.PropertyType.GetProperty(entry.Key.ToString()); + var pi = pd.PropertyType.GetProperty(entry.Key.ToString()); if (pi?.CanWrite == true) pi.SetValue(boxed, Convert.ChangeType(entry.Value, pi.PropertyType), null); } @@ -36,14 +40,14 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); } - public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) + public override object? ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value is ulong) return $"{value:X16}"; // no 0x prefix return base.ConvertTo(context, culture, value, destinationType); } - public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is not string input) return base.ConvertFrom(context, culture, value); diff --git a/PKHeX.WinForms/Controls/PKM Editor/PKMEditor.cs b/PKHeX.WinForms/Controls/PKM Editor/PKMEditor.cs index f28657db0..372a16006 100644 --- a/PKHeX.WinForms/Controls/PKM Editor/PKMEditor.cs +++ b/PKHeX.WinForms/Controls/PKM Editor/PKMEditor.cs @@ -1132,12 +1132,20 @@ private void UpdatePKRSCured(object sender, EventArgs e) private void UpdatePKRSInfected(object sender, EventArgs e) { - if (CHK_Cured.Checked && !CHK_Infected.Checked) - { CHK_Cured.Checked = false; return; } if (CHK_Cured.Checked) + { + if (!CHK_Infected.Checked) + CHK_Cured.Checked = false; return; + } + Label_PKRS.Visible = CB_PKRSStrain.Visible = CHK_Infected.Checked; - if (!CHK_Infected.Checked) { CB_PKRSStrain.SelectedIndex = 0; CB_PKRSDays.SelectedIndex = 0; Label_PKRSdays.Visible = CB_PKRSDays.Visible = false; } + if (!CHK_Infected.Checked) + { + CB_PKRSStrain.SelectedIndex = 0; + CB_PKRSDays.SelectedIndex = 0; + Label_PKRSdays.Visible = CB_PKRSDays.Visible = false; + } else if (CB_PKRSStrain.SelectedIndex == 0) { CB_PKRSStrain.SelectedIndex = CB_PKRSDays.SelectedIndex = 1; @@ -1650,14 +1658,14 @@ private void ValidateMovePaint(object sender, DrawItemEventArgs e) if (e.Index < 0) return; - var item = (ComboItem)((ComboBox)sender).Items[e.Index]; - var valid = LegalMoveSource.CanLearn(item.Value) && !HaX; + var (text, value) = (ComboItem)((ComboBox)sender).Items[e.Index]; + var valid = LegalMoveSource.CanLearn(value) && !HaX; var current = (e.State & DrawItemState.Selected) == DrawItemState.Selected; var brush = Draw.Brushes.GetBackground(valid, current); var textColor = Draw.GetText(current); - DrawMoveRectangle(e, brush, item.Text, textColor); + DrawMoveRectangle(e, brush, text, textColor); } private static void DrawMoveRectangle(DrawItemEventArgs e, Brush brush, string text, Color textColor) diff --git a/PKHeX.WinForms/Controls/SAV Editor/PartyEditor.cs b/PKHeX.WinForms/Controls/SAV Editor/PartyEditor.cs index 71ad0144c..f8db4fea7 100644 --- a/PKHeX.WinForms/Controls/SAV Editor/PartyEditor.cs +++ b/PKHeX.WinForms/Controls/SAV Editor/PartyEditor.cs @@ -24,13 +24,12 @@ internal bool InitializeGrid() { const int width = 2; const int height = 3; - if (PartyPokeGrid.InitializeGrid(width, height, SpriteUtil.Spriter)) - { - PartyPokeGrid.HorizontallyCenter(this); - InitializeSlots(); - return true; - } - return false; + if (!PartyPokeGrid.InitializeGrid(width, height, SpriteUtil.Spriter)) + return false; + + PartyPokeGrid.HorizontallyCenter(this); + InitializeSlots(); + return true; } private void InitializeSlots() diff --git a/PKHeX.WinForms/Controls/Slots/SlotUtil.cs b/PKHeX.WinForms/Controls/Slots/SlotUtil.cs index 281fde329..b03c7a19d 100644 --- a/PKHeX.WinForms/Controls/Slots/SlotUtil.cs +++ b/PKHeX.WinForms/Controls/Slots/SlotUtil.cs @@ -54,11 +54,12 @@ public static void UpdateSlot(PictureBox pb, ISlotInfo c, PKM p, SaveFile s, boo return; } - var img = c is SlotInfoBox b - ? p.Sprite(s, b.Box, b.Slot, flagIllegal) - : c is SlotInfoParty ps - ? p.Sprite(s, -1, ps.Slot, flagIllegal) - : p.Sprite(s, -1, -1, flagIllegal); + var img = c switch + { + SlotInfoBox b => p.Sprite(s, b.Box, b.Slot, flagIllegal), + SlotInfoParty ps => p.Sprite(s, -1, ps.Slot, flagIllegal), + _ => p.Sprite(s, -1, -1, flagIllegal) + }; pb.BackColor = Color.Transparent; pb.Image = img; diff --git a/PKHeX.WinForms/MainWindow/Main.cs b/PKHeX.WinForms/MainWindow/Main.cs index 22cd14200..e63de0023 100644 --- a/PKHeX.WinForms/MainWindow/Main.cs +++ b/PKHeX.WinForms/MainWindow/Main.cs @@ -244,7 +244,7 @@ private void FormLoadCheckForUpdates() Debug.WriteLine($"Exception while checking for latest version: {ex}"); return; } - if (latestVersion > CurrentProgramVersion) + if (latestVersion is not null && latestVersion > CurrentProgramVersion) Invoke((MethodInvoker)(() => NotifyNewVersionAvailable(latestVersion))); }); } @@ -1108,10 +1108,15 @@ private void Main_DragDrop(object sender, DragEventArgs e) private void Dragout_MouseDown(object sender, MouseEventArgs e) { - if (e.Button == MouseButtons.Left && (ModifierKeys is Keys.Alt or Keys.Shift)) - ClickQR(sender, e); - if (e.Button == MouseButtons.Right) + if (e.Button != MouseButtons.Left) return; + + if (ModifierKeys is Keys.Alt or Keys.Shift) + { + ClickQR(sender, e); + return; + } + if (!PKME_Tabs.EditsComplete) return; diff --git a/PKHeX.WinForms/MainWindow/PluginLoader.cs b/PKHeX.WinForms/MainWindow/PluginLoader.cs index 69ac63574..b7c34c86d 100644 --- a/PKHeX.WinForms/MainWindow/PluginLoader.cs +++ b/PKHeX.WinForms/MainWindow/PluginLoader.cs @@ -44,7 +44,7 @@ private static IEnumerable GetAssemblies(IEnumerable dllFileNa private static IEnumerable GetPluginsOfType(IEnumerable assemblies) { var pluginType = typeof(T); - return assemblies.Where(z => z != null).SelectMany(z => GetPluginTypes(z, pluginType)); + return assemblies.SelectMany(z => GetPluginTypes(z, pluginType)); } private static IEnumerable GetPluginTypes(Assembly z, Type pluginType) diff --git a/PKHeX.WinForms/Subforms/SAV_MysteryGiftDB.cs b/PKHeX.WinForms/Subforms/SAV_MysteryGiftDB.cs index 0a082b91e..39b949e45 100644 --- a/PKHeX.WinForms/Subforms/SAV_MysteryGiftDB.cs +++ b/PKHeX.WinForms/Subforms/SAV_MysteryGiftDB.cs @@ -288,10 +288,12 @@ private void B_Search_Click(object sender, EventArgs e) if (move2 != -1) res = res.Where(mg => mg.HasMove(move2)); if (move3 != -1) res = res.Where(mg => mg.HasMove(move3)); if (move4 != -1) res = res.Where(mg => mg.HasMove(move4)); + if (CHK_Shiny.CheckState == CheckState.Checked) res = res.Where(pk => pk.IsShiny); - if (CHK_Shiny.CheckState == CheckState.Unchecked) res = res.Where(pk => !pk.IsShiny); + else if (CHK_Shiny.CheckState == CheckState.Unchecked) res = res.Where(pk => !pk.IsShiny); + if (CHK_IsEgg.CheckState == CheckState.Checked) res = res.Where(pk => pk.IsEgg); - if (CHK_IsEgg.CheckState == CheckState.Unchecked) res = res.Where(pk => !pk.IsEgg); + else if (CHK_IsEgg.CheckState == CheckState.Unchecked) res = res.Where(pk => !pk.IsEgg); slotSelected = -1; // reset the slot last viewed diff --git a/PKHeX.WinForms/Subforms/Save Editors/Gen7/SAV_Capture7GG.cs b/PKHeX.WinForms/Subforms/Save Editors/Gen7/SAV_Capture7GG.cs index 0ebfb7ecf..8db5b9600 100644 --- a/PKHeX.WinForms/Subforms/Save Editors/Gen7/SAV_Capture7GG.cs +++ b/PKHeX.WinForms/Subforms/Save Editors/Gen7/SAV_Capture7GG.cs @@ -33,8 +33,8 @@ public SAV_Capture7GG(SaveFile sav) var species = GameInfo.SpeciesDataSource.Where(z => list.Contains(z.Value)).ToList(); CB_Species.InitializeBinding(); CB_Species.DataSource = new BindingSource(species, null); - foreach (var entry in species.OrderBy(z => z.Value)) - LB_Species.Items.Add($"{entry.Value:000}: {entry.Text}"); + foreach (var (text, value) in species.OrderBy(z => z.Value)) + LB_Species.Items.Add($"{value:000}: {text}"); GetTotals(); CB_Species.KeyDown += WinFormsUtil.RemoveDropCB; diff --git a/PKHeX.WinForms/Subforms/Save Editors/Gen7/SAV_FestivalPlaza.cs b/PKHeX.WinForms/Subforms/Save Editors/Gen7/SAV_FestivalPlaza.cs index 85cac6c69..c6a782b7f 100644 --- a/PKHeX.WinForms/Subforms/Save Editors/Gen7/SAV_FestivalPlaza.cs +++ b/PKHeX.WinForms/Subforms/Save Editors/Gen7/SAV_FestivalPlaza.cs @@ -12,6 +12,8 @@ public partial class SAV_FestivalPlaza : Form private readonly SaveFile Origin; private readonly SAV7 SAV; + private int entry = -1; + public SAV_FestivalPlaza(SaveFile sav) { InitializeComponent(); @@ -215,8 +217,6 @@ private int TypeIndexToType(int typeIndex) ? RES_FacilityColor[i].Length - 1 : 3; - private int entry = -1; - private void LoadFacility() { editing = true; diff --git a/PKHeX.WinForms/Subforms/Save Editors/SAV_MailBox.cs b/PKHeX.WinForms/Subforms/Save Editors/SAV_MailBox.cs index 37a6033b2..f27ba8220 100644 --- a/PKHeX.WinForms/Subforms/Save Editors/SAV_MailBox.cs +++ b/PKHeX.WinForms/Subforms/Save Editors/SAV_MailBox.cs @@ -423,12 +423,8 @@ private void B_Save_Click(object sender, EventArgs e) private string GetSpeciesNameFromCB(int index) { - foreach (var i in CB_AppearPKM1.Items.OfType()) - { - if (index == i.Value) - return i.Text; - } - return "PKM"; + var result = CB_AppearPKM1.Items.OfType().FirstOrDefault(z => z.Value == index); + return result != null ? result.Text : "PKM"; } private DialogResult ModifyHeldItem() diff --git a/PKHeX.WinForms/Subforms/Save Editors/SAV_Wondercard.cs b/PKHeX.WinForms/Subforms/Save Editors/SAV_Wondercard.cs index 87258b20c..3caac982a 100644 --- a/PKHeX.WinForms/Subforms/Save Editors/SAV_Wondercard.cs +++ b/PKHeX.WinForms/Subforms/Save Editors/SAV_Wondercard.cs @@ -264,22 +264,20 @@ private void ClearReceivedFlag(object sender, EventArgs e) if (LB_Received.SelectedIndex < 0) return; - if (LB_Received.SelectedIndices.Count > 1) { - for (int i = LB_Received.SelectedIndices.Count - 1; i >= 0; i--) { + if (LB_Received.SelectedIndices.Count > 1) + { + for (int i = LB_Received.SelectedIndices.Count - 1; i >= 0; i--) LB_Received.Items.RemoveAt(LB_Received.SelectedIndices[i]); - } } - else if (LB_Received.SelectedIndices.Count == 1) { + else if (LB_Received.SelectedIndices.Count == 1) + { int lastIndex = LB_Received.SelectedIndex; - LB_Received.Items.RemoveAt(LB_Received.SelectedIndex); - if (LB_Received.Items.Count > 0) { - if (lastIndex > LB_Received.Items.Count - 1) { - LB_Received.SelectedIndex = lastIndex - 1; - } - else { - LB_Received.SelectedIndex = lastIndex; - } - } + LB_Received.Items.RemoveAt(lastIndex); + if (LB_Received.Items.Count == 0) + return; + if (lastIndex == LB_Received.Items.Count) + lastIndex--; + LB_Received.SelectedIndex = lastIndex; } } @@ -629,23 +627,22 @@ private void B_ModifyAll_Click(object sender, EventArgs e) private void LB_Received_KeyDown(object sender, KeyEventArgs e) { - if (e.KeyCode == Keys.Delete) { - if (LB_Received.SelectedIndices.Count > 1) { - for (int i = LB_Received.SelectedIndices.Count - 1; i >= 0; i--) { + if (e.KeyCode == Keys.Delete) + { + if (LB_Received.SelectedIndices.Count > 1) + { + for (int i = LB_Received.SelectedIndices.Count - 1; i >= 0; i--) LB_Received.Items.RemoveAt(LB_Received.SelectedIndices[i]); - } } - else if (LB_Received.SelectedIndices.Count == 1) { + else if (LB_Received.SelectedIndices.Count == 1) + { int lastIndex = LB_Received.SelectedIndex; - LB_Received.Items.RemoveAt(LB_Received.SelectedIndex); - if (LB_Received.Items.Count > 0) { - if (lastIndex > LB_Received.Items.Count - 1) { - LB_Received.SelectedIndex = lastIndex - 1; - } - else { - LB_Received.SelectedIndex = lastIndex; - } - } + LB_Received.Items.RemoveAt(lastIndex); + if (LB_Received.Items.Count == 0) + return; + if (lastIndex == LB_Received.Items.Count) + lastIndex--; + LB_Received.SelectedIndex = lastIndex; } } } diff --git a/PKHeX.WinForms/Subforms/Save Editors/TrainerStat.cs b/PKHeX.WinForms/Subforms/Save Editors/TrainerStat.cs index a2b63db2e..573cb1cd9 100644 --- a/PKHeX.WinForms/Subforms/Save Editors/TrainerStat.cs +++ b/PKHeX.WinForms/Subforms/Save Editors/TrainerStat.cs @@ -26,12 +26,12 @@ public void LoadRecords(ITrainerStatRecord sav, Dictionary records) CB_Stats.Items.Clear(); for (int i = 0; i < sav.RecordCount; i++) { - if (!RecordList.TryGetValue(i, out var name)) + if (!records.TryGetValue(i, out var name)) name = $"{i:D3}"; - CB_Stats.Items.Add(name); + CB_Stats.Items.Add(name!); } - CB_Stats.SelectedIndex = RecordList.First().Key; + CB_Stats.SelectedIndex = records.First().Key; } private void ChangeStat(object sender, EventArgs e) diff --git a/Tests/PKHeX.Core.Tests/Saves/MemeCrypto/MemeCryptoTests.cs b/Tests/PKHeX.Core.Tests/Saves/MemeCrypto/MemeCryptoTests.cs index d5ffa1745..1b5f3ceb5 100644 --- a/Tests/PKHeX.Core.Tests/Saves/MemeCrypto/MemeCryptoTests.cs +++ b/Tests/PKHeX.Core.Tests/Saves/MemeCrypto/MemeCryptoTests.cs @@ -13,7 +13,7 @@ public void TestVerifySaveSignature() var savebuffer = "58EA53A7133F34DA9F2BEC12F1560354E8BDF8A484ADE4E2954D3C48673118EB67E2D52ED0196E54DC5D93013E9F3B00C8A43B556AEE8C2F763EA9DC125988C6B5F2D3C74CA2C58026BB024B403D09BC5950C54CEB6F21E45D0B66B68791BCBB6D7E67C2F7E4A7F4A517FC50B4FEED9A65BF901ABEB0FFAC44AE07237BE5DD2D" .ToByteArray(); - Assert.True(MemeCrypto.VerifyMemeData(savebuffer, out var _)); + Assert.True(MemeCrypto.VerifyMemeData(savebuffer, out _)); } [Fact] @@ -78,8 +78,8 @@ public void TestVerifyPoke() "A96E2D8D9B99DBFB934939C097E3AC101C7D48CEC52FCA717B14B19890208592045C430035DD09A31446142E9EA33CF3E6B6E69484B6D2EED500B8389048013491602403DBE7B814EA069667CFADAFE74895217D78037B4A456FAB2CAFD71E690000504F4B4509000000000000" .ToByteArray(); - Assert.True(MemeCrypto.VerifyMemePOKE(vector, out var _)); - Assert.True(MemeCrypto.VerifyMemePOKE(vector2, out var _)); + Assert.True(MemeCrypto.VerifyMemePOKE(vector, out _)); + Assert.True(MemeCrypto.VerifyMemePOKE(vector2, out _)); } public static IEnumerable KnownKeys() @@ -105,7 +105,7 @@ public static IEnumerable KnownKeys() [MemberData(nameof(KnownKeys))] public void TestVerifyKnownKeys(MemeKeyIndex keyIndex, byte[] key) { - MemeCrypto.VerifyMemeData(key, out var _, keyIndex).Should().BeTrue("becuase they key should be valid"); + MemeCrypto.VerifyMemeData(key, out _, keyIndex).Should().BeTrue("because they key should be valid"); } } }