Minor clean

Annotations (nullable), some switch cases for readability
This commit is contained in:
Kurt 2021-03-14 16:16:55 -07:00
parent 4f6258e492
commit 6bce4eea14
51 changed files with 285 additions and 255 deletions

View file

@ -29,7 +29,7 @@ namespace PKHeX.Core
/// </summary>
/// <param name="type">Manipulation type.</param>
/// <returns>Reference to <see cref="IBoxManip"/>.</returns>
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);
/// <summary>
/// Gets the corresponding name from <see cref="ManipCategoryNames"/> for the requested <see cref="type"/>.

View file

@ -20,18 +20,20 @@ namespace PKHeX.Core
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;
}
var indexString = l.Substring(1);
if (int.TryParse(indexString, out index))
return true;
Debug.WriteLine($"Rejected line due to bad index: {indexString}");
return false;
}
/// <summary>

View file

@ -19,7 +19,12 @@ namespace PKHeX.Core
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)

View file

@ -50,7 +50,12 @@ namespace PKHeX.Core
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);
}
}

View file

@ -12,12 +12,13 @@ namespace PKHeX.Core
/// <returns>Unpacked array containing all files that were packed.</returns>
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][];

View file

@ -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()

View file

@ -26,7 +26,7 @@ namespace PKHeX.Core
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;

View file

@ -21,7 +21,7 @@ namespace PKHeX.Core
{
public static class EncounterSlotGenerator
{
public static IEnumerable<EncounterSlot> GetPossible(PKM pkm, IReadOnlyList<DexLevel> chain, GameVersion gameSource = GameVersion.Any)
public static IEnumerable<EncounterSlot> GetPossible(PKM pkm, IReadOnlyList<DexLevel> 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 @@ namespace PKHeX.Core
}
}
public static IEnumerable<EncounterSlot> GetValidWildEncounters34(PKM pkm, IReadOnlyList<EvoCriteria> chain, GameVersion gameSource = GameVersion.Any)
public static IEnumerable<EncounterSlot> GetValidWildEncounters34(PKM pkm, IReadOnlyList<EvoCriteria> 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 @@ namespace PKHeX.Core
return slots; // defer deferrals to the method consuming this collection
}
public static IEnumerable<EncounterSlot> GetValidWildEncounters12(PKM pkm, IReadOnlyList<EvoCriteria> chain, GameVersion gameSource = GameVersion.Any)
public static IEnumerable<EncounterSlot> GetValidWildEncounters12(PKM pkm, IReadOnlyList<EvoCriteria> chain, GameVersion gameSource = Any)
{
if (gameSource == GameVersion.Any)
if (gameSource == Any)
gameSource = (GameVersion)pkm.Version;
return GetRawEncounterSlots(pkm, chain, gameSource);
}
public static IEnumerable<EncounterSlot> GetValidWildEncounters(PKM pkm, IReadOnlyList<EvoCriteria> chain, GameVersion gameSource = GameVersion.Any)
public static IEnumerable<EncounterSlot> GetValidWildEncounters(PKM pkm, IReadOnlyList<EvoCriteria> chain, GameVersion gameSource = Any)
{
if (gameSource == GameVersion.Any)
if (gameSource == Any)
gameSource = (GameVersion)pkm.Version;
return GetRawEncounterSlots(pkm, chain, gameSource);
}
public static IEnumerable<EncounterArea> GetEncounterSlots(PKM pkm, GameVersion gameSource = GameVersion.Any)
public static IEnumerable<EncounterArea> GetEncounterSlots(PKM pkm, GameVersion gameSource = Any)
{
if (gameSource == GameVersion.Any)
if (gameSource == Any)
gameSource = (GameVersion)pkm.Version;
return GetEncounterTable(pkm, gameSource);
}
private static IEnumerable<EncounterArea> GetEncounterAreas(PKM pkm, GameVersion gameSource = GameVersion.Any)
private static IEnumerable<EncounterArea> 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;

View file

@ -194,7 +194,7 @@ namespace PKHeX.Core
public List<EvoCriteria> 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<EvoCriteria>(1)

View file

@ -11,8 +11,9 @@ namespace PKHeX.Core
if (pkm.IsEgg && pkm.Format <= 5) // pre relearn
return MoveList.GetBaseEggMoves(pkm, pkm.Species, 0, (GameVersion)pkm.Version, pkm.CurrentLevel);
if (types == MoveSourceType.None)
{
if (types != MoveSourceType.None)
return GetValidMoves(pkm, evoChains, types).Skip(1).ToArray(); // skip move 0
// try to give current moves
if (enc.Generation <= 2)
{
@ -25,7 +26,6 @@ namespace PKHeX.Core
{
return MoveLevelUp.GetEncounterMoves(pkm.Species, pkm.Form, pkm.CurrentLevel, (GameVersion)pkm.Version);
}
}
return GetValidMoves(pkm, evoChains, types).Skip(1).ToArray(); // skip move 0
}

View file

@ -144,30 +144,28 @@ namespace PKHeX.Core
return proc < 60;
if (frameType == FrameType.MethodH)
return true; // fishing encounters are disjointed by the hooked message.
return GetCanEncounterFish(lead, stype, proc);
}
// fishing
if (stype == SlotType.Old_Rod)
private static bool GetCanEncounterFish(LeadRequired lead, SlotType stype, int proc) => stype switch
{
if (proc < 25)
return true;
if (proc < 50)
return lead == LeadRequired.None;
}
else if (stype == SlotType.Good_Rod)
// Lead:None => can be suction cups
SlotType.Old_Rod => proc switch
{
if (proc < 50)
return true;
if (proc < 75)
return lead == LeadRequired.None;
}
else if (stype == SlotType.Super_Rod)
< 25 => true,
< 50 => lead == LeadRequired.None,
_ => false
},
SlotType.Good_Rod => proc switch
{
if (proc < 75)
return true;
return lead == LeadRequired.None; // < 100 always true
}
return false; // shouldn't hit here
}
< 50 => true,
< 75 => lead == LeadRequired.None,
_ => false
},
SlotType.Super_Rod => proc < 75 || lead == LeadRequired.None,
_ => false
};
/// <summary>
/// Checks both Static and Magnet Pull ability type selection encounters to see if the encounter can be selected.

View file

@ -203,7 +203,7 @@ namespace PKHeX.Core
while (true)
{
var seed = Util.Rand32();
if (!MethodFinder.IsPokeSpotActivation(slot, seed, out var _))
if (!MethodFinder.IsPokeSpotActivation(slot, seed, out _))
continue;
var rng = RNG.XDRNG;

View file

@ -102,13 +102,12 @@ namespace PKHeX.Core
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;

View file

@ -122,11 +122,6 @@ namespace PKHeX.Core
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

View file

@ -63,21 +63,26 @@ namespace PKHeX.Core
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)
{
result.Add($"Bean ID: {gift.Bean}");
result.Add($"Quantity: {gift.Quantity}");
}
else { result.Add(MsgMysteryGiftParseTypeUnknown); }
if (gift is WC7 w7)
switch (gift)
{
case WC7 w7:
result.Add($"Repeatable: {w7.GiftRepeatable}");
result.Add($"Collected: {w7.GiftUsed}");
result.Add($"Once Per Day: {w7.GiftOncePerDay}");
break;
}
return result;
}

View file

@ -114,12 +114,12 @@ namespace PKHeX.Core
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; } }

View file

@ -719,18 +719,13 @@ namespace PKHeX.Core
/// Gets the IV Judge Rating value.
/// </summary>
/// <remarks>IV Judge scales his response 0 (worst) to 3 (best).</remarks>
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
};
/// <summary>
/// Gets the current Battle Stats.

View file

@ -24,12 +24,13 @@ namespace PKHeX.Core.Searching
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<PKM> FilterByGeneration(IEnumerable<PKM> res, int generation) => generation switch

View file

@ -96,13 +96,13 @@ namespace PKHeX.Core
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 { }
}

View file

@ -439,6 +439,9 @@ namespace PKHeX.Core
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);
}
}

View file

@ -94,7 +94,7 @@ namespace PKHeX.Core
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

View file

@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PKHeX.Core
{

View file

@ -25,6 +25,7 @@ namespace PKHeX.Core
protected override SAV4 CloneInternal4() => State.Exportable ? new SAV4DP(Data) : new SAV4DP();
public override PersonalTable Personal => PersonalTable.DP;
public override IReadOnlyList<ushort> 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

View file

@ -25,6 +25,7 @@ namespace PKHeX.Core
public override PersonalTable Personal => PersonalTable.HGSS;
public override IReadOnlyList<ushort> 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?

View file

@ -23,6 +23,7 @@ namespace PKHeX.Core
protected override SAV4 CloneInternal4() => State.Exportable ? new SAV4Pt(Data) : new SAV4Pt();
public override PersonalTable Personal => PersonalTable.Pt;
public override IReadOnlyList<ushort> 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

View file

@ -295,11 +295,10 @@ namespace PKHeX.Core
{
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 @@ namespace PKHeX.Core
{
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);

View file

@ -27,21 +27,23 @@ namespace PKHeX.Core
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;

View file

@ -17,5 +17,5 @@ namespace PKHeX.Core
Black = 12,
White = 13,
Gold = 14,
};
}
}

View file

@ -21,10 +21,8 @@ namespace PKHeX.Core
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);

View file

@ -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<string> GetPSSParse(SAV6 SAV)
{

View file

@ -42,13 +42,17 @@ namespace PKHeX.Core
public override int GetRecord(int recordID)
{
int ofs = Records.GetOffset(Offset, recordID);
if (recordID < 100)
switch (recordID)
{
case < 100:
return BitConverter.ToInt32(Data, ofs);
if (recordID < 200)
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 @@ namespace PKHeX.Core
int max = GetRecordMax(recordID);
if (value > max)
value = max;
if (recordID < 100)
switch (recordID)
{
case < 100:
BitConverter.GetBytes(value).CopyTo(Data, ofs);
else if (recordID < 200)
break;
case < 200:
BitConverter.GetBytes((ushort)value).CopyTo(Data, ofs);
else
break;
default:
Trace.Fail(nameof(recordID));
break;
}
}
}
}

View file

@ -219,12 +219,14 @@ namespace PKHeX.Core
public bool IsValidItemAndCount(ITrainerInfo sav, int item, bool HasNew, bool HaX, ref int count)
{
if (HaX && sav.Generation != 7) // Gen7 has true cap at 1023, keep 999 cap.
{
count = sav.Generation switch
{
// 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;
<= 2 when count > byte.MaxValue => byte.MaxValue,
>= 3 when count > ushort.MaxValue => ushort.MaxValue,
_ => count
};
return true;
}

View file

@ -46,15 +46,12 @@ namespace PKHeX.Core
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);

View file

@ -279,9 +279,7 @@ namespace PKHeX.Core
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;

View file

@ -24,14 +24,12 @@ namespace PKHeX.Core
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};

View file

@ -12,6 +12,9 @@ namespace PKHeX.Core
try
{
var stream = GetStreamFromURL(url);
if (stream == null)
return null;
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
@ -25,7 +28,7 @@ namespace PKHeX.Core
}
}
private static Stream GetStreamFromURL(string url)
private static Stream? GetStreamFromURL(string url)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

View file

@ -159,6 +159,8 @@ namespace PKHeX.Core
public static byte[] GetBinaryResource(string name)
{
using var resource = thisAssembly.GetManifestResourceStream($"PKHeX.Core.Resources.byte.{name}");
if (resource is null)
return Array.Empty<byte>();
var buffer = new byte[resource.Length];
resource.Read(buffer, 0, (int)resource.Length);
return buffer;
@ -176,7 +178,7 @@ namespace PKHeX.Core
}
using var resource = thisAssembly.GetManifestResourceStream(resourceName);
if (resource == null)
if (resource is null)
return null;
using var reader = new StreamReader(resource);
return reader.ReadToEnd();

View file

@ -15,7 +15,7 @@ namespace PKHeX.Core
{
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

View file

@ -11,12 +11,16 @@ namespace PKHeX.Core
{
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 @@ namespace PKHeX.Core
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);

View file

@ -1132,12 +1132,20 @@ namespace PKHeX.WinForms.Controls
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 @@ namespace PKHeX.WinForms.Controls
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)

View file

@ -24,14 +24,13 @@ namespace PKHeX.WinForms.Controls
{
const int width = 2;
const int height = 3;
if (PartyPokeGrid.InitializeGrid(width, height, SpriteUtil.Spriter))
{
if (!PartyPokeGrid.InitializeGrid(width, height, SpriteUtil.Spriter))
return false;
PartyPokeGrid.HorizontallyCenter(this);
InitializeSlots();
return true;
}
return false;
}
private void InitializeSlots()
{

View file

@ -54,11 +54,12 @@ namespace PKHeX.WinForms.Controls
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;

View file

@ -244,7 +244,7 @@ namespace PKHeX.WinForms
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 @@ namespace PKHeX.WinForms
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;

View file

@ -44,7 +44,7 @@ namespace PKHeX.WinForms
private static IEnumerable<Type> GetPluginsOfType<T>(IEnumerable<Assembly> 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<Type> GetPluginTypes(Assembly z, Type pluginType)

View file

@ -288,10 +288,12 @@ namespace PKHeX.WinForms
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

View file

@ -33,8 +33,8 @@ namespace PKHeX.WinForms
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;

View file

@ -12,6 +12,8 @@ namespace PKHeX.WinForms
private readonly SaveFile Origin;
private readonly SAV7 SAV;
private int entry = -1;
public SAV_FestivalPlaza(SaveFile sav)
{
InitializeComponent();
@ -215,8 +217,6 @@ namespace PKHeX.WinForms
? RES_FacilityColor[i].Length - 1
: 3;
private int entry = -1;
private void LoadFacility()
{
editing = true;

View file

@ -423,12 +423,8 @@ namespace PKHeX.WinForms
private string GetSpeciesNameFromCB(int index)
{
foreach (var i in CB_AppearPKM1.Items.OfType<ComboItem>())
{
if (index == i.Value)
return i.Text;
}
return "PKM";
var result = CB_AppearPKM1.Items.OfType<ComboItem>().FirstOrDefault(z => z.Value == index);
return result != null ? result.Text : "PKM";
}
private DialogResult ModifyHeldItem()

View file

@ -264,24 +264,22 @@ namespace PKHeX.WinForms
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.Items.RemoveAt(lastIndex);
if (LB_Received.Items.Count == 0)
return;
if (lastIndex == LB_Received.Items.Count)
lastIndex--;
LB_Received.SelectedIndex = lastIndex;
}
}
}
}
// Drag & Drop Wonder Cards
private static void Main_DragEnter(object sender, DragEventArgs e)
@ -629,25 +627,24 @@ namespace PKHeX.WinForms
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.Items.RemoveAt(lastIndex);
if (LB_Received.Items.Count == 0)
return;
if (lastIndex == LB_Received.Items.Count)
lastIndex--;
LB_Received.SelectedIndex = lastIndex;
}
}
}
}
}
}
}

View file

@ -26,12 +26,12 @@ namespace PKHeX.WinForms.Subforms.Save_Editors
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)

View file

@ -13,7 +13,7 @@ namespace PKHeX.Tests.Saves
var savebuffer =
"58EA53A7133F34DA9F2BEC12F1560354E8BDF8A484ADE4E2954D3C48673118EB67E2D52ED0196E54DC5D93013E9F3B00C8A43B556AEE8C2F763EA9DC125988C6B5F2D3C74CA2C58026BB024B403D09BC5950C54CEB6F21E45D0B66B68791BCBB6D7E67C2F7E4A7F4A517FC50B4FEED9A65BF901ABEB0FFAC44AE07237BE5DD2D"
.ToByteArray();
Assert.True(MemeCrypto.VerifyMemeData(savebuffer, out var _));
Assert.True(MemeCrypto.VerifyMemeData(savebuffer, out _));
}
[Fact]
@ -78,8 +78,8 @@ namespace PKHeX.Tests.Saves
"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<object[]> KnownKeys()
@ -105,7 +105,7 @@ namespace PKHeX.Tests.Saves
[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");
}
}
}