diff --git a/AutoLegalityMod/APILegality.cs b/AutoLegalityMod/APILegality.cs index 6f57c95d..cb54dd8f 100644 --- a/AutoLegalityMod/APILegality.cs +++ b/AutoLegalityMod/APILegality.cs @@ -127,12 +127,13 @@ public static void ValidateGender(PKM pkm) if (genderValid) return; + + if (pkm.Gender == 0) + pkm.Gender = 1; + else if (pkm.Gender == 1) + pkm.Gender = 0; else - { - if (pkm.Gender == 0) pkm.Gender = 1; - else if (pkm.Gender == 1) pkm.Gender = 0; - else pkm.GetSaneGender(); - } + pkm.GetSaneGender(); } /// @@ -178,13 +179,14 @@ public static bool FixFormes(ShowdownSet SSet, out ShowdownSet changedSet) /// /// PKM to modify /// SSet to modify + /// Form to modify public static void SetSpeciesLevel(PKM pk, ShowdownSet SSet, int Form) { pk.Species = SSet.Species; if (SSet.Gender != null) pk.Gender = (SSet.Gender == "M") ? 0 : 1; pk.SetAltForm(Form); pk.IsNicknamed = (SSet.Nickname != null); - pk.Nickname = SSet.Nickname != null ? SSet.Nickname : PKX.GetSpeciesNameGeneration(pk.Species, pk.Language, SAV.Generation); + pk.Nickname = SSet.Nickname ?? PKX.GetSpeciesNameGeneration(pk.Species, pk.Language, SAV.Generation); pk.CurrentLevel = SSet.Level; if (pk.CurrentLevel == 50) pk.CurrentLevel = 100; // VGC Override } @@ -296,6 +298,9 @@ public static void SetShinyBoolean(PKM pk, bool isShiny) /// /// /// + /// + /// + /// public static void SetIVsPID(PKM pk, ShowdownSet SSet, PIDType Method, int HPType, PKM originalPKMN) { // Useful Values for computation @@ -307,8 +312,8 @@ public static void SetIVsPID(PKM pk, ShowdownSet SSet, PIDType Method, int HPTyp // Find the encounter LegalInfo li = EncounterFinder.FindVerifiedEncounter(originalPKMN); - var property = li.EncounterMatch.GetType().GetProperty("PIDType"); - // TODO: Something about the gen 5 events. Maybe check for nature and shiny val and not touch the PID in that case? + var property = li.EncounterMatch.GetType().GetProperty("PIDType"); + // TODO: Something about the gen 5 events. Maybe check for nature and shiny val and not touch the PID in that case? // Also need to figure out hidden power handling in that case.. for PIDType 0 that may isn't even be possible. if (pk.GenNumber > 4 || pk.VC) @@ -354,6 +359,7 @@ public static PKM DebugReturn(PKM pk, out bool satisfied, int OptionalGame = -1) /// PKM to modify /// Given Method /// HPType INT for preserving Hidden powers + /// public static void FindPIDIV(PKM pk, PIDType Method, int HPType, PKM originalPKMN) { if (Method == PIDType.None) @@ -363,7 +369,7 @@ public static void FindPIDIV(PKM pk, PIDType Method, int HPType, PKM originalPKM if (Method == PIDType.None) pk.PID = PKX.GetRandomPID(pk.Species, pk.Gender, pk.Version, pk.Nature, pk.Format, (uint)(pk.AbilityNumber * 0x10001)); } PKM iterPKM = pk; - while (true && Method != PIDType.None) + while (Method != PIDType.None) { uint seed = Util.Rand32(); PIDGenerator.SetValuesFromSeed(pk, Method, seed); @@ -383,9 +389,9 @@ public static void FindPIDIV(PKM pk, PIDType Method, int HPType, PKM originalPKM public static PIDType FindLikelyPIDType(PKM pk, PKM pkmn) { BruteForce b = new BruteForce(); - if (b.usesEventBasedMethod(pk.Species, pk.Moves, "BACD_R")) + if (b.UsesEventBasedMethod(pk.Species, pk.Moves, "BACD_R")) return PIDType.BACD_R; - if (b.usesEventBasedMethod(pk.Species, pk.Moves, "M2")) return PIDType.Method_2; + if (b.UsesEventBasedMethod(pk.Species, pk.Moves, "M2")) return PIDType.Method_2; if (pk.Species == 490 && pk.Gen4) { pk.Egg_Location = 2002; @@ -451,7 +457,10 @@ public static void SetEncryptionConstant(PKM pk) uint EC = wIndex < 0 ? Util.Rand32() : PKX.GetWurmpleEC(wIndex / 2); if (!(pk.Species == 658 && pk.AltForm == 1)) pk.EncryptionConstant = EC; } - else pk.EncryptionConstant = pk.PID; // Generations 3 to 5 + else + { + pk.EncryptionConstant = pk.PID; // Generations 3 to 5 + } } /// diff --git a/AutoLegalityMod/ArchitMod.cs b/AutoLegalityMod/ArchitMod.cs index 6fcd35f6..895b2b2d 100644 --- a/AutoLegalityMod/ArchitMod.cs +++ b/AutoLegalityMod/ArchitMod.cs @@ -16,13 +16,8 @@ public partial class AutoLegalityMod /// byte array public static void PrintByteArray(byte[] bytes) { - var sb = new System.Text.StringBuilder("new byte[] { "); - foreach (var b in bytes) - { - sb.Append(b + ", "); - } - sb.Append("}"); - Console.WriteLine(sb.ToString()); + var str = $"new byte[] {{ {string.Join(", ", bytes)} }}"; + Console.WriteLine(str); } /// @@ -31,11 +26,12 @@ public static void PrintByteArray(byte[] bytes) /// String denoting the exact country /// String denoting the exact sub region /// String denoting the exact console region + /// public static void SetRegions(string Country, string SubRegion, string ConsoleRegion, PKM pk) { - pk.Country = Util.GetCBList("countries", "en").FirstOrDefault(z => z.Text == Country).Value; - pk.Region = Util.GetCBList($"sr_{pk.Country:000}", "en").FirstOrDefault(z => z.Text == SubRegion).Value; - pk.ConsoleRegion = Util.GetUnsortedCBList("regions3ds").FirstOrDefault(z => z.Text == ConsoleRegion).Value; + pk.Country = Util.GetCBList("countries", "en").Find(z => z.Text == Country).Value; + pk.Region = Util.GetCBList($"sr_{pk.Country:000}", "en").Find(z => z.Text == SubRegion).Value; + pk.ConsoleRegion = Util.GetUnsortedCBList("regions3ds").Find(z => z.Text == ConsoleRegion).Value; } /// @@ -60,7 +56,9 @@ public static PKM SetPKMRegions(int Country, int SubRegion, int ConsoleRegion, P /// string value of OT name /// INT value of TID /// INT value of SID + /// /// + /// /// public static PKM SetTrainerData(string OT, int TID, int SID, int gender, PKM pk, bool APILegalized = false) { @@ -88,7 +86,7 @@ public static PKM SetTrainerData(string OT, int TID, int SID, int gender, PKM pk /// /// string form of trainerdata.json /// - public static string checkMode(string jsonstring = "") + public static string CheckMode(string jsonstring = "") { if(jsonstring != "") { @@ -99,12 +97,15 @@ public static string checkMode(string jsonstring = "") } else { - if (!System.IO.File.Exists(Directory.GetCurrentDirectory() + "\\trainerdata.json")) + if (!File.Exists(Directory.GetCurrentDirectory() + "\\trainerdata.json")) { return "save"; // Default trainerdata.txt handling } - jsonstring = System.IO.File.ReadAllText(Directory.GetCurrentDirectory() + "\\trainerdata.json", System.Text.Encoding.UTF8); - if (jsonstring != "") return checkMode(jsonstring); + jsonstring = File.ReadAllText(Directory.GetCurrentDirectory() + "\\trainerdata.json", System.Text.Encoding.UTF8); + if (jsonstring != "") + { + return CheckMode(jsonstring); + } else { MessageBox.Show("Empty trainerdata.json file", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information); @@ -120,10 +121,10 @@ public static string checkMode(string jsonstring = "") /// int value of the game /// internal json: trainerdata[Game] /// - public static bool checkIfGameExists(string jsonstring, int Game, out string jsonvalue) + public static bool CheckIfGameExists(string jsonstring, int Game, out string jsonvalue) { jsonvalue = ""; - if (checkMode(jsonstring) == "auto") + if (CheckMode(jsonstring) == "auto") { jsonvalue = "auto"; return false; @@ -147,7 +148,7 @@ public static bool checkIfGameExists(string jsonstring, int Game, out string jso /// /// /// - public static string getValueFromKey(string key, string finaljson) + public static string GetValueFromKey(string key, string finaljson) { return finaljson.Split(new string[] { key }, StringSplitOptions.None)[1].Split('"')[2].Trim(); } @@ -160,7 +161,7 @@ public static string getValueFromKey(string key, string finaljson) /// public static int[] ConvertTIDSID7toTIDSID(int tid7, int sid7) { - var repack = (long)sid7 * 1_000_000 + tid7; + var repack = ((long)sid7 * 1_000_000) + tid7; int sid = (ushort)(repack >> 16); int tid = (ushort)repack; return new int[] { tid, sid }; @@ -172,22 +173,22 @@ public static int[] ConvertTIDSID7toTIDSID(int tid7, int sid7) /// Current Save Editor /// optional Game value in case of mode being game /// - public static string[] parseTrainerJSON(SaveFile C_SAV, int Game = -1) + public static string[] ParseTrainerJSON(SaveFile C_SAV, int Game = -1) { if (!File.Exists(Directory.GetCurrentDirectory() + "\\trainerdata.json")) { - return parseTrainerData(C_SAV); // Default trainerdata.txt handling + return ParseTrainerData(); // Default trainerdata.txt handling } - string jsonstring = System.IO.File.ReadAllText(Directory.GetCurrentDirectory() + "\\trainerdata.json", System.Text.Encoding.UTF8); - if (Game == -1) Game = C_SAV.Game; - if(!checkIfGameExists(jsonstring, Game, out string finaljson)) return parseTrainerData(C_SAV, finaljson == "auto"); - string TID = getValueFromKey("TID", finaljson); - string SID = getValueFromKey("SID", finaljson); - string OT = getValueFromKey("OT", finaljson); - string Gender = getValueFromKey("Gender", finaljson); - string Country = getValueFromKey("Country", finaljson); - string SubRegion = getValueFromKey("SubRegion", finaljson); - string ConsoleRegion = getValueFromKey("3DSRegion", finaljson); + string jsonstring = File.ReadAllText(Directory.GetCurrentDirectory() + "\\trainerdata.json", System.Text.Encoding.UTF8); + if (Game == -1) Game = C_SAV.Game; + if(!CheckIfGameExists(jsonstring, Game, out string finaljson)) return ParseTrainerData(finaljson == "auto"); + string TID = GetValueFromKey("TID", finaljson); + string SID = GetValueFromKey("SID", finaljson); + string OT = GetValueFromKey("OT", finaljson); + string Gender = GetValueFromKey("Gender", finaljson); + string Country = GetValueFromKey("Country", finaljson); + string SubRegion = GetValueFromKey("SubRegion", finaljson); + string ConsoleRegion = GetValueFromKey("3DSRegion", finaljson); if (TID.Length == 6 && SID.Length == 4) { if(new List { 33, 32, 31, 30 }.IndexOf(Game) == -1) MessageBox.Show("Force Converting G7TID/G7SID to TID/SID", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information); @@ -201,9 +202,9 @@ public static string[] parseTrainerJSON(SaveFile C_SAV, int Game = -1) /// /// Parser for auto and preset trainerdata.txt files /// - /// SAVEditor of the current save file + /// /// - public static string[] parseTrainerData(SaveFile C_SAV, bool auto = false) + public static string[] ParseTrainerData(bool auto = false) { // Defaults string TID = "23456"; @@ -219,12 +220,12 @@ public static string[] parseTrainerData(SaveFile C_SAV, bool auto = false) } string[] trainerdataLines = File.ReadAllText(Directory.GetCurrentDirectory() + "\\trainerdata.txt", System.Text.Encoding.UTF8) .Split(new string[] { Environment.NewLine }, StringSplitOptions.None); - List lstlines = trainerdataLines.OfType().ToList(); + List lstlines = trainerdataLines.Where(f => f != null).ToList(); int count = lstlines.Count; for (int i =0; i < count; i++) { string item = lstlines[0]; - if (item.TrimEnd() == "" || item.TrimEnd() == "auto") continue; + if (item.TrimEnd().Length == 0 || item.TrimEnd() == "auto") continue; string key = item.Split(':')[0].TrimEnd(); string value = item.Split(':')[1].TrimEnd(); lstlines.RemoveAt(0); @@ -263,7 +264,5 @@ public static string[] parseTrainerData(SaveFile C_SAV, bool auto = false) } return new string[] { TID, SID, OT, Gender, Country, SubRegion, ConsoleRegion }; } - } - } diff --git a/AutoLegalityMod/AutoLegalityMod.cs b/AutoLegalityMod/AutoLegalityMod.cs index cb76cb10..995a18ea 100644 --- a/AutoLegalityMod/AutoLegalityMod.cs +++ b/AutoLegalityMod/AutoLegalityMod.cs @@ -6,7 +6,6 @@ namespace AutoLegalityMod { public partial class AutoLegalityMod : IPlugin { - /// /// Main Plugin Variables /// @@ -53,7 +52,7 @@ private void AddPluginControl(ToolStripDropDownItem modmenu) { var ctrl = new ToolStripMenuItem(Name); modmenu.DropDownItems.Add(ctrl); - ctrl.Click += new EventHandler(ClickShowdownImportPKMModded); + ctrl.Click += ClickShowdownImportPKMModded; ctrl.Name = "Menu_AutoLegalityMod"; ctrl.Image = AutoLegalityResources.autolegalitymod; ctrl.ShortcutKeys = (Keys.Control | Keys.I); @@ -83,6 +82,5 @@ public void ClickShowdownImportPKMModded(object sender, EventArgs e) AutomaticLegality.SaveFileEditor = SaveFileEditor; AutomaticLegality.ImportModded(); } - } } diff --git a/AutoLegalityMod/AutoLegalityMod.csproj b/AutoLegalityMod/AutoLegalityMod.csproj index 238f1e25..8beb63ed 100644 --- a/AutoLegalityMod/AutoLegalityMod.csproj +++ b/AutoLegalityMod/AutoLegalityMod.csproj @@ -37,12 +37,6 @@ - - - - - - diff --git a/AutoLegalityMod/AutomaticLegality.cs b/AutoLegalityMod/AutomaticLegality.cs index 4f3d154d..e46aafac 100644 --- a/AutoLegalityMod/AutomaticLegality.cs +++ b/AutoLegalityMod/AutomaticLegality.cs @@ -10,7 +10,7 @@ namespace AutoLegalityMod { - public class AutomaticLegality + public static class AutomaticLegality { public static ISaveFileProvider SaveFileEditor { get; set; } public static IPKMView PKMEditor { get; set; } @@ -19,30 +19,33 @@ public class AutomaticLegality /// /// Global Variables for Auto Legality Mod /// - static int TID_ALM = -1; - static int SID_ALM = -1; - static string OT_ALM = ""; - static int gender_ALM = 0; - static string Country_ALM = ""; - static string SubRegion_ALM = ""; - static string ConsoleRegion_ALM = ""; - static bool APILegalized = false; - static string MGDatabasePath = Path.Combine(Directory.GetCurrentDirectory(), "mgdb"); + private static int TID_ALM = -1; + private static int SID_ALM = -1; + private static string OT_ALM = ""; + private static int gender_ALM = 0; + private static string Country_ALM = ""; + private static string SubRegion_ALM = ""; + private static string ConsoleRegion_ALM = ""; + private static bool APILegalized = false; + private static readonly string MGDatabasePath = Path.Combine(Directory.GetCurrentDirectory(), "mgdb"); public static void ImportModded() { Stopwatch timer = Stopwatch.StartNew(); // TODO: Check for Auto Legality Mod Updates - bool allowAPI = true; // Use true to allow experimental API usage + const bool allowAPI = true; // Use true to allow experimental API usage APILegalized = false; // Initialize to false everytime command is used // Check for lack of showdown data provided CheckLoadFromText(out bool valid); - if (!valid) return; + if (!valid) + return; // Make a blank MGDB directory and initialize trainerdata - if (!Directory.Exists(MGDatabasePath)) Directory.CreateDirectory(MGDatabasePath); - if (AutoLegalityMod.checkMode() != "game") LoadTrainerData(); + if (!Directory.Exists(MGDatabasePath)) + Directory.CreateDirectory(MGDatabasePath); + if (AutoLegalityMod.CheckMode() != "game") + LoadTrainerData(); // Get Text source from clipboard and convert to ShowdownSet(s) string source = Clipboard.GetText().TrimEnd(); @@ -54,8 +57,10 @@ public static void ImportModded() // Debug Statements Debug.WriteLine(LogTimer(timer)); - if (message.StartsWith("[DEBUG]")) Debug.WriteLine(message); - else Alert(message); + if (message.StartsWith("[DEBUG]")) + Debug.WriteLine(message); + else + Alert(message); } /// @@ -64,26 +69,24 @@ public static void ImportModded() /// output boolean that tells if the data provided is valid or not private static void CheckLoadFromText(out bool valid) { - valid = true; - if (!showdownData() || (Control.ModifierKeys & Keys.Shift) == Keys.Shift) + if (!ShowdownData() || (Control.ModifierKeys & Keys.Shift) == Keys.Shift) { if (OpenSAVPKMDialog(new string[] { "txt" }, out string path)) { Clipboard.SetText(File.ReadAllText(path).TrimEnd()); - if (!showdownData()) + if (!ShowdownData()) { Alert("Text file with invalid data provided. Please provide a text file with proper Showdown data"); valid = false; - return; } } else { Alert("No data provided."); valid = false; - return; } } + valid = true; } /// @@ -92,16 +95,16 @@ private static void CheckLoadFromText(out bool valid) /// Optional legal PKM for loading trainerdata on a per game basis private static void LoadTrainerData(PKM legal = null) { - bool checkPerGame = (AutoLegalityMod.checkMode() == "game"); + bool checkPerGame = (AutoLegalityMod.CheckMode() == "game"); // If mode is not set as game: (auto or save) - string[] tdataVals; - if (!checkPerGame || legal == null) tdataVals = AutoLegalityMod.parseTrainerJSON(SAV); - - else tdataVals = AutoLegalityMod.parseTrainerJSON(SAV, legal.Version); + var tdataVals = !checkPerGame || legal == null + ? AutoLegalityMod.ParseTrainerJSON(SAV) + : AutoLegalityMod.ParseTrainerJSON(SAV, legal.Version); TID_ALM = Convert.ToInt32(tdataVals[0]); SID_ALM = Convert.ToInt32(tdataVals[1]); if (legal != null) SID_ALM = legal.VC ? 0 : SID_ALM; + OT_ALM = tdataVals[2]; if (OT_ALM == "PKHeX") OT_ALM = "Archit(TCD)"; // Avoids secondary handler error gender_ALM = 0; @@ -123,7 +126,7 @@ private static void LoadTrainerData(PKM legal = null) private static void ImportSets(List sets, bool replace, out string message, bool allowAPI = true) { message = "[DEBUG] Commencing Import"; - List emptySlots = new List { }; + List emptySlots = new List(); IList BoxData = SAV.BoxData; int BoxOffset = SaveFileEditor.CurrentBox * SAV.BoxSlotCount; if (replace) emptySlots = Enumerable.Range(0, sets.Count).ToList(); @@ -172,15 +175,20 @@ private static void ImportSets(List sets, bool replace, out string SAV.BoxData = BoxData; SaveFileEditor.ReloadSlots(); message = "[DEBUG] API Genned Sets: " + apiCounter + Environment.NewLine + Environment.NewLine + "Number of sets not genned by the API: " + invalidAPISets.Count; - foreach (ShowdownSet i in invalidAPISets) Debug.WriteLine(i.Text); + foreach (ShowdownSet i in invalidAPISets) + Debug.WriteLine(i.Text); + } + else + { + message = "[DEBUG] Set Genning Complete"; } - else message = "[DEBUG] Set Genning Complete"; } /// /// Set trainer data for a legal PKM /// /// Legal PKM for setting the data + /// /// PKM with the necessary values modified to reflect trainerdata changes private static PKM SetTrainerData(PKM legal, bool display) { @@ -212,7 +220,7 @@ private static List PopulateEmptySlots(IList BoxData, int CurrentBox) int BoxCount = SAV.BoxSlotCount; for (int i = 0; i < BoxCount; i++) { - if (BoxData[CurrentBox * BoxCount + i].Species < 1) emptySlots.Add(i); + if (BoxData[(CurrentBox * BoxCount) + i].Species < 1) emptySlots.Add(i); } return emptySlots; } @@ -222,6 +230,7 @@ private static List PopulateEmptySlots(IList BoxData, int CurrentBox) /// Needs to be extended to hold several teams /// /// + /// /// private static List ShowdownSets(string paste, out Dictionary TeamData) { @@ -291,24 +300,22 @@ private static string LogTimer(Stopwatch timer) /// Checks the input text is a showdown set or not /// /// boolean of the summary - private static bool showdownData() + private static bool ShowdownData() { - if (!Clipboard.ContainsText()) return false; + if (!Clipboard.ContainsText()) + return false; string source = Clipboard.GetText().TrimEnd(); - if (TeamBackup(source)) return true; + if (TeamBackup(source)) + return true; string[] stringSeparators = new string[] { "\n\r" }; - string[] result; - // ... - result = source.Split(stringSeparators, StringSplitOptions.None); - if (new ShowdownSet(result[0]).Species < 0) return false; - return true; + var result = source.Split(stringSeparators, StringSplitOptions.None); + return new ShowdownSet(result[0]).Species >= 0; } - /// TODO - /// Method to check for updates to AutoLegalityMod - /// TODO - + // TODO + // Method to check for updates to AutoLegalityMod + // TODO /// /// Parse release GitHub tag into a PKHeX style version @@ -322,29 +329,7 @@ public static int ParseTagAsVersion(string v) int.TryParse(date[0], out int a); int.TryParse(date[1], out int b); int.TryParse(date[2], out int c); - return (a + 2000) * 10000 + b * 100 + c; - } - - /// - /// GET request to a url with UserAgent Header being AutoLegalityMod - /// - /// URL on which the GET request is to be executed - /// GET Response - private static string GetPage(string url) - { - try - { - var request = (HttpWebRequest)WebRequest.Create(url); - request.UserAgent = "AutoLegalityMod"; - var response = (HttpWebResponse)request.GetResponse(); - var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); - return responseString; - } - catch (Exception e) - { - Debug.WriteLine("An error occured while trying to obtain the contents of the URL. This is most likely an issue with your Internet Connection. The exact error is as follows: " + e.ToString() + "\nURL tried to access: " + url); - return "Error :" + e.ToString(); - } + return ((a + 2000) * 10000) + (b * 100) + c; } private static DialogResult Alert(params string[] lines) diff --git a/AutoLegalityMod/EdgeCaseLegality.cs b/AutoLegalityMod/EdgeCaseLegality.cs index a3dd399a..404e5c91 100644 --- a/AutoLegalityMod/EdgeCaseLegality.cs +++ b/AutoLegalityMod/EdgeCaseLegality.cs @@ -10,17 +10,17 @@ namespace AutoLegalityMod { - public class EdgeCaseLegality + public static class EdgeCaseLegality { - public EncounterStatic[] BWEntreeForest = MarkG5DreamWorld(BW_DreamWorld); - public EncounterStatic[] B2W2EntreeForest = MarkG5DreamWorld(B2W2_DreamWorld); - public EncounterStatic[] USUMEdgeEnc = MarkEncountersGeneration(USUMEdgeEncounters, 7); + public static readonly EncounterStatic[] BWEntreeForest = MarkG5DreamWorld(BW_DreamWorld); + public static readonly EncounterStatic[] B2W2EntreeForest = MarkG5DreamWorld(B2W2_DreamWorld); + public static readonly EncounterStatic[] USUMEdgeEnc = MarkEncountersGeneration(USUMEdgeEncounters, 7); /// ///Gen 5 Dreamworld wack events /// - public static EncounterStatic[] DreamWorld_Common = + public static readonly EncounterStatic[] DreamWorld_Common = { // Pleasant forest new EncounterStatic { Species=019, Level = 10, Moves = new[]{098, 382, 231}, }, //Rattata @@ -188,69 +188,69 @@ public class EdgeCaseLegality new EncounterStatic { Species=376, Level = 45, Moves = new[]{038}, Gender = 2, }, //Metagross }; - static EncounterStatic[] BW_DreamWorld = DreamWorld_Common.Concat(new[] + private static readonly EncounterStatic[] BW_DreamWorld = DreamWorld_Common.Concat(new[] { // Pleasant forest new EncounterStatic { Species=029, Level = 10, Moves = new[]{010, 389, 162}, }, //Nidoran (F) new EncounterStatic { Species=032, Level = 10, Moves = new[]{064, 068, 162}, }, //Nidoran (M) - new EncounterStatic { Species=174, Level = 10, Moves = new[]{047, 313, 270}, }, //Igglybuff - new EncounterStatic { Species=187, Level = 10, Moves = new[]{235, 270, 331}, }, //Hoppip - new EncounterStatic { Species=270, Level = 10, Moves = new[]{071, 073, 352}, }, //Lotad - new EncounterStatic { Species=276, Level = 10, Moves = new[]{064, 119, 366}, }, //Taillow - new EncounterStatic { Species=309, Level = 10, Moves = new[]{086, 423, 324}, }, //Electrike - new EncounterStatic { Species=351, Level = 10, Moves = new[]{052, 466, 352}, }, //Castform - new EncounterStatic { Species=417, Level = 10, Moves = new[]{098, 343, 351}, }, //Pachirisu + new EncounterStatic { Species=174, Level = 10, Moves = new[]{047, 313, 270}, }, //Igglybuff + new EncounterStatic { Species=187, Level = 10, Moves = new[]{235, 270, 331}, }, //Hoppip + new EncounterStatic { Species=270, Level = 10, Moves = new[]{071, 073, 352}, }, //Lotad + new EncounterStatic { Species=276, Level = 10, Moves = new[]{064, 119, 366}, }, //Taillow + new EncounterStatic { Species=309, Level = 10, Moves = new[]{086, 423, 324}, }, //Electrike + new EncounterStatic { Species=351, Level = 10, Moves = new[]{052, 466, 352}, }, //Castform + new EncounterStatic { Species=417, Level = 10, Moves = new[]{098, 343, 351}, }, //Pachirisu // Windskept Sky - new EncounterStatic { Species=012, Level = 10, Moves = new[]{093, 355, 314}, }, //Butterfree - new EncounterStatic { Species=163, Level = 10, Moves = new[]{193, 101, 278}, }, //Hoothoot - new EncounterStatic { Species=278, Level = 10, Moves = new[]{055, 239, 351}, }, //Wingull - new EncounterStatic { Species=333, Level = 10, Moves = new[]{064, 297, 355}, }, //Swablu - new EncounterStatic { Species=425, Level = 10, Moves = new[]{107, 095, 285}, }, //Drifloon - new EncounterStatic { Species=441, Level = 10, Moves = new[]{119, 417, 272}, }, //Chatot + new EncounterStatic { Species=012, Level = 10, Moves = new[]{093, 355, 314}, }, //Butterfree + new EncounterStatic { Species=163, Level = 10, Moves = new[]{193, 101, 278}, }, //Hoothoot + new EncounterStatic { Species=278, Level = 10, Moves = new[]{055, 239, 351}, }, //Wingull + new EncounterStatic { Species=333, Level = 10, Moves = new[]{064, 297, 355}, }, //Swablu + new EncounterStatic { Species=425, Level = 10, Moves = new[]{107, 095, 285}, }, //Drifloon + new EncounterStatic { Species=441, Level = 10, Moves = new[]{119, 417, 272}, }, //Chatot // Sparkling Sea - new EncounterStatic { Species=079, Level = 10, Moves = new[]{281, 335, 362}, }, //Slowpoke - new EncounterStatic { Species=098, Level = 10, Moves = new[]{011, 133, 290}, }, //Krabby - new EncounterStatic { Species=119, Level = 33, Moves = new[]{352, 214, 203}, }, //Seaking - new EncounterStatic { Species=120, Level = 10, Moves = new[]{055, 278, 196}, }, //Staryu - new EncounterStatic { Species=222, Level = 10, Moves = new[]{145, 109, 446}, }, //Corsola + new EncounterStatic { Species=079, Level = 10, Moves = new[]{281, 335, 362}, }, //Slowpoke + new EncounterStatic { Species=098, Level = 10, Moves = new[]{011, 133, 290}, }, //Krabby + new EncounterStatic { Species=119, Level = 33, Moves = new[]{352, 214, 203}, }, //Seaking + new EncounterStatic { Species=120, Level = 10, Moves = new[]{055, 278, 196}, }, //Staryu + new EncounterStatic { Species=222, Level = 10, Moves = new[]{145, 109, 446}, }, //Corsola new EncounterStatic { Species=422, Level = 10, Moves = new[]{189, 281, 290}, Form = 0 }, //Shellos new EncounterStatic { Species=422, Level = 10, Moves = new[]{189, 281, 290}, Form = 1 }, // Spooky Mannor - new EncounterStatic { Species=202, Level = 15, Moves = new[]{243, 204, 227}, }, //Wobbuffet - new EncounterStatic { Species=238, Level = 10, Moves = new[]{186, 445, 285}, }, //Smoochum - new EncounterStatic { Species=303, Level = 10, Moves = new[]{313, 424, 008}, }, //Mawile - new EncounterStatic { Species=307, Level = 10, Moves = new[]{096, 409, 203}, }, //Meditite - new EncounterStatic { Species=436, Level = 10, Moves = new[]{095, 285, 356}, }, //Bronzor - new EncounterStatic { Species=052, Level = 10, Moves = new[]{010, 095, 290}, }, //Meowth - new EncounterStatic { Species=479, Level = 10, Moves = new[]{086, 351, 324}, }, //Rotom - new EncounterStatic { Species=280, Level = 10, Moves = new[]{093, 194, 270}, }, //Ralts - new EncounterStatic { Species=302, Level = 10, Moves = new[]{193, 389, 180}, }, //Sableye - new EncounterStatic { Species=442, Level = 10, Moves = new[]{180, 220, 196}, }, //Spiritomb + new EncounterStatic { Species=202, Level = 15, Moves = new[]{243, 204, 227}, }, //Wobbuffet + new EncounterStatic { Species=238, Level = 10, Moves = new[]{186, 445, 285}, }, //Smoochum + new EncounterStatic { Species=303, Level = 10, Moves = new[]{313, 424, 008}, }, //Mawile + new EncounterStatic { Species=307, Level = 10, Moves = new[]{096, 409, 203}, }, //Meditite + new EncounterStatic { Species=436, Level = 10, Moves = new[]{095, 285, 356}, }, //Bronzor + new EncounterStatic { Species=052, Level = 10, Moves = new[]{010, 095, 290}, }, //Meowth + new EncounterStatic { Species=479, Level = 10, Moves = new[]{086, 351, 324}, }, //Rotom + new EncounterStatic { Species=280, Level = 10, Moves = new[]{093, 194, 270}, }, //Ralts + new EncounterStatic { Species=302, Level = 10, Moves = new[]{193, 389, 180}, }, //Sableye + new EncounterStatic { Species=442, Level = 10, Moves = new[]{180, 220, 196}, }, //Spiritomb // Rugged Mountain - new EncounterStatic { Species=056, Level = 10, Moves = new[]{067, 179, 009}, }, //Mankey - new EncounterStatic { Species=111, Level = 10, Moves = new[]{030, 068, 038}, }, //Rhyhorn - new EncounterStatic { Species=231, Level = 10, Moves = new[]{175, 484, 402}, }, //Phanpy - new EncounterStatic { Species=451, Level = 10, Moves = new[]{044, 097, 401}, }, //Skorupi - new EncounterStatic { Species=216, Level = 10, Moves = new[]{313, 242, 264}, }, //Teddiursa - new EncounterStatic { Species=296, Level = 10, Moves = new[]{292, 270, 008}, }, //Makuhita - new EncounterStatic { Species=327, Level = 10, Moves = new[]{383, 252, 276}, }, //Spinda - new EncounterStatic { Species=374, Level = 10, Moves = new[]{036, 428, 442}, }, //Beldum - new EncounterStatic { Species=447, Level = 10, Moves = new[]{203, 418, 264}, }, //Riolu + new EncounterStatic { Species=056, Level = 10, Moves = new[]{067, 179, 009}, }, //Mankey + new EncounterStatic { Species=111, Level = 10, Moves = new[]{030, 068, 038}, }, //Rhyhorn + new EncounterStatic { Species=231, Level = 10, Moves = new[]{175, 484, 402}, }, //Phanpy + new EncounterStatic { Species=451, Level = 10, Moves = new[]{044, 097, 401}, }, //Skorupi + new EncounterStatic { Species=216, Level = 10, Moves = new[]{313, 242, 264}, }, //Teddiursa + new EncounterStatic { Species=296, Level = 10, Moves = new[]{292, 270, 008}, }, //Makuhita + new EncounterStatic { Species=327, Level = 10, Moves = new[]{383, 252, 276}, }, //Spinda + new EncounterStatic { Species=374, Level = 10, Moves = new[]{036, 428, 442}, }, //Beldum + new EncounterStatic { Species=447, Level = 10, Moves = new[]{203, 418, 264}, }, //Riolu // Icy Cave - new EncounterStatic { Species=173, Level = 10, Moves = new[]{227, 312, 214}, }, //Cleffa - new EncounterStatic { Species=213, Level = 10, Moves = new[]{227, 270, 504}, }, //Shuckle - new EncounterStatic { Species=299, Level = 10, Moves = new[]{033, 446, 246}, }, //Nosepass - new EncounterStatic { Species=363, Level = 10, Moves = new[]{181, 090, 401}, }, //Spheal - new EncounterStatic { Species=408, Level = 10, Moves = new[]{029, 442, 007}, }, //Cranidos - new EncounterStatic { Species=206, Level = 10, Moves = new[]{111, 277, 446}, }, //Dunsparce - new EncounterStatic { Species=410, Level = 10, Moves = new[]{182, 068, 090}, }, //Shieldon + new EncounterStatic { Species=173, Level = 10, Moves = new[]{227, 312, 214}, }, //Cleffa + new EncounterStatic { Species=213, Level = 10, Moves = new[]{227, 270, 504}, }, //Shuckle + new EncounterStatic { Species=299, Level = 10, Moves = new[]{033, 446, 246}, }, //Nosepass + new EncounterStatic { Species=363, Level = 10, Moves = new[]{181, 090, 401}, }, //Spheal + new EncounterStatic { Species=408, Level = 10, Moves = new[]{029, 442, 007}, }, //Cranidos + new EncounterStatic { Species=206, Level = 10, Moves = new[]{111, 277, 446}, }, //Dunsparce + new EncounterStatic { Species=410, Level = 10, Moves = new[]{182, 068, 090}, }, //Shieldon // Dream Park - new EncounterStatic { Species=048, Level = 10, Moves = new[]{050, 226, 285}, }, //Venonat - new EncounterStatic { Species=088, Level = 10, Moves = new[]{139, 114, 425}, }, //Grimer - new EncounterStatic { Species=415, Level = 10, Moves = new[]{016, 366, 314}, }, //Combee - new EncounterStatic { Species=015, Level = 10, Moves = new[]{031, 314, 210}, }, //Beedrill - new EncounterStatic { Species=335, Level = 10, Moves = new[]{098, 458, 067}, }, //Zangoose - new EncounterStatic { Species=336, Level = 10, Moves = new[]{044, 034, 401}, }, //Seviper + new EncounterStatic { Species=048, Level = 10, Moves = new[]{050, 226, 285}, }, //Venonat + new EncounterStatic { Species=088, Level = 10, Moves = new[]{139, 114, 425}, }, //Grimer + new EncounterStatic { Species=415, Level = 10, Moves = new[]{016, 366, 314}, }, //Combee + new EncounterStatic { Species=015, Level = 10, Moves = new[]{031, 314, 210}, }, //Beedrill + new EncounterStatic { Species=335, Level = 10, Moves = new[]{098, 458, 067}, }, //Zangoose + new EncounterStatic { Species=336, Level = 10, Moves = new[]{044, 034, 401}, }, //Seviper // PGL new EncounterStatic { Species=134, Level = 10, Gender = 0, }, //Vaporeon new EncounterStatic { Species=135, Level = 10, Gender = 0, }, //Jolteon @@ -279,54 +279,54 @@ public class EdgeCaseLegality new EncounterStatic { Species=334, Level = 35, Moves = new[]{206}, Gender = 0,}, //Altaria new EncounterStatic { Species=242, Level = 10 }, //Blissey new EncounterStatic { Species=448, Level = 10, Moves = new[]{418}, Gender = 0, }, //Lucario - new EncounterStatic { Species=189, Level = 27, Moves = new[]{206}, Gender = 0, }, //Jumpluff + new EncounterStatic { Species=189, Level = 27, Moves = new[]{206}, Gender = 0, }, //Jumpluff }).ToArray(); - static EncounterStatic[] B2W2_DreamWorld = DreamWorld_Common.Concat(new[] + private static readonly EncounterStatic[] B2W2_DreamWorld = DreamWorld_Common.Concat(new[] { // Pleasant forest - new EncounterStatic { Species=535, Level = 10, Moves = new[]{496, 414, 352}, }, //Tympole - new EncounterStatic { Species=546, Level = 10, Moves = new[]{073, 227, 388}, }, //Cottonee - new EncounterStatic { Species=548, Level = 10, Moves = new[]{079, 204, 230}, }, //Petilil - new EncounterStatic { Species=588, Level = 10, Moves = new[]{203, 224, 450}, }, //Karrablast - new EncounterStatic { Species=616, Level = 10, Moves = new[]{051, 226, 227}, }, //Shelmet - new EncounterStatic { Species=545, Level = 30, Moves = new[]{342, 390, 276}, }, //Scolipede + new EncounterStatic { Species=535, Level = 10, Moves = new[]{496, 414, 352}, }, //Tympole + new EncounterStatic { Species=546, Level = 10, Moves = new[]{073, 227, 388}, }, //Cottonee + new EncounterStatic { Species=548, Level = 10, Moves = new[]{079, 204, 230}, }, //Petilil + new EncounterStatic { Species=588, Level = 10, Moves = new[]{203, 224, 450}, }, //Karrablast + new EncounterStatic { Species=616, Level = 10, Moves = new[]{051, 226, 227}, }, //Shelmet + new EncounterStatic { Species=545, Level = 30, Moves = new[]{342, 390, 276}, }, //Scolipede // Windskept Sky - new EncounterStatic { Species=519, Level = 10, Moves = new[]{016, 095, 234}, }, //Pidove - new EncounterStatic { Species=561, Level = 10, Moves = new[]{095, 500, 257}, }, //Sigilyph - new EncounterStatic { Species=580, Level = 10, Moves = new[]{432, 362, 382}, }, //Ducklett - new EncounterStatic { Species=587, Level = 10, Moves = new[]{098, 403, 204}, }, //Emolga + new EncounterStatic { Species=519, Level = 10, Moves = new[]{016, 095, 234}, }, //Pidove + new EncounterStatic { Species=561, Level = 10, Moves = new[]{095, 500, 257}, }, //Sigilyph + new EncounterStatic { Species=580, Level = 10, Moves = new[]{432, 362, 382}, }, //Ducklett + new EncounterStatic { Species=587, Level = 10, Moves = new[]{098, 403, 204}, }, //Emolga // Sparkling Sea new EncounterStatic { Species=550, Level = 10, Moves = new[]{029, 097, 428}, Form = 0 },//Basculin new EncounterStatic { Species=550, Level = 10, Moves = new[]{029, 097, 428}, Form = 1 }, - new EncounterStatic { Species=594, Level = 10, Moves = new[]{392, 243, 220}, }, //Alomomola - new EncounterStatic { Species=618, Level = 10, Moves = new[]{189, 174, 281}, }, //Stunfisk - new EncounterStatic { Species=564, Level = 10, Moves = new[]{205, 175, 334}, }, //Tirtouga + new EncounterStatic { Species=594, Level = 10, Moves = new[]{392, 243, 220}, }, //Alomomola + new EncounterStatic { Species=618, Level = 10, Moves = new[]{189, 174, 281}, }, //Stunfisk + new EncounterStatic { Species=564, Level = 10, Moves = new[]{205, 175, 334}, }, //Tirtouga // Spooky Mannor - new EncounterStatic { Species=605, Level = 10, Moves = new[]{377, 112, 417}, }, //Elgyem - new EncounterStatic { Species=624, Level = 10, Moves = new[]{210, 427, 389}, }, //Pawniard - new EncounterStatic { Species=596, Level = 36, Moves = new[]{486, 050, 228}, }, //Galvantula - new EncounterStatic { Species=578, Level = 32, Moves = new[]{105, 286, 271}, }, //Duosion - new EncounterStatic { Species=622, Level = 10, Moves = new[]{205, 007, 009}, }, //Golett + new EncounterStatic { Species=605, Level = 10, Moves = new[]{377, 112, 417}, }, //Elgyem + new EncounterStatic { Species=624, Level = 10, Moves = new[]{210, 427, 389}, }, //Pawniard + new EncounterStatic { Species=596, Level = 36, Moves = new[]{486, 050, 228}, }, //Galvantula + new EncounterStatic { Species=578, Level = 32, Moves = new[]{105, 286, 271}, }, //Duosion + new EncounterStatic { Species=622, Level = 10, Moves = new[]{205, 007, 009}, }, //Golett // Rugged Mountain - new EncounterStatic { Species=631, Level = 10, Moves = new[]{510, 257, 202}, }, //Heatmor - new EncounterStatic { Species=632, Level = 10, Moves = new[]{210, 203, 422}, }, //Durant - new EncounterStatic { Species=556, Level = 10, Moves = new[]{042, 073, 191}, }, //Maractus - new EncounterStatic { Species=558, Level = 34, Moves = new[]{157, 068, 400}, }, //Crustle - new EncounterStatic { Species=553, Level = 40, Moves = new[]{242, 068, 212}, }, //Krookodile + new EncounterStatic { Species=631, Level = 10, Moves = new[]{510, 257, 202}, }, //Heatmor + new EncounterStatic { Species=632, Level = 10, Moves = new[]{210, 203, 422}, }, //Durant + new EncounterStatic { Species=556, Level = 10, Moves = new[]{042, 073, 191}, }, //Maractus + new EncounterStatic { Species=558, Level = 34, Moves = new[]{157, 068, 400}, }, //Crustle + new EncounterStatic { Species=553, Level = 40, Moves = new[]{242, 068, 212}, }, //Krookodile // Icy Cave - new EncounterStatic { Species=529, Level = 10, Moves = new[]{229, 319, 431}, }, //Drilbur - new EncounterStatic { Species=621, Level = 10, Moves = new[]{044, 424, 389}, }, //Druddigon - new EncounterStatic { Species=525, Level = 25, Moves = new[]{479, 174, 484}, }, //Boldore - new EncounterStatic { Species=583, Level = 35, Moves = new[]{429, 420, 286}, }, //Vanillish - new EncounterStatic { Species=600, Level = 38, Moves = new[]{451, 356, 393}, }, //Klang - new EncounterStatic { Species=610, Level = 10, Moves = new[]{082, 068, 400}, }, //Axew + new EncounterStatic { Species=529, Level = 10, Moves = new[]{229, 319, 431}, }, //Drilbur + new EncounterStatic { Species=621, Level = 10, Moves = new[]{044, 424, 389}, }, //Druddigon + new EncounterStatic { Species=525, Level = 25, Moves = new[]{479, 174, 484}, }, //Boldore + new EncounterStatic { Species=583, Level = 35, Moves = new[]{429, 420, 286}, }, //Vanillish + new EncounterStatic { Species=600, Level = 38, Moves = new[]{451, 356, 393}, }, //Klang + new EncounterStatic { Species=610, Level = 10, Moves = new[]{082, 068, 400}, }, //Axew // Dream Park - new EncounterStatic { Species=531, Level = 10, Moves = new[]{270, 227, 281}, }, //Audino - new EncounterStatic { Species=538, Level = 10, Moves = new[]{020, 008, 276}, }, //Throh - new EncounterStatic { Species=539, Level = 10, Moves = new[]{249, 009, 530}, }, //Sawk - new EncounterStatic { Species=559, Level = 10, Moves = new[]{067, 252, 409}, }, //Scraggy - new EncounterStatic { Species=533, Level = 25, Moves = new[]{067, 183, 409}, }, //Gurdurr + new EncounterStatic { Species=531, Level = 10, Moves = new[]{270, 227, 281}, }, //Audino + new EncounterStatic { Species=538, Level = 10, Moves = new[]{020, 008, 276}, }, //Throh + new EncounterStatic { Species=539, Level = 10, Moves = new[]{249, 009, 530}, }, //Sawk + new EncounterStatic { Species=559, Level = 10, Moves = new[]{067, 252, 409}, }, //Scraggy + new EncounterStatic { Species=533, Level = 25, Moves = new[]{067, 183, 409}, }, //Gurdurr // PGL new EncounterStatic { Species=575, Level = 32, Moves = new[]{243}, Gender = 0, }, //Gothorita new EncounterStatic { Species=025, Level = 10, Moves = new[]{029}, Gender = 0, }, //Pikachu @@ -336,10 +336,10 @@ public class EdgeCaseLegality new EncounterStatic { Species=387, Level = 10, Moves = new[]{254}, Gender = 0, }, //Turtwig new EncounterStatic { Species=390, Level = 10, Moves = new[]{252}, Gender = 0, }, //Chimchar new EncounterStatic { Species=393, Level = 10, Moves = new[]{297}, Gender = 0, }, //Piplup - new EncounterStatic { Species=575, Level = 32, Moves = new[]{286}, Gender = 0, }, //Gothorita + new EncounterStatic { Species=575, Level = 32, Moves = new[]{286}, Gender = 0, }, //Gothorita }).ToArray(); - static EncounterStatic[] USUMEdgeEncounters = new EncounterStatic[] + private static readonly EncounterStatic[] USUMEdgeEncounters = new EncounterStatic[] { new EncounterStatic // Pikachu (Pretty Wing), should probably be a fake mystery gift as it has OT details { @@ -384,15 +384,16 @@ private static EncounterStatic[] MarkG5DreamWorld(EncounterStatic[] t) list.Add(clone); } } - t = list.ToArray(); - return t; + return list.ToArray(); } + internal static EncounterStatic Cloner(EncounterStatic s, int location) { var result = CloneObject(s); result.Location = location; return result; } + internal static EncounterStatic CloneObject(EncounterStatic s) { if (s == null) return null; @@ -403,6 +404,7 @@ internal static EncounterStatic CloneObject(EncounterStatic s) else return null; } + internal static EncounterStatic[] GetStaticEncounters(IEnumerable source, GameVersion game) { return source.Where(s => s.Version.Contains(game)).ToArray(); diff --git a/AutoLegalityMod/IVtoPIDGenerator.cs b/AutoLegalityMod/IVtoPIDGenerator.cs index e229cd83..32083338 100644 --- a/AutoLegalityMod/IVtoPIDGenerator.cs +++ b/AutoLegalityMod/IVtoPIDGenerator.cs @@ -2,7 +2,6 @@ namespace Misc { - internal class GenericRng { // This is the generic base that all of the other lcrngs will @@ -83,12 +82,12 @@ public enum FrameType internal class Seed { - // Needs to hold all of the information about + // Needs to hold all of the information about // a seed that we have created from an IV and // nature combo. // Need to come up with a better name for this, as it - // cant seem to have the same name as the containing + // cant seem to have the same name as the containing // class :P public uint MonsterSeed { get; set; } @@ -173,9 +172,7 @@ public class Frame private uint dv; private uint id; - private uint number; private uint pid; - private uint seed; private uint sid; internal Frame(FrameType frameType) @@ -187,17 +184,9 @@ internal Frame(FrameType frameType) public uint RngResult { get; set; } - public uint Seed - { - get { return seed; } - set { seed = value; } - } + public uint Seed { get; set; } - public uint Number - { - get { return number; } - set { number = value; } - } + public uint Number { get; set; } public uint Offset { get; set; } @@ -206,7 +195,7 @@ public uint Number public bool Shiny { get; private set; } // The following are cacluated differently based - // on the creation method of the pokemon. + // on the creation method of the pokemon. public uint Pid { @@ -295,7 +284,7 @@ public static Frame GenerateFrame( }; - // Set up the ID and SID before we calculate + // Set up the ID and SID before we calculate // the pid, as we are going to need this. @@ -317,15 +306,15 @@ public static Frame GenerateFrame( { var frame = new Frame(frameType) { - seed = seed, - number = number, + Seed = seed, + Number = number, RngResult = rngResult, id = id, sid = sid, Pid = (pid2 << 16) | pid1, Dv = (dv2 << 16) | dv1 }; - // Set up the ID and SID before we calculate + // Set up the ID and SID before we calculate // the pid, as we are going to need this. @@ -354,8 +343,8 @@ public static Frame GenerateFrame( var frame = new Frame(frameType) { - seed = seed, - number = number, + Seed = seed, + Number = number, RngResult = rngResult, id = id, sid = sid, @@ -408,7 +397,7 @@ public FrameCompare(IVFilter ivBase, uint nature) Nature = nature; } - public uint Nature { get; private set; } + public uint Nature { get; } public bool Compare(Frame frame) { @@ -587,7 +576,6 @@ public List Generate( break; } - if (frameCompare.Compare(frame)) { frames.Add(frame); break; @@ -597,7 +585,7 @@ public List Generate( else { // We are going to grab our initial set of rngs here and - // then start our loop so that we can iterate as many + // then start our loop so that we can iterate as many // times as we have to. var rng = new PokeRng((uint)InitialSeed); rngList = new List(); @@ -675,7 +663,6 @@ public List Generate( break; } - // Now we need to filter and decide if we are going // to add this to our collection for display to the // user. @@ -694,7 +681,7 @@ public List Generate( /// /// This class is going to do an IV/PID/Seed calculation given a particular method (1, 2 or 3, or 4). Should use the same code to develop candidate IVs. /// - internal class IVtoSeed + internal static class IVtoSeed { // We need a function to return a list of monster seeds, // which will be updated to include a method. @@ -1105,7 +1092,6 @@ public static List GetSeeds( } } - public class IVtoPIDGenerator { public static string[] M1PID(uint hp, uint atk, uint def, uint spa, uint spd, uint spe, uint nature, uint tid) @@ -1255,7 +1241,7 @@ public string[] generateWishmkr(uint targetNature) uint ivs2 = forward(ivs1); ivs1 >>= 16; ivs2 >>= 16; - uint[] ivs = createIVs(ivs1, ivs2); + uint[] ivs = CreateIVs(ivs1, ivs2); if (ivs != null) { finalPID = pid; @@ -1277,7 +1263,7 @@ private uint forward(uint seed) return seed * 0x41c64e6d + 0x6073; } - private uint[] createIVs(uint iv1, uint ivs2) + private uint[] CreateIVs(uint iv1, uint ivs2) { uint[] ivs = new uint[6]; @@ -1293,7 +1279,7 @@ private uint[] createIVs(uint iv1, uint ivs2) return ivs; } - private static IVFilter hptofilter(string hiddenpower) + private static IVFilter Hptofilter(string hiddenpower) { if (hiddenpower == "dark") { @@ -1365,27 +1351,20 @@ private static IVFilter hptofilter(string hiddenpower) } } - public static string[] getIVPID(uint nature, string hiddenpower, bool XD = false, string method = "") + public static string[] GetIVPID(uint nature, string hiddenpower, bool XD = false, string method = "") { var generator = new FrameGenerator(); - if (XD || method == "XD") generator = new FrameGenerator - { - FrameType = FrameType.ColoXD - }; - if (method == "M2") generator = new FrameGenerator - { - FrameType = FrameType.Method2 - }; + if (XD || method == "XD") + generator = new FrameGenerator{FrameType = FrameType.ColoXD}; + if (method == "M2") + generator = new FrameGenerator{FrameType = FrameType.Method2}; if (method == "BACD_R") { - generator = new FrameGenerator - { - FrameType = FrameType.Method1Reverse - }; + generator = new FrameGenerator{FrameType = FrameType.Method1Reverse}; IVtoPIDGenerator bacdr = new IVtoPIDGenerator(); return bacdr.generateWishmkr(nature); } - FrameCompare frameCompare = new FrameCompare(hptofilter(hiddenpower), nature); + FrameCompare frameCompare = new FrameCompare(Hptofilter(hiddenpower), nature); List frames = generator.Generate(frameCompare, 0, 0); //Console.WriteLine("Num frames: " + frames.Count); return new string[] { frames[0].Pid.ToString("X"), frames[0].Hp.ToString(), frames[0].Atk.ToString(), frames[0].Def.ToString(), frames[0].Spa.ToString(), frames[0].Spd.ToString(), frames[0].Spe.ToString() }; diff --git a/AutoLegalityMod/PKSMAutoLegality.cs b/AutoLegalityMod/PKSMAutoLegality.cs index 516e7b25..a6edb9b6 100644 --- a/AutoLegalityMod/PKSMAutoLegality.cs +++ b/AutoLegalityMod/PKSMAutoLegality.cs @@ -11,11 +11,10 @@ namespace AutoLegalityMod { public partial class BruteForce { - PKM backup; - bool requestedShiny = false; - public event EventHandler LegalityChanged; + private PKM backup; + private bool requestedShiny; public SaveFile SAV; - bool legalized = false; + private bool legalized; /// /// Try to generate every a legal PKM from a showdown set using bruteforce. This should generally never be needed. @@ -32,7 +31,7 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm { backup = Set; bool trainerinfo = TID > 0; - List> evoChart = generateEvoLists2(); + List> evoChart = GenerateEvoLists2(); int abilitynum = Set.AbilityNumber < 6 ? Set.AbilityNumber >> 1 : 0; if (resetForm) { @@ -114,9 +113,9 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm Set.Met_Location = 30001; Set.Met_Level = 100; } - else { Set = clickMetLocationModPKSM(Set); } + else { Set = ClickMetLocationModPKSM(Set); } if (Set.GenNumber > 4) Set.Met_Level = 1; - setMarkings(Set); + SetMarkings(Set); try { Set.CurrentHandler = 1; @@ -142,7 +141,7 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm if (Set.GenNumber < 6 && !legalized) Set.EncryptionConstant = Set.PID; if (new LegalityAnalysis(Set).Valid && SAV.Generation >= Set.GenNumber) { - setHappiness(Set); + SetHappiness(Set); if (shiny && !Set.IsShiny) Set.SetShinySID(); return Set; } @@ -155,7 +154,7 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm catch { continue; } } } - + if (!new LegalityAnalysis(Set).Valid && !eventMon) { for (int i = 0; i < GameVersionList.Length; i++) @@ -187,12 +186,10 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm { Set.SID = 0; if (OT.Length > 6) - { Set.OT_Name = "ARCH"; - } } Set.MetDate = DateTime.Today; - setMarkings(Set); + SetMarkings(Set); try { Set.RelearnMove1 = 0; @@ -216,7 +213,7 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm } else { - clickMetLocationModPKSM(Set); + ClickMetLocationModPKSM(Set); } Set = SetSuggestedRelearnMoves_PKSM(Set); Set.CurrentHandler = 1; @@ -226,39 +223,52 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm if (Set.PID == 0) { Set.PID = PKX.GetRandomPID(Set.Species, Set.Gender, Set.Version, Set.Nature, Set.Format, (uint)(Set.AbilityNumber * 0x10001)); - if (shiny) Set.SetShinyPID(); + if (shiny) + Set.SetShinyPID(); } + Set.RefreshAbility(abilitynum); Set = FixMemoriesPKM(Set); - if (Set.GenNumber < 6) Set.EncryptionConstant = Set.PID; + if (Set.GenNumber < 6) + Set.EncryptionConstant = Set.PID; + if (CommonErrorHandling2(Set)) { HyperTrain(Set); if (shiny) Set.SetShinyPID(); return Set; } + HyperTrain(Set); - if (new LegalityAnalysis(Set).Valid) legalized = true; + if (new LegalityAnalysis(Set).Valid) + legalized = true; + AlternateAbilityRefresh(Set); - if (Set.GenNumber < 6 && !legalized) Set.EncryptionConstant = Set.PID; + if (Set.GenNumber < 6 && !legalized) + Set.EncryptionConstant = Set.PID; + if (new LegalityAnalysis(Set).Valid && SAV.Generation >= Set.GenNumber) { - setHappiness(Set); + SetHappiness(Set); PKM returnval = Set; - if (shiny && Set.IsShiny) return Set; - if (shiny && !Set.IsShiny) - { - Set.SetShinySID(); - if (new LegalityAnalysis(Set).Valid) return Set; - Set = returnval; - Set.SetShinyPID(); - if (new LegalityAnalysis(Set).Valid) return Set; - } - else return returnval; + if (shiny && Set.IsShiny) + return Set; + if (!shiny || Set.IsShiny) + return returnval; + + Set.SetShinySID(); + if (new LegalityAnalysis(Set).Valid) + return Set; + + Set = returnval; + Set.SetShinyPID(); + + if (new LegalityAnalysis(Set).Valid) + return Set; } else { - List edgeLegality = edgeMons(Set.Version, Set); + var edgeLegality = EdgeMons(Set.Version, Set); foreach (EncounterStatic el in edgeLegality) { Set.Met_Location = el.Location; @@ -301,11 +311,11 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm } } if (chain.Count == 0 && Set.Species != 0) chain.Add(PKMNList[Set.Species]); - foreach (string file in System.IO.Directory.GetFiles(fpath, "*.*", System.IO.SearchOption.AllDirectories)) + foreach (string file in Directory.GetFiles(fpath, "*.*", SearchOption.AllDirectories)) { foreach (string mon in chain) { - if (file.ToLower().Contains(mon.ToLower()) || Path.GetExtension(file) == ".pl6") + if (file.IndexOf(mon, StringComparison.OrdinalIgnoreCase) >= 0 || Path.GetExtension(file) == ".pl6") { fileList.Add(file); Console.WriteLine(file); @@ -321,9 +331,9 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm int AbilityType = -1; uint fixedPID = 0; int form = Set.AltForm; - if (System.IO.Path.GetExtension(file) == ".wc7" || System.IO.Path.GetExtension(file) == ".wc7full") + if (Path.GetExtension(file) == ".wc7" || Path.GetExtension(file) == ".wc7full") { - var mg = (WC7)MysteryGift.GetMysteryGift(System.IO.File.ReadAllBytes(file), System.IO.Path.GetExtension(file)); + var mg = (WC7)MysteryGift.GetMysteryGift(File.ReadAllBytes(file), Path.GetExtension(file)); PIDType = (int)mg.PIDType; AbilityType = mg.AbilityType; Generation = 7; @@ -332,9 +342,9 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm var temp = mg.ConvertToPKM(SAV); eventpk = PKMConverter.ConvertToType(temp, SAV.PKMType, out string c); } - else if (System.IO.Path.GetExtension(file) == ".wc6" || System.IO.Path.GetExtension(file) == ".wc6full") + else if (Path.GetExtension(file) == ".wc6" || Path.GetExtension(file) == ".wc6full") { - var mg = (WC6)MysteryGift.GetMysteryGift(System.IO.File.ReadAllBytes(file), System.IO.Path.GetExtension(file)); + var mg = (WC6)MysteryGift.GetMysteryGift(File.ReadAllBytes(file), Path.GetExtension(file)); PIDType = (int)mg.PIDType; AbilityType = mg.AbilityType; Generation = 6; @@ -343,64 +353,72 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm var temp = mg.ConvertToPKM(SAV); eventpk = PKMConverter.ConvertToType(temp, SAV.PKMType, out string c); } - else if (System.IO.Path.GetExtension(file) == ".pl6") // Pokemon Link + else if (Path.GetExtension(file) == ".pl6") // Pokemon Link { PL6_PKM[] LinkPokemon = new PL6(File.ReadAllBytes(file)).Pokes; bool ExistsEligible = false; PL6_PKM Eligible = new PL6_PKM(); foreach (PL6_PKM i in LinkPokemon) { - if (i.Species != Set.Species) continue; - else - { - Eligible = i; - ExistsEligible = true; - PIDType = i.PIDType; - AbilityType = i.AbilityType; - Generation = 6; - fixedPID = i.PID; - break; - } + if (i.Species != Set.Species) + continue; + + Eligible = i; + ExistsEligible = true; + PIDType = i.PIDType; + AbilityType = i.AbilityType; + Generation = 6; + fixedPID = i.PID; + + break; } if (ExistsEligible) eventpk = PKMConverter.ConvertToType(ConvertPL6ToPKM(Eligible), SAV.PKMType, out string c); } - else if (System.IO.Path.GetExtension(file) == ".pgf") + else if (Path.GetExtension(file) == ".pgf") { - var mg = (PGF)MysteryGift.GetMysteryGift(System.IO.File.ReadAllBytes(file), System.IO.Path.GetExtension(file)); + var mg = (PGF)MysteryGift.GetMysteryGift(File.ReadAllBytes(file), Path.GetExtension(file)); PIDType = mg.PIDType; AbilityType = mg.AbilityType; Generation = 5; fixedPID = mg.PID; - if (!ValidShiny(mg.PIDType, shiny)) continue; + if (!ValidShiny(mg.PIDType, shiny)) + continue; + var temp = mg.ConvertToPKM(SAV); eventpk = PKMConverter.ConvertToType(temp, SAV.PKMType, out string c); } - else if (System.IO.Path.GetExtension(file) == ".pgt" || System.IO.Path.GetExtension(file) == ".pcd" || System.IO.Path.GetExtension(file) == ".wc4") + else if (Path.GetExtension(file) == ".pgt" || Path.GetExtension(file) == ".pcd" || Path.GetExtension(file) == ".wc4") { try { - var mg = (PCD)MysteryGift.GetMysteryGift(System.IO.File.ReadAllBytes(file), System.IO.Path.GetExtension(file)); + var mg = (PCD)MysteryGift.GetMysteryGift(File.ReadAllBytes(file), Path.GetExtension(file)); Generation = 4; - if (shiny != mg.IsShiny) continue; + if (shiny != mg.IsShiny) + continue; + var temp = mg.ConvertToPKM(SAV); eventpk = PKMConverter.ConvertToType(temp, SAV.PKMType, out string c); fixedPID = eventpk.PID; } catch { - var mg = (PGT)MysteryGift.GetMysteryGift(System.IO.File.ReadAllBytes(file), System.IO.Path.GetExtension(file)); + var mg = (PGT)MysteryGift.GetMysteryGift(File.ReadAllBytes(file), Path.GetExtension(file)); Generation = 4; - if (shiny != mg.IsShiny) continue; + if (shiny != mg.IsShiny) + continue; + var temp = mg.ConvertToPKM(SAV); eventpk = PKMConverter.ConvertToType(temp, SAV.PKMType, out string c); fixedPID = eventpk.PID; } } - else if (System.IO.Path.GetExtension(file) == ".pk3") + else if (Path.GetExtension(file) == ".pk3") { Generation = 3; var pk = PKMConverter.GetPKMfromBytes(File.ReadAllBytes(file), prefer: Path.GetExtension(file).Length > 0 ? (Path.GetExtension(file).Last() - '0') & 0xF : SAV.Generation); - if (pk == null) break; + if (pk == null) + break; + eventpk = PKMConverter.ConvertToType(pk, SAV.PKMType, out string c); } @@ -418,16 +436,21 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm } try { - if ((PIDType == 0 && eventpk.IsShiny && shiny == false && Generation > 4) || (PIDType == 0 && !eventpk.IsShiny && shiny == true && Generation > 4)) continue; - if (shiny == true && !eventpk.IsShiny && Generation > 4) + if ((PIDType == 0 && eventpk.IsShiny && !shiny && Generation > 4) || (PIDType == 0 && !eventpk.IsShiny && shiny && Generation > 4)) + continue; + + if (shiny && !eventpk.IsShiny && Generation > 4) { - if (PIDType == 1) eventpk.SetShinyPID(); - else if (PIDType == 3) continue; + if (PIDType == 1) + eventpk.SetShinyPID(); + else if (PIDType == 3) + continue; } - if (shiny == false && eventpk.IsShiny && Generation > 4) + if (!shiny && eventpk.IsShiny && Generation > 4) { if (PIDType == 1) eventpk.PID ^= 0x10000000; - else if (PIDType == 2) continue; + else if (PIDType == 2) + continue; } eventpk.Species = Set.Species; eventpk.AltForm = form; @@ -452,7 +475,6 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm eventpk.EV_SPD = Set.EVs[5]; eventpk.EV_SPE = Set.EVs[3]; - eventpk.CurrentLevel = 100; eventpk.Move1 = SSet.Moves[0]; eventpk.Move2 = SSet.Moves[1]; @@ -470,20 +492,20 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm eventpk.Move3_PP = eventpk.GetMovePP(eventpk.Move3, eventpk.Move3_PPUps); eventpk.Move4_PP = eventpk.GetMovePP(eventpk.Move4, eventpk.Move4_PPUps); - setMarkings(eventpk); - setHappiness(eventpk); + SetMarkings(eventpk); + SetHappiness(eventpk); HyperTrain(eventpk); if (new LegalityAnalysis(eventpk).Valid) return eventpk; - eventpk = SetWCXPID(eventpk, PIDType, Generation, AbilityType, shiny); + eventpk = SetWCXPID(eventpk, PIDType, Generation, AbilityType); LegalityAnalysis la2 = new LegalityAnalysis(eventpk); if (!la2.Valid) { Console.WriteLine(la2.Report(false)); AlternateAbilityRefresh(eventpk); if (new LegalityAnalysis(eventpk).Valid) return eventpk; - if (eventErrorHandling(eventpk, PIDType, AbilityType, Generation, fixedPID)) return eventpk; + if (EventErrorHandling(eventpk, Generation, fixedPID)) return eventpk; prevevent = eventpk; continue; } @@ -499,7 +521,7 @@ public PKM LoadShowdownSetModded_PKSM(PKM Set, ShowdownSet SSet, bool resetForm return Set; } - private void setMarkings(PKM pk) + private void SetMarkings(PKM pk) { if (pk.IV_HP == 31) pk.MarkCircle = 1; if (pk.IV_ATK == 31) pk.MarkTriangle = 1; @@ -521,39 +543,37 @@ private void setMarkings(PKM pk) if (pk.IV_SPE < 29) pk.MarkDiamond = 1; } - private void setHappiness(PKM pk) + private static void SetHappiness(PKM pk) { if (pk.Moves.Contains(218)) pk.CurrentFriendship = 0; else pk.CurrentFriendship = 255; } - private List edgeMons(int Game, PKM pk) + private static List EdgeMons(int Game, PKM pk) { - List edgecase = new List(); - EdgeCaseLegality el = new EdgeCaseLegality(); - var edgecasearray = new EncounterStatic[] { }; - if (Game == (int)GameVersion.B || Game == (int)GameVersion.W) - { - edgecasearray = el.BWEntreeForest; - } - else if (Game == (int)GameVersion.B2 || Game == (int)GameVersion.W2) - { - edgecasearray = el.B2W2EntreeForest; - } - else if (Game == (int)GameVersion.US || Game == (int)GameVersion.UM) + var edgecasearray = GetEdgeCaseArray(Game); + return new List(edgecasearray.Where(e => e.Species == pk.Species)); + } + + private static EncounterStatic[] GetEdgeCaseArray(int Game) + { + switch (Game) { - edgecasearray = el.USUMEdgeEnc; - } - foreach (EncounterStatic e in edgecasearray) { - if (e.Species == pk.Species) - { - edgecase.Add(e); - } + case (int)GameVersion.B: + case (int)GameVersion.W: + return EdgeCaseLegality.BWEntreeForest; + case (int)GameVersion.B2: + case (int)GameVersion.W2: + return EdgeCaseLegality.B2W2EntreeForest; + case (int)GameVersion.US: + case (int)GameVersion.UM: + return EdgeCaseLegality.USUMEdgeEnc; } - return edgecase; + + return new EncounterStatic[] { }; } - private bool eventErrorHandling(PKM pk, int PIDType, int AbilityType, int Generation, uint fixedPID) + private bool EventErrorHandling(PKM pk, int Generation, uint fixedPID) { LegalityAnalysis la = new LegalityAnalysis(pk); var report = la.Report(false); @@ -589,7 +609,7 @@ private bool eventErrorHandling(PKM pk, int PIDType, int AbilityType, int Genera } if (report.Contains(V411)) // V411 = Encounter type PID mismatch { - if ((usesEventBasedMethod(pk.Species, pk.Moves, "M2") && pk.Version == (int)GameVersion.FR) || (usesEventBasedMethod(pk.Species, pk.Moves, "M2") && pk.Version == (int)GameVersion.LG)) + if ((UsesEventBasedMethod(pk.Species, pk.Moves, "M2") && pk.Version == (int)GameVersion.FR) || (UsesEventBasedMethod(pk.Species, pk.Moves, "M2") && pk.Version == (int)GameVersion.LG)) { bool shiny = pk.IsShiny; pk = M2EventFix(pk, shiny); @@ -597,7 +617,7 @@ private bool eventErrorHandling(PKM pk, int PIDType, int AbilityType, int Genera report = UpdateReport(pk); } - if (usesEventBasedMethod(pk.Species, pk.Moves, "BACD_R") && pk.Version == (int)GameVersion.R) + if (UsesEventBasedMethod(pk.Species, pk.Moves, "BACD_R") && pk.Version == (int)GameVersion.R) { bool shiny = pk.IsShiny; pk = BACD_REventFix(pk, pk.IsShiny); @@ -610,7 +630,7 @@ private bool eventErrorHandling(PKM pk, int PIDType, int AbilityType, int Genera return false; } - private PKM SetWCXPID(PKM pk, int PIDType, int Generation, int AbilityType, bool shiny) + private PKM SetWCXPID(PKM pk, int PIDType, int Generation, int AbilityType) { if (Generation == 6 || Generation == 7) { @@ -649,27 +669,30 @@ private PKM SetWCXPID(PKM pk, int PIDType, int Generation, int AbilityType, bool break; } if (pk.PID != 0) - pk.PID = pk.PID; - else { - pk.PID = Util.Rand32(); + pk.PID = pk.PID; + return pk; + } - // Force Gender - do { pk.PID = (pk.PID & 0xFFFFFF00) | Util.Rand32() & 0xFF; } while (!pk.IsGenderValid()); + pk.PID = Util.Rand32(); - // Force Ability - if (av == 1) pk.PID |= 0x10000; else pk.PID &= 0xFFFEFFFF; + // Force Gender + do { pk.PID = (pk.PID & 0xFFFFFF00) | (Util.Rand32() & 0xFF); } + while (!pk.IsGenderValid()); - if (PIDType == 2) // Force Shiny - { - uint gb = pk.PID & 0xFF; - pk.PID = PIDGenerator.GetMG5ShinyPID(gb, (uint)av, pk.TID, pk.SID); - } - else if (PIDType != 1) // Force Not Shiny - { - if (pk.IsShiny) - pk.PID ^= 0x10000000; - } + // Force Ability + if (av == 1) + pk.PID |= 0x10000; else pk.PID &= 0xFFFEFFFF; + + if (PIDType == 2) // Force Shiny + { + uint gb = pk.PID & 0xFF; + pk.PID = PIDGenerator.GetMG5ShinyPID(gb, (uint)av, pk.TID, pk.SID); + } + else if (PIDType != 1) // Force Not Shiny + { + if (pk.IsShiny) + pk.PID ^= 0x10000000; } return pk; } @@ -730,8 +753,8 @@ private bool ValidAbility(int AbilityNumber, int AbilityType) private bool ValidShiny(int PIDType, bool shiny) { - if ((PIDType == 0 && shiny == true) || (PIDType == 1 && shiny == true) || (PIDType == 2 && shiny == true)) return true; - if ((PIDType == 0 && shiny == false) || (PIDType == 1 && shiny == false) || (PIDType == 3 && shiny == false)) return true; + if ((PIDType == 0 && shiny) || (PIDType == 1 && shiny) || (PIDType == 2 && shiny)) return true; + if ((PIDType == 0 && !shiny) || (PIDType == 1 && !shiny) || (PIDType == 3 && !shiny)) return true; return false; } @@ -747,6 +770,7 @@ private PKM SetSuggestedRelearnMoves_PKSM(PKM Set) int[] m = Legality.GetSuggestedRelearn(); if (m.All(z => z == 0)) + { if (!Set.WasEgg && !Set.WasEvent && !Set.WasEventEgg && !Set.WasLink) { if (Set.Version != (int)GameVersion.CXD) @@ -756,6 +780,7 @@ private PKM SetSuggestedRelearnMoves_PKSM(PKM Set) m = encounter.Relearn; } } + } if (Set.RelearnMoves.SequenceEqual(m)) return Set; @@ -770,8 +795,7 @@ private PKM SetSuggestedRelearnMoves_PKSM(PKM Set) private void AlternateAbilityRefresh(PKM pk) { int abilityID = pk.Ability; - int abilityNum = pk.AbilityNumber; - int finalabilitynum = abilityNum; + int finalabilitynum = pk.AbilityNumber; int[] abilityNumList = new int[] { 1, 2, 4 }; for (int i = 0; i < 3; i++) { @@ -791,6 +815,7 @@ private void AlternateAbilityRefresh(PKM pk) pk.AbilityNumber = finalabilitynum; pk.RefreshAbility(pk.AbilityNumber < 6 ? pk.AbilityNumber >> 1 : 0); } + private PKM FixMemoriesPKM(PKM pk) { if (SAV.PKMType == typeof(PK7)) @@ -805,6 +830,7 @@ private PKM FixMemoriesPKM(PKM pk) } return pk; } + public bool CommonErrorHandling2(PKM pk) { string hp = pk.IV_HP.ToString(); @@ -817,13 +843,13 @@ public bool CommonErrorHandling2(PKM pk) var report = la.Report(false); // fucking M2 - if ((usesEventBasedMethod(pk.Species, pk.Moves, "M2") && pk.Version == (int)GameVersion.FR) || (usesEventBasedMethod(pk.Species, pk.Moves, "M2") && pk.Version == (int)GameVersion.LG)) + if ((UsesEventBasedMethod(pk.Species, pk.Moves, "M2") && pk.Version == (int)GameVersion.FR) || (UsesEventBasedMethod(pk.Species, pk.Moves, "M2") && pk.Version == (int)GameVersion.LG)) { pk = M2EventFix(pk, pk.IsShiny); report = UpdateReport(pk); } - if (usesEventBasedMethod(pk.Species, pk.Moves, "BACD_R") && pk.Version == (int)GameVersion.R) + if (UsesEventBasedMethod(pk.Species, pk.Moves, "BACD_R") && pk.Version == (int)GameVersion.R) { pk = BACD_REventFix(pk, pk.IsShiny); report = UpdateReport(pk); @@ -887,14 +913,7 @@ public bool CommonErrorHandling2(PKM pk) } if (report.Contains(V251)) //V251 = PID-Gender mismatch. { - if (pk.Gender == 0) - { - pk.Gender = 1; - } - else - { - pk.Gender = 0; - } + pk.Gender = pk.Gender == 0 ? 1 : 0; report = UpdateReport(pk); } if (report.Contains(V407) || report.Contains(V408)) //V407 = OT from Colosseum/XD cannot be female. V408 = Female OT from Generation 1 / 2 is invalid. @@ -1012,9 +1031,10 @@ public bool CommonErrorHandling2(PKM pk) // All eggs have encounter type none, even if they are from static encounters if (pk.Gen4 && !pk.WasEgg) { + // If there is more than one slot, the get wild encounter have filter for the pkm type encounter like safari/sports ball if (EncounterMatch is EncounterSlot w) - // If there is more than one slot, the get wild encounter have filter for the pkm type encounter like safari/sports ball type = w.TypeEncounter; + if (EncounterMatch is EncounterStaticTyped s) type = s.TypeEncounter; } @@ -1027,51 +1047,34 @@ public bool CommonErrorHandling2(PKM pk) } if (report.Contains(V86)) //V86 = Evolution not valid (or level/trade evolution unsatisfied). { - pk.Met_Level = pk.Met_Level - 1; + pk.Met_Level--; report = UpdateReport(pk); } if (report.Contains(V411)) //V411 = Encounter Type PID mismatch. { - if (pk.Version == (int)GameVersion.CXD) - { pk = setPIDSID(pk, pk.IsShiny, true); } - else pk = setPIDSID(pk, pk.IsShiny); + if (pk.Version == (int) GameVersion.CXD) + pk = SetPIDSID(pk, pk.IsShiny, true); + else + pk = SetPIDSID(pk, pk.IsShiny); + if (new LegalityAnalysis(pk).Valid) - { return false; - } + report = UpdateReport(pk); if (report.Equals(V411)) // V411 = Encounter Type PID mismatch. - { return true; - } - else if (report.Contains(V251)) // V251 = PID-Gender mismatch. + + if (report.Contains(V251)) // V251 = PID-Gender mismatch. { - if (pk.Gender == 0) - { - pk.Gender = 1; - } - else - { - pk.Gender = 0; - } + pk.Gender = pk.Gender == 0 ? 1 : 0; report = UpdateReport(pk); if (new LegalityAnalysis(pk).Valid) - { return false; - } } } if (report.Contains(V41)) // V41 = Can't Hyper Train a Pokémon with perfect IVs. { - if (pk is IHyperTrain h) - { - h.HT_HP = false; - h.HT_ATK = false; - h.HT_DEF = false; - h.HT_SPA = false; - h.HT_SPD = false; - h.HT_SPE = false; - } + ((IHyperTrain)pk).HyperTrainClear(); report = UpdateReport(pk); } if (report.Contains(V42)) // V42 = Can't Hyper Train a perfect IV. @@ -1090,8 +1093,8 @@ public bool CommonErrorHandling2(PKM pk) /* Uncomment to automatically override specified IVs. * Default Behaviour would be to ignore this fix if IVs are specified to be of such values - * - * + * + * if (report.Contains(string.Format(V28, 3))) //V28 = Should have at least {0} IVs = 31. { PKM temp = pk; @@ -1123,7 +1126,7 @@ private string UpdateReport(PKM pk) return report; } - private PKM setPIDSID(PKM pk, bool shiny, bool XD = false) + private PKM SetPIDSID(PKM pk, bool shiny, bool XD = false) { uint hp = (uint)pk.IV_HP; uint atk = (uint)pk.IV_ATK; @@ -1156,7 +1159,7 @@ private PKM setPIDSID(PKM pk, bool shiny, bool XD = false) { string[] hpower = { "fighting", "flying", "poison", "ground", "rock", "bug", "ghost", "steel", "fire", "water", "grass", "electric", "psychic", "ice", "dragon", "dark" }; string hiddenpower = hpower[pk.HPType]; - string[] NatureHPIVs = Misc.IVtoPIDGenerator.getIVPID(nature, hiddenpower, XD); + string[] NatureHPIVs = Misc.IVtoPIDGenerator.GetIVPID(nature, hiddenpower, XD); Console.WriteLine(XD); pk.PID = Util.GetHexValue(NatureHPIVs[0]); if (pk.GenNumber < 5) pk.EncryptionConstant = pk.PID; @@ -1186,14 +1189,7 @@ private PKM setPIDSID(PKM pk, bool shiny, bool XD = false) updatedReport = recheckLA.Report(false); if (updatedReport.Contains("PID-Gender mismatch.")) { - if (pk.Gender == 0) - { - pk.Gender = 1; - } - else - { - pk.Gender = 0; - } + pk.Gender = pk.Gender == 0 ? 1 : 0; LegalityAnalysis recheckLA2 = new LegalityAnalysis(pk); updatedReport = recheckLA2.Report(false); } @@ -1205,18 +1201,18 @@ private PKM setPIDSID(PKM pk, bool shiny, bool XD = false) } LegalityAnalysis Legality = new LegalityAnalysis(pk); if (Legality.Valid) return pk; - // Fix Moves if a slot is empty + // Fix Moves if a slot is empty pk.FixMoves(); // PKX is now filled pk.RefreshChecksum(); pk.RefreshAbility(pk.AbilityNumber < 6 ? pk.AbilityNumber >> 1 : 0); - if (updatedReport.Contains("Invalid: Encounter Type PID mismatch.") || usesEventBasedMethod(pk.Species, pk.Moves, "M2")) + if (updatedReport.Contains("Invalid: Encounter Type PID mismatch.") || UsesEventBasedMethod(pk.Species, pk.Moves, "M2")) { - if (pk.GenNumber == 3 || usesEventBasedMethod(pk.Species, pk.Moves, "M2")) + if (pk.GenNumber == 3 || UsesEventBasedMethod(pk.Species, pk.Moves, "M2")) { pk = M2EventFix(pk, shiny); - if (!new LegalityAnalysis(pk).Report(false).Contains("PID mismatch") || usesEventBasedMethod(pk.Species, pk.Moves, "M2")) return pk; + if (!new LegalityAnalysis(pk).Report(false).Contains("PID mismatch") || UsesEventBasedMethod(pk.Species, pk.Moves, "M2")) return pk; } pk.IV_HP = (int)hp; pk.IV_ATK = (int)atk; @@ -1237,7 +1233,7 @@ private PKM M2EventFix(PKM pk, bool shiny) pk.FatefulEncounter = true; string[] hpower = { "fighting", "flying", "poison", "ground", "rock", "bug", "ghost", "steel", "fire", "water", "grass", "electric", "psychic", "ice", "dragon", "dark" }; string hiddenpower = hpower[pk.HPType]; - string[] NatureHPIVs = Misc.IVtoPIDGenerator.getIVPID((uint)pk.Nature, hiddenpower, false, "M2"); + string[] NatureHPIVs = Misc.IVtoPIDGenerator.GetIVPID((uint)pk.Nature, hiddenpower, false, "M2"); pk.PID = Util.GetHexValue(NatureHPIVs[0]); if (pk.GenNumber < 5) pk.EncryptionConstant = pk.PID; Console.WriteLine(NatureHPIVs[0]); @@ -1252,18 +1248,11 @@ private PKM M2EventFix(PKM pk, bool shiny) string updatedReport = recheckLA.Report(false); if (updatedReport.Contains("PID-Gender mismatch")) { - if (pk.Gender == 0) - { - pk.Gender = 1; - } - else - { - pk.Gender = 0; - } + pk.Gender = pk.Gender == 0 ? 1 : 0; LegalityAnalysis recheckLA2 = new LegalityAnalysis(pk); updatedReport = recheckLA2.Report(false); } - if (!updatedReport.Contains("PID mismatch") || usesEventBasedMethod(pk.Species, pk.Moves, "M2")) return pk; + if (!updatedReport.Contains("PID mismatch") || UsesEventBasedMethod(pk.Species, pk.Moves, "M2")) return pk; Console.WriteLine(UpdateReport(pk)); pk.FatefulEncounter = feFlag; pk.Egg_Location = eggloc; @@ -1278,7 +1267,7 @@ private PKM BACD_REventFix(PKM pk, bool shiny) pk.FatefulEncounter = false; string[] hpower = { "fighting", "flying", "poison", "ground", "rock", "bug", "ghost", "steel", "fire", "water", "grass", "electric", "psychic", "ice", "dragon", "dark" }; string hiddenpower = hpower[pk.HPType]; - string[] NatureHPIVs = Misc.IVtoPIDGenerator.getIVPID((uint)pk.Nature, hiddenpower, false, "BACD_R"); + string[] NatureHPIVs = Misc.IVtoPIDGenerator.GetIVPID((uint)pk.Nature, hiddenpower, false, "BACD_R"); pk.PID = Util.GetHexValue(NatureHPIVs[0]); if (pk.GenNumber < 5) pk.EncryptionConstant = pk.PID; Console.WriteLine(NatureHPIVs[0]); @@ -1293,28 +1282,21 @@ private PKM BACD_REventFix(PKM pk, bool shiny) string updatedReport = recheckLA.Report(false); if (updatedReport.Contains("PID-Gender mismatch")) { - if (pk.Gender == 0) - { - pk.Gender = 1; - } - else - { - pk.Gender = 0; - } + pk.Gender = pk.Gender == 0 ? 1 : 0; LegalityAnalysis recheckLA2 = new LegalityAnalysis(pk); updatedReport = recheckLA2.Report(false); } - if (!updatedReport.Contains("PID mismatch") || usesEventBasedMethod(pk.Species, pk.Moves, "BACD_R")) return pk; + if (!updatedReport.Contains("PID mismatch") || UsesEventBasedMethod(pk.Species, pk.Moves, "BACD_R")) return pk; Console.WriteLine(UpdateReport(pk)); pk.FatefulEncounter = feFlag; pk.Egg_Location = eggloc; return pk; } - public bool usesEventBasedMethod(int Species, int[] Moves, string method) + public bool UsesEventBasedMethod(int Species, int[] Moves, string method) { Dictionary RNGList = new Dictionary(); - if (getRNGListIndex(method) != -1) RNGList = WC3RNGList[getRNGListIndex(method)]; + if (GetRNGListIndex(method) != -1) RNGList = WC3RNGList[GetRNGListIndex(method)]; else return false; if (!RNGList.Keys.Contains(Species)) return false; foreach (int i in Moves) @@ -1324,22 +1306,26 @@ public bool usesEventBasedMethod(int Species, int[] Moves, string method) return false; } - int getRNGListIndex(string Method) + private int GetRNGListIndex(string Method) { - if (Method == "M2") return 0; - else if (Method == "BACD_R") return 1; - else return -1; + switch (Method) + { + case "M2": + return 0; + case "BACD_R": + return 1; + default: + return -1; + } } - private PKM clickMetLocationModPKSM(PKM p) + private PKM ClickMetLocationModPKSM(PKM p) { LegalityAnalysis Legality = new LegalityAnalysis(p); var encounter = Legality.GetSuggestedMetInfo(); if (encounter == null || (p.Format >= 3 && encounter.Location < 0)) - { return p; - } int level = encounter.Level; int location = encounter.Location; @@ -1356,26 +1342,27 @@ private PKM clickMetLocationModPKSM(PKM p) return p; } - private List> generateEvoLists2() + private List> GenerateEvoLists2() { int counter = 0; string line; List> evoList = new List>(); List blankList = new List(); var assembly = Assembly.GetExecutingAssembly(); - var resourceName = "AutoLegalityMod.Resources.txt.evolutions.txt"; - System.IO.Stream stream = assembly.GetManifestResourceStream(resourceName); - System.IO.StreamReader file = new System.IO.StreamReader(stream); + const string resourceName = "AutoLegalityMod.Resources.txt.evolutions.txt"; + var stream = assembly.GetManifestResourceStream(resourceName); + StreamReader file = new StreamReader(stream); while ((line = file.ReadLine()) != null) { - if (line.Trim() == "") + var trim = line.Trim(); + if (trim.Length == 0) { evoList.Add(blankList); blankList = new List(); } else { - blankList.Add(line.Trim()); + blankList.Add(trim); } counter++; } @@ -1406,8 +1393,7 @@ private bool NeedsHyperTraining(PKM pk) if (i == 31) flawless++; if (i == 0 || i == 1) minIVs++; //ignore IV value = 0/1 for intentional IV values (1 for hidden power cases) } - if (flawless + minIVs == 6) return false; - return true; + return flawless + minIVs != 6; } private void HyperTrain(PKM pk) @@ -1425,34 +1411,6 @@ private void HyperTrain(PKM pk) } } - private void UpdateLegality(PKM pkm, bool skipMoveRepop = false) - { - LegalityAnalysis Legality = new LegalityAnalysis(pkm); - Console.WriteLine(Legality.Report(true)); - // Refresh Move Legality - bool[] validmoves = new bool[] { false, false, false, false }; - for (int i = 0; i < 4; i++) - validmoves[i] = !Legality.Info?.Moves[i].Valid ?? false; - - bool[] validrelearn = new bool[] { false, false, false, false }; - if (pkm.Format >= 6) - for (int i = 0; i < 4; i++) - validrelearn[i] = !Legality.Info?.Relearn[i].Valid ?? false; - - if (skipMoveRepop) - return; - // Resort moves - bool fieldsLoaded = true; - bool tmp = fieldsLoaded; - fieldsLoaded = false; - var cb = new[] { pkm.Move1, pkm.Move2, pkm.Move3, pkm.Move4 }; - var moves = Legality.AllSuggestedMovesAndRelearn; - var moveList = GameInfo.MoveDataSource.OrderByDescending(m => moves.Contains(m.Value)).ToArray(); - - fieldsLoaded |= tmp; - LegalityChanged?.Invoke(Legality.Valid, null); - } - private PKM ConvertPL6ToPKM(PL6_PKM pk) { var pi = PersonalTable.AO.GetFormeEntry(pk.Species, pk.Form); @@ -1504,7 +1462,7 @@ private PKM ConvertPL6ToPKM(PL6_PKM pk) IV_SPA = pk.IV_SPA, IV_SPD = pk.IV_SPD, IV_SPE = pk.IV_SPE, - + // Ribbons RibbonCountry = pk.RibbonCountry, RibbonNational = pk.RibbonNational, @@ -1579,6 +1537,7 @@ private PKM ConvertPL6ToPKM(PL6_PKM pk) eventpk.AbilityNumber = 1 << av; if (!pk.IsEgg) + { if (eventpk.CurrentHandler == 0) // OT { eventpk.OT_Memory = 3; @@ -1594,6 +1553,8 @@ private PKM ConvertPL6ToPKM(PL6_PKM pk) eventpk.HT_Feeling = Util.Rand.Next(0, 10); // 0-9 eventpk.HT_Friendship = eventpk.OT_Friendship; } + } + eventpk.IsNicknamed = false; eventpk.Nickname = eventpk.IsNicknamed ? eventpk.Nickname : PKX.GetSpeciesNameGeneration(pk.Species, eventpk.Language, SAV.Generation); eventpk.CurrentFriendship = eventpk.IsEgg ? pi.HatchCycles : pi.BaseFriendship; @@ -1626,7 +1587,7 @@ private PKM ConvertPL6ToPKM(PL6_PKM pk) {108, new[]{273, 215}}, // Lickitung with Wish & Heal Bell {463, new[]{273, 215}}, {113, new[]{273, 230}}, // Chansey with Wish & Sweet Scent - {242, new[]{273, 230}}, + {242, new[]{273, 230}}, {115, new[]{273, 281}}, // Kangaskhan with Wish & Yawn {054, new[]{300}}, // Psyduck with Mud Sport {055, new[]{300}}, @@ -1673,7 +1634,7 @@ private PKM ConvertPL6ToPKM(PL6_PKM pk) {280, new[]{204, 273} }, // Ralts with Charm {281, new[]{204, 273} }, {282, new[]{204, 273} }, - {475, new[]{204, 273} }, + {475, new[]{204, 273} }, {359, new[]{180, 273} }, // Absol with Spite {371, new[]{334, 273} }, // Bagon with Iron Defense {372, new[]{334, 273} }, diff --git a/ExportBoxToShowdown/ExportBoxToShowdown.cs b/ExportBoxToShowdown/ExportBoxToShowdown.cs index ab32abd1..e58849ef 100644 --- a/ExportBoxToShowdown/ExportBoxToShowdown.cs +++ b/ExportBoxToShowdown/ExportBoxToShowdown.cs @@ -51,7 +51,7 @@ private void AddPluginControl(ToolStripDropDownItem tools) { var ctrl = new ToolStripMenuItem(Name); tools.DropDownItems.Add(ctrl); - ctrl.Click += new EventHandler(BoxToShowdown); + ctrl.Click += BoxToShowdown; ctrl.Image = ExportBoxToShowdownResources.exportboxtoshowdown; } @@ -65,13 +65,12 @@ public bool TryLoadFile(string filePath) Console.WriteLine($"{Name} was provided with the file path, but chose to do nothing with it."); return false; // no action taken } + private void BoxToShowdown(object sender, EventArgs e) { try { - IList BoxData = SaveFileEditor.SAV.BoxData; - List BoxList = new List(BoxData); - List CurrBox = BoxList.GetRange(SaveFileEditor.CurrentBox * SaveFileEditor.SAV.BoxSlotCount, SaveFileEditor.SAV.BoxSlotCount); + var CurrBox = SaveFileEditor.SAV.GetBoxData(SaveFileEditor.SAV.CurrentBox); var str = ShowdownSet.GetShowdownSets(CurrBox, Environment.NewLine + Environment.NewLine); if (string.IsNullOrWhiteSpace(str)) return; Clipboard.SetText(str); diff --git a/ExportBoxToShowdown/ExportBoxToShowdown.csproj b/ExportBoxToShowdown/ExportBoxToShowdown.csproj index e0d20423..9cfdc536 100644 --- a/ExportBoxToShowdown/ExportBoxToShowdown.csproj +++ b/ExportBoxToShowdown/ExportBoxToShowdown.csproj @@ -37,12 +37,6 @@ - - - - - - diff --git a/ExportQRCodes/ExportQRCodes.cs b/ExportQRCodes/ExportQRCodes.cs index 4f44da65..69ecc00b 100644 --- a/ExportQRCodes/ExportQRCodes.cs +++ b/ExportQRCodes/ExportQRCodes.cs @@ -52,7 +52,7 @@ private void AddPluginControl(ToolStripDropDownItem tools) { var ctrl = new ToolStripMenuItem(Name); tools.DropDownItems.Add(ctrl); - ctrl.Click += new EventHandler(ExportQRs); + ctrl.Click += ExportQRs; ctrl.Image = ExportQRCodesResources.exportqrcode; } @@ -65,18 +65,17 @@ private void ExportQRs(object sender, EventArgs e) MessageBox.Show("Box Data is null"); } int ctr = 0; - Dictionary qrcodes = new Dictionary(); + var qrcodes = new Dictionary(); foreach (PKM pk in boxdata) { if (pk.Species == 0 || !pk.Valid || (pk.Box - 1) != SaveFileEditor.CurrentBox) continue; ctr++; - Image qr; - qr = QR.GenerateQRCode7((PK7)pk); - if (qr == null) continue; - + Image qr = QR.GenerateQRCode7((PK7)pk); + if (qr == null) + continue; + string[] r = pk.QRText; - string refer = "PKHeX Auto Legality Mod"; qrcodes.Add(Util.CleanFileName(pk.FileName), RefreshImage(qr)); } if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "qrcodes"))) diff --git a/ExportQRCodes/ExportQRCodes.csproj b/ExportQRCodes/ExportQRCodes.csproj index ba5ba7ad..c77f663c 100644 --- a/ExportQRCodes/ExportQRCodes.csproj +++ b/ExportQRCodes/ExportQRCodes.csproj @@ -37,12 +37,6 @@ - - - - - - diff --git a/ExportQRCodes/ImageUtil.cs b/ExportQRCodes/ImageUtil.cs index 73122a9b..117cc398 100644 --- a/ExportQRCodes/ImageUtil.cs +++ b/ExportQRCodes/ImageUtil.cs @@ -21,6 +21,7 @@ public static Bitmap LayerImage(Image baseLayer, Image overLayer, int x, int y, } return img; } + public static Bitmap ChangeOpacity(Image img, double trans) { if (img == null) @@ -38,6 +39,7 @@ public static Bitmap ChangeOpacity(Image img, double trans) return bmp; } + public static Bitmap ChangeAllColorTo(Image img, Color c) { if (img == null) @@ -55,6 +57,7 @@ public static Bitmap ChangeAllColorTo(Image img, Color c) return bmp; } + public static Bitmap ToGrayscale(Image img) { if (img == null) @@ -72,18 +75,21 @@ public static Bitmap ToGrayscale(Image img) return bmp; } + private static void GetBitmapData(Bitmap bmp, out BitmapData bmpData, out IntPtr ptr, out byte[] data) { bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); ptr = bmpData.Scan0; data = new byte[bmp.Width * bmp.Height * 4]; } + public static Bitmap GetBitmap(byte[] data, int width, int height, int stride = -1, PixelFormat format = PixelFormat.Format32bppArgb) { if (stride == -1 && format == PixelFormat.Format32bppArgb) stride = 4 * width; // defaults return new Bitmap(width, height, stride, format, Marshal.UnsafeAddrOfPinnedArrayElement(data, 0)); } + public static byte[] GetPixelData(Bitmap bitmap) { var argbData = new byte[bitmap.Width * bitmap.Height * 4]; @@ -92,11 +98,13 @@ public static byte[] GetPixelData(Bitmap bitmap) bitmap.UnlockBits(bd); return argbData; } + private static void SetAllTransparencyTo(byte[] data, double trans) { for (int i = 0; i < data.Length; i += 4) data[i + 3] = (byte)(data[i + 3] * trans); } + private static void SetAllColorTo(byte[] data, Color c) { byte R = c.R; @@ -111,13 +119,14 @@ private static void SetAllColorTo(byte[] data, Color c) data[i + 2] = R; } } + private static void SetAllColorToGrayScale(byte[] data) { for (int i = 0; i < data.Length; i += 4) { if (data[i + 3] == 0) continue; - byte greyS = (byte)((0.3 * data[i + 2] + 0.59 * data[i + 1] + 0.11 * data[i + 0]) / 3); + byte greyS = (byte)(((0.3 * data[i + 2]) + (0.59 * data[i + 1]) + (0.11 * data[i + 0])) / 3); data[i + 0] = greyS; data[i + 1] = greyS; data[i + 2] = greyS; diff --git a/ExportQRCodes/QR.cs b/ExportQRCodes/QR.cs index 33b9385e..c2d725d9 100644 --- a/ExportQRCodes/QR.cs +++ b/ExportQRCodes/QR.cs @@ -8,7 +8,7 @@ public partial class QR { private Image finalqr; private readonly PKM pkm; - private Image qr; + private readonly Image qr; public QR(Image qr, PKM pk) { @@ -35,6 +35,7 @@ public static Image GenerateQRCode7(PK7 pk7, int box = 0, int slot = 0, int num_ byte[] data = QR7.GenerateQRData(pk7, box, slot, num_copies); return GenerateQRCode(data, ppm: 4); } + private static Image GenerateQRCode(byte[] data, int ppm = 4) { using (var generator = new QRCodeGenerator()) diff --git a/ExportTrainerData/ExportTrainerData.cs b/ExportTrainerData/ExportTrainerData.cs index 943af20a..f01d1a43 100644 --- a/ExportTrainerData/ExportTrainerData.cs +++ b/ExportTrainerData/ExportTrainerData.cs @@ -48,7 +48,7 @@ private void AddPluginControl(ToolStripDropDownItem tools) { var ctrl = new ToolStripMenuItem(Name); tools.DropDownItems.Add(ctrl); - ctrl.Click += new EventHandler(ExportData); + ctrl.Click += ExportData; ctrl.Image = ExportTrainerDataResources.exporttrainerdata; } @@ -82,16 +82,17 @@ private void ExportData(object sender, EventArgs e) Country = pk.Country.ToString(); SubRegion = pk.Region.ToString(); ConsoleRegion = pk.ConsoleRegion.ToString(); - writeTxtFile(TID, SID, OT, Gender, Country, SubRegion, ConsoleRegion); + WriteTxtFile(TID, SID, OT, Gender, Country, SubRegion, ConsoleRegion); MessageBox.Show("trainerdata.txt Successfully Exported in the same directory as PKHeX"); } catch { - writeTxtFile(TID, SID, OT, Gender, Country, SubRegion, ConsoleRegion); + WriteTxtFile(TID, SID, OT, Gender, Country, SubRegion, ConsoleRegion); MessageBox.Show("Some of the fields were wrongly filled. Exported the default trainerdata.txt"); } } - private void writeTxtFile(string TID, string SID, string OT, string Gender, string Country, string SubRegion, string ConsoleRegion) + + private void WriteTxtFile(string TID, string SID, string OT, string Gender, string Country, string SubRegion, string ConsoleRegion) { string[] lines = { "TID:" + TID, "SID:" + SID, "OT:" + OT, "Gender:" + Gender, "Country:" + Country, "SubRegion:" + SubRegion, "3DSRegion:" + ConsoleRegion }; System.IO.File.WriteAllLines(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "trainerdata.txt"), lines); diff --git a/ExportTrainerData/ExportTrainerData.csproj b/ExportTrainerData/ExportTrainerData.csproj index 63506dbf..08bf8fc1 100644 --- a/ExportTrainerData/ExportTrainerData.csproj +++ b/ExportTrainerData/ExportTrainerData.csproj @@ -37,12 +37,6 @@ - - - - - - diff --git a/LegalizeBoxes/LegalizeBoxes.cs b/LegalizeBoxes/LegalizeBoxes.cs index cebaee93..ea73ea8f 100644 --- a/LegalizeBoxes/LegalizeBoxes.cs +++ b/LegalizeBoxes/LegalizeBoxes.cs @@ -52,7 +52,7 @@ private void AddPluginControl(ToolStripDropDownItem tools) { var ctrl = new ToolStripMenuItem(Name); tools.DropDownItems.Add(ctrl); - ctrl.Click += new EventHandler(Legalize); + ctrl.Click += Legalize; ctrl.Image = LegalizeBoxesResources.legalizeboxes; } @@ -78,10 +78,11 @@ private void Legalize(object sender, EventArgs e) PKM illegalPK = PKMEditor.PreparePKM(); bool box = false; if ((Control.ModifierKeys & Keys.Control) == Keys.Control) - { box = true; - } - if (box) illegalPK = BoxData[SaveFileEditor.CurrentBox * SaveFileEditor.SAV.BoxSlotCount + i]; + + if (box && BoxData.Count > (SaveFileEditor.CurrentBox * SaveFileEditor.SAV.BoxSlotCount) + i) + illegalPK = BoxData[(SaveFileEditor.CurrentBox * SaveFileEditor.SAV.BoxSlotCount) + i]; + if (illegalPK.Species > 0 && !new LegalityAnalysis(illegalPK).Valid) { ShowdownSet Set = new ShowdownSet(ShowdownSet.GetShowdownText(illegalPK)); @@ -97,13 +98,20 @@ private void Legalize(object sender, EventArgs e) catch { satisfied = false; } if (!satisfied) { - BruteForce b = new BruteForce(); - b.SAV = SaveFileEditor.SAV; + BruteForce b = new BruteForce { SAV = SaveFileEditor.SAV }; legal = b.LoadShowdownSetModded_PKSM(illegalPK, Set, resetForm, illegalPK.TID, illegalPK.SID, illegalPK.OT_Name, illegalPK.OT_Gender); } - else legal = APIGenerated; + else + { + legal = APIGenerated; + } + legal = AutoLegalityMod.AutoLegalityMod.SetTrainerData(illegalPK.OT_Name, illegalPK.TID, illegalPK.SID, illegalPK.OT_Gender, legal, satisfied); - if (box) BoxData[SaveFileEditor.CurrentBox * SaveFileEditor.SAV.BoxSlotCount + i] = legal; + + if (box) + { + BoxData[(SaveFileEditor.CurrentBox * SaveFileEditor.SAV.BoxSlotCount) + i] = legal; + } else { PKMEditor.PopulateFields(legal); diff --git a/LegalizeBoxes/LegalizeBoxes.csproj b/LegalizeBoxes/LegalizeBoxes.csproj index 6234ebf2..903e5d1f 100644 --- a/LegalizeBoxes/LegalizeBoxes.csproj +++ b/LegalizeBoxes/LegalizeBoxes.csproj @@ -37,12 +37,6 @@ - - - - - - diff --git a/MGDBDownloader/MGDBDownloader.cs b/MGDBDownloader/MGDBDownloader.cs index e6b762fc..a1992126 100644 --- a/MGDBDownloader/MGDBDownloader.cs +++ b/MGDBDownloader/MGDBDownloader.cs @@ -53,7 +53,7 @@ private void AddPluginControl(ToolStripDropDownItem tools) { var ctrl = new ToolStripMenuItem(Name); tools.DropDownItems.Add(ctrl); - ctrl.Click += new EventHandler(DownloadMGDB); + ctrl.Click += DownloadMGDB; ctrl.Image = MGDBDownloaderResources.mgdbdownload; } @@ -72,11 +72,11 @@ public void DownloadMGDB(object o, EventArgs e) DialogResult latestCommit = MessageBox.Show("Download the entire database, which includes past generation events?\nSelecting No will download only the public release of the database.", "Download entire database?", MessageBoxButtons.YesNo); if (latestCommit == DialogResult.Yes) { - string mgdbURL = @"https://github.com/projectpokemon/EventsGallery/archive/master.zip"; + const string mgdbURL = "https://github.com/projectpokemon/EventsGallery/archive/master.zip"; WebClient client = new WebClient(); - string mgdbZipPath = @"mgdb.zip"; + const string mgdbZipPath = "mgdb.zip"; client.DownloadFile(new Uri(mgdbURL), mgdbZipPath); ZipFile.ExtractToDirectory(mgdbZipPath, MGDatabasePath); File.Delete("mgdb.zip"); @@ -92,7 +92,7 @@ public void DownloadMGDB(object o, EventArgs e) string json_data = DownloadString("https://api.github.com/repos/projectpokemon/EventsGallery/releases/latest"); string mgdbURL = json_data.Split(new string[] { "browser_download_url" }, StringSplitOptions.None)[1].Substring(3).Split('"')[0]; Console.WriteLine(mgdbURL); - string mgdbZipPath = @"mgdb.zip"; + const string mgdbZipPath = "mgdb.zip"; client.DownloadFile(new Uri(mgdbURL), mgdbZipPath); ZipFile.ExtractToDirectory(mgdbZipPath, MGDatabasePath); File.Delete("mgdb.zip"); @@ -105,7 +105,7 @@ public static string DownloadString(string address) { using (WebClient client = new WebClient()) { - HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/projectpokemon/EventsGallery/releases/latest"); + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address); request.Method = "GET"; request.UserAgent = "PKHeX-Auto-Legality-Mod"; request.Accept = "application/json"; diff --git a/PGLRentalLegality/CryptoUtil.cs b/PGLRentalLegality/CryptoUtil.cs index 6dff6680..41aa69a7 100644 --- a/PGLRentalLegality/CryptoUtil.cs +++ b/PGLRentalLegality/CryptoUtil.cs @@ -1,11 +1,9 @@ -using System; -using System.Security.Cryptography; +using System.Security.Cryptography; -namespace PKHeX.WinForms.Misc +namespace PGLRentalLegality { - public partial class Util + public static class CryptoUtil { - /// /// Creates a new instance of , or if not supported by the current platform. /// diff --git a/PGLRentalLegality/DataFetch.cs b/PGLRentalLegality/DataFetch.cs new file mode 100644 index 00000000..136a5905 --- /dev/null +++ b/PGLRentalLegality/DataFetch.cs @@ -0,0 +1,129 @@ +using System; + +using PKHeX.Core; + +namespace PGLRentalLegality +{ + public static class DataFetch + { + public static string GetSpecies(ushort ID, int form) + { + try + { + if (form > 0) + { + //Has a different form from normal + foreach (string line in GetCSV("pokemonFormAbilities")) + { + var currLine = line.Split(','); + if (int.Parse(currLine[0]) == ID && int.Parse(currLine[1]) == form) + return currLine[2]; + } + } + return Util.GetStringList("text_Species_en")[ID]; + } + catch (Exception) + { + return ID.ToString(); + } + } + + public static string GetMove(ushort ID, QRPoke p) + { + string[] names = Util.GetStringList("text_Moves_en"); + try + { + if (names[ID] == "Hidden Power") + { + return "Hidden Power [" + p.GetHiddenPowerType() + "]"; + } + return names[ID]; + } + catch (Exception) + { + return ID.ToString(); + } + } + + public static string GetAbility(ushort ID, int form, int ability) + { + //Update to deal with the 1,2,4. + /* + * P3DS thoughts: + * - Split abilities into abilities and forms w/ different abilities + * - Then, first check if Pokemon has a form ID > 0. If it does, check the form list for it + * since it will require more processing than a standard list like normal. + * - Maybe include an exclusion list as well, to help sort the out. + * + */ + + try + { + if (form > 0) + { + //Has a different form from normal + foreach (string line in GetCSV("pokemonFormAbilities")) + { + var currLine = line.Split(','); + if (int.Parse(currLine[0]) == ID) + { + if (int.Parse(currLine[1]) == form) + { + return currLine[3 + (int)Math.Log(ability, 2)]; + } + } + } + } + return GetCSV("pokemonAbilities")[ID].Split(',')[(int)Math.Log(ability, 2)]; + } + catch (Exception) + { + return ability.ToString(); + } + } + + public static string GetItem(ushort ID) + { + string[] names = Util.GetStringList("text_Items_en"); + try + { + return names[ID]; + } + catch (Exception) + { + return ID.ToString(); + } + } + + public static string GetNature(byte ID) + { + string[] names = Util.GetStringList("text_Natures_en"); + try + { + return names[ID]; + } + catch (Exception) + { + return ID.ToString(); + } + } + + private static string[] GetCSV(string loc) + { + var assembly = System.Reflection.Assembly.GetExecutingAssembly(); + var resourceName = "PGLRentalLegality.Resources.text." + loc + ".csv"; + System.IO.Stream stream = assembly.GetManifestResourceStream(resourceName); + System.IO.StreamReader file = new System.IO.StreamReader(stream); + var txt = file.ReadToEnd(); + if (txt == null) + return new string[0]; + + string[] rawlist = (txt).Split('\n'); + + for (int i = 0; i < rawlist.Length; i++) + rawlist[i] = rawlist[i].Trim(); + + return rawlist; + } + } +} \ No newline at end of file diff --git a/PGLRentalLegality/PGLRentalLegality.cs b/PGLRentalLegality/PGLRentalLegality.cs index 02b6a77e..eb669753 100644 --- a/PGLRentalLegality/PGLRentalLegality.cs +++ b/PGLRentalLegality/PGLRentalLegality.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Windows.Forms; using PKHeX.Core; using AutoLegalityMod; @@ -12,11 +11,11 @@ public class PGLRentalLegality : IPlugin public int Priority => 1; public ISaveFileProvider SaveFileEditor { get; private set; } public IPKMView PKMEditor { get; private set; } - public object[] arguments { get; private set; } + public object[] Arguments { get; private set; } public void Initialize(params object[] args) { - arguments = args; + Arguments = args; Console.WriteLine($"[Auto Legality Mod] Loading {Name}"); if (args == null) return; @@ -52,7 +51,7 @@ private void AddPluginControl(ToolStripDropDownItem tools) { var ctrl = new ToolStripMenuItem(Name); tools.DropDownItems.Add(ctrl); - ctrl.Click += new EventHandler(PGLShowdownSet); + ctrl.Click += PGLShowdownSet; ctrl.Image = PGLRentalLegalityResources.pglqrcode; ctrl.ShortcutKeys = (Keys.Alt | Keys.Q); } @@ -60,9 +59,9 @@ private void AddPluginControl(ToolStripDropDownItem tools) private void PGLShowdownSet(object sender, EventArgs e) { if (!Clipboard.ContainsImage()) return; - PKHeX.WinForms.Misc.RentalTeam rentalTeam = new PKHeX.WinForms.Misc.QRParser().decryptQRCode(Clipboard.GetImage()); + var rentalTeam = new QRParser().decryptQRCode(Clipboard.GetImage()); string data = ""; - foreach (PKHeX.WinForms.Misc.Pokemon p in rentalTeam.team) + foreach (QRPoke p in rentalTeam.team) { data += p.ToShowdownFormat(false) + Environment.NewLine + Environment.NewLine; } diff --git a/PGLRentalLegality/PGLRentalLegality.csproj b/PGLRentalLegality/PGLRentalLegality.csproj index e599c462..df56840f 100644 --- a/PGLRentalLegality/PGLRentalLegality.csproj +++ b/PGLRentalLegality/PGLRentalLegality.csproj @@ -40,15 +40,10 @@ - - - - - - + True @@ -92,7 +87,6 @@ - diff --git a/PGLRentalLegality/QRParser.cs b/PGLRentalLegality/QRParser.cs index 784527d3..2cc8a1ae 100644 --- a/PGLRentalLegality/QRParser.cs +++ b/PGLRentalLegality/QRParser.cs @@ -14,186 +14,45 @@ using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; -namespace PKHeX.WinForms.Misc -{ - public partial class DataFetch - { - public static string getSpecies(ushort ID, int form) - { - - try - { - if (form > 0) - { - //Has a different form from normal - foreach (string line in getCSV("pokemonFormAbilities")) - { - var currLine = line.Split(','); - if (int.Parse(currLine[0]) == ID) - { - if (int.Parse(currLine[1]) == form) - { - return currLine[2]; - } - } - } - } - return PKHeX.Core.Util.GetStringList("text_Species_en")[ID]; - - } - catch (Exception e) - { - return ID.ToString(); - } - } - public static string getMove(ushort ID, Pokemon p) - { - string[] names = PKHeX.Core.Util.GetStringList("text_Moves_en"); - try - { - if (names[ID] == "Hidden Power") - { - return "Hidden Power [" + p.getHiddenPowerType() + "]"; - } - return names[ID]; - } - catch (Exception e) - { - return ID.ToString(); - } - } - public static string getAbility(ushort ID, int form, int ability) - { - //Update to deal with the 1,2,4. - /* - * P3DS thoughts: - * - Split abilities into abilities and forms w/ different abilities - * - Then, first check if Pokemon has a form ID > 0. If it does, check the form list for it - * since it will require more processing than a standard list like normal. - * - Maybe include an exclusion list as well, to help sort the out. - * - */ - - try - { - if (form > 0) - { - //Has a different form from normal - foreach (string line in getCSV("pokemonFormAbilities")) - { - var currLine = line.Split(','); - if (int.Parse(currLine[0]) == ID) - { - if (int.Parse(currLine[1]) == form) - { - return currLine[3 + (int)Math.Log(ability, 2)]; - } - } - } - } - return getCSV("pokemonAbilities")[ID].Split(',')[(int)Math.Log(ability, 2)]; - - } - catch (Exception e) - { - return ability.ToString(); - } +using PKHeX.Core; - } - public static string getItem(ushort ID) - { - string[] names = PKHeX.Core.Util.GetStringList("text_Items_en"); - try - { - return names[ID]; - } - catch (Exception e) - { - return ID.ToString(); - } - } - public static string getNature(byte ID) - { - string[] names = PKHeX.Core.Util.GetStringList("text_Natures_en"); - try - { - return names[ID]; - } - catch (Exception e) - { - return ID.ToString(); - } - } - private static string[] getCSV(string loc) - { - var assembly = System.Reflection.Assembly.GetExecutingAssembly(); - var resourceName = "PGLRentalLegality.Resources.text." + loc + ".csv"; - System.IO.Stream stream = assembly.GetManifestResourceStream(resourceName); - System.IO.StreamReader file = new System.IO.StreamReader(stream); - var txt = file.ReadToEnd(); - if (txt == null) - return new string[0]; - - string[] rawlist = (txt).Split('\n'); - - for (int i = 0; i < rawlist.Length; i++) - rawlist[i] = rawlist[i].Trim(); - - return rawlist; - } - private static string[] getList(string loc) - { - var assembly = System.Reflection.Assembly.GetExecutingAssembly(); - var resourceName = "PKHeX.Core.Resources.text.en."+ loc +".txt"; - System.IO.Stream stream = assembly.GetManifestResourceStream(resourceName); - System.IO.StreamReader file = new System.IO.StreamReader(stream); - var txt = file.ReadToEnd(); - if (txt == null) - return new string[0]; - - string[] rawlist = (txt).Split('\n'); - - for (int i = 0; i < rawlist.Length; i++) - rawlist[i] = rawlist[i].Trim(); - - return rawlist; - } - } - public partial class Pokemon +namespace PGLRentalLegality +{ + public class QRPoke { - uint Key; - byte HyperTrainingFlags; - byte field_5; - byte field_6; - byte field_7; - byte[] PPUps; - uint IvFlags; - uint field_10; - ushort MonsNo; - ushort HoldItem; - ushort[] Moves; - byte field_20; - byte AbilityFlags; - byte Nature; - byte EncounterFlags; - byte EffortHp; - byte EffortAtk; - byte EffortDef; - byte EffortSpeed; - byte EffortSpAtk; - byte EffortSpDef; - byte field_2A; - byte Familiarity; - byte Pokeball; - byte Level; - byte CassetteVersion; - byte LangId; - byte[] rawData; - string gender; - int formID; - int[] IVs; - - public Pokemon(byte[] pkmData) + private readonly uint Key; + private readonly byte HyperTrainingFlags; + private readonly byte field_5; + private readonly byte field_6; + private readonly byte field_7; + private readonly byte[] PPUps; + private readonly uint IvFlags; + private readonly uint field_10; + private readonly ushort MonsNo; + private readonly ushort HoldItem; + private readonly ushort[] Moves; + private readonly byte field_20; + private readonly byte AbilityFlags; + private readonly byte Nature; + private readonly byte EncounterFlags; + private readonly byte EffortHp; + private readonly byte EffortAtk; + private readonly byte EffortDef; + private readonly byte EffortSpeed; + private readonly byte EffortSpAtk; + private readonly byte EffortSpDef; + private readonly byte field_2A; + private readonly byte Familiarity; + private readonly byte Pokeball; + private readonly byte Level; + private readonly byte CassetteVersion; + private readonly byte LangId; + private readonly byte[] rawData; + private readonly string gender; + private readonly int formID; + private readonly int[] IVs; + + public QRPoke(byte[] pkmData) { Console.WriteLine(pkmData.Length); try @@ -224,7 +83,7 @@ public Pokemon(byte[] pkmData) Nature = pkmData[34]; EncounterFlags = pkmData[35]; - //From Project Pokemon. + //From Project Pokemon. //Stored as: Bit 0: Fateful Encounter, Bit 1: Female, Bit 2: Genderless, Bits 3-7: Form Data. gender = ((EncounterFlags & 0x2) != 0) ? "(F) " : ((EncounterFlags & 0x4) != 0) ? "" : "(M) "; @@ -268,31 +127,28 @@ public Pokemon(byte[] pkmData) } } - public String getHiddenPowerType() + public String GetHiddenPowerType() { - string rtn = ""; - int type = IVs[0] % 2 + (IVs[1] % 2) * 2 + (IVs[2] % 2) * 4 + (IVs[5] % 2) * 8 + (IVs[3] % 2) * 16 + (IVs[4] % 2) * 32; - type = (type * 15) / 63; - switch (type) + switch (HiddenPower.GetType(IVs)) { - case 0: rtn = "Fighting"; break; - case 1: rtn = "Flying"; break; - case 2: rtn = "Poison"; break; - case 3: rtn = "Ground"; break; - case 4: rtn = "Rock"; break; - case 5: rtn = "Bug"; break; - case 6: rtn = "Ghost"; break; - case 7: rtn = "Steel"; break; - case 8: rtn = "Fire"; break; - case 9: rtn = "Water"; break; - case 10: rtn = "Grass"; break; - case 11: rtn = "Electric"; break; - case 12: rtn = "Psychic"; break; - case 13: rtn = "Ice"; break; - case 14: rtn = "Dragon"; break; - case 15: rtn = "Dark"; break; + case 0: return "Fighting"; + case 1: return "Flying"; + case 2: return "Poison"; + case 3: return "Ground"; + case 4: return "Rock"; + case 5: return "Bug"; + case 6: return "Ghost"; + case 7: return "Steel"; + case 8: return "Fire"; + case 9: return "Water"; + case 10: return "Grass"; + case 11: return "Electric"; + case 12: return "Psychic"; + case 13: return "Ice"; + case 14: return "Dragon"; + case 15: return "Dark"; } - return rtn; + return string.Empty; } public string ToShowdownFormat(bool HT) @@ -332,23 +188,23 @@ public string ToShowdownFormat(bool HT) string[] format = { - DataFetch.getSpecies(MonsNo,formID) + /*" (" +")" +*/ " @ " + DataFetch.getItem(HoldItem), - "Ability: "+DataFetch.getAbility(MonsNo,formID,AbilityFlags), + DataFetch.GetSpecies(MonsNo,formID) + /*" (" +")" +*/ " @ " + DataFetch.GetItem(HoldItem), + "Ability: "+DataFetch.GetAbility(MonsNo,formID,AbilityFlags), "Level: "+Level, "Happiness: 0", "EVs: " + EffortHp + " HP / " + EffortAtk + " Atk / " + EffortDef + " Def / " + EffortSpAtk + " SpA / " + EffortSpDef + " SpD / " + EffortSpeed + " Spe", - DataFetch.getNature(Nature) + " Nature", + DataFetch.GetNature(Nature) + " Nature", "IVs: " + IVString[0] + " HP / " + IVString[1] + " Atk / " + IVString[2] + " Def / " + IVString[3] + " SpA / " + IVString[4] + " SpD / " + IVString[5] + " Spe ", - " - " + DataFetch.getMove(Moves[0],this), - " - " + DataFetch.getMove(Moves[1],this), - " - " + DataFetch.getMove(Moves[2],this), - " - " + DataFetch.getMove(Moves[3],this) + " - " + DataFetch.GetMove(Moves[0],this), + " - " + DataFetch.GetMove(Moves[1],this), + " - " + DataFetch.GetMove(Moves[2],this), + " - " + DataFetch.GetMove(Moves[3],this) }; return string.Join("\n", format); } - public string getStatsData() + public string GetStatsData() { string HTFlags = Convert.ToString(HyperTrainingFlags, 2); for (int i = 0; i < 30 - HTFlags.Length; i++) @@ -373,12 +229,11 @@ public string getStatsData() { HT += "X"; } - } string[] format = { - "Item: " + DataFetch.getItem(HoldItem), + "Item: " + DataFetch.GetItem(HoldItem), HT, "EVs: " + EffortHp + "H " + EffortAtk + "A " + EffortDef + "B " + EffortSpAtk + "C " + EffortSpDef + "D " + EffortSpeed + "S", "IVs: " + IVs[0] + "/" + IVs[1] + "/" + IVs[2] + "/" + IVs[3] + "/" + IVs[4] + "/" + IVs[5] @@ -387,14 +242,14 @@ public string getStatsData() return string.Join("\n", format); } - public string getMovesString() + public string GetMovesString() { string[] format = { - " - " + DataFetch.getMove(Moves[0],this), - " - " + DataFetch.getMove(Moves[1],this), - " - " + DataFetch.getMove(Moves[2],this), - " - " + DataFetch.getMove(Moves[3],this) + " - " + DataFetch.GetMove(Moves[0],this), + " - " + DataFetch.GetMove(Moves[1],this), + " - " + DataFetch.GetMove(Moves[2],this), + " - " + DataFetch.GetMove(Moves[3],this) }; return string.Join("\n", format); @@ -406,43 +261,42 @@ public override string ToString() { return "\n" + ToShowdownFormat(true) + "\n"; } - catch (Exception e) + catch (Exception) { return "No Pokemon in this Slot"; } } } - public partial class RentalTeam + + public class RentalTeam { - public List team; + public List team; public byte[] GLid; public byte[] UnknownData; public RentalTeam(byte[] data) { Console.WriteLine(data.Length); - team = new List(); - team.Add(new Pokemon(data.Take(0x30).ToArray())); - team.Add(new Pokemon(data.Skip(0x30).Take(0x30).ToArray())); - team.Add(new Pokemon(data.Skip(0x60).Take(0x30).ToArray())); - team.Add(new Pokemon(data.Skip(0x90).Take(0x30).ToArray())); - team.Add(new Pokemon(data.Skip(0xC0).Take(0x30).ToArray())); - team.Add(new Pokemon(data.Skip(0xF0).Take(0x30).ToArray())); - - foreach (Pokemon p in team) - { + team = new List(); + team.Add(new QRPoke(data.Take(0x30).ToArray())); + team.Add(new QRPoke(data.Skip(0x30).Take(0x30).ToArray())); + team.Add(new QRPoke(data.Skip(0x60).Take(0x30).ToArray())); + team.Add(new QRPoke(data.Skip(0x90).Take(0x30).ToArray())); + team.Add(new QRPoke(data.Skip(0xC0).Take(0x30).ToArray())); + team.Add(new QRPoke(data.Skip(0xF0).Take(0x30).ToArray())); + + foreach (QRPoke p in team) Console.WriteLine(p.ToShowdownFormat(true) + "\n"); - } GLid = data.Skip(0x120).Take(8).ToArray(); UnknownData = data.Skip(0x128).ToArray(); } } - public partial class QRParser + + public class QRParser { private string sID, tID, cookie; - public QRParser() { sID = ""; @@ -466,7 +320,6 @@ public void printByteArray(byte[] b) public Image getQRData() { - byte[] data = Encoding.ASCII.GetBytes("savedataId=" + sID + "&battleTeamCd=" + tID); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://3ds.pokemon-gl.com/frontendApi/battleTeam/getQr"); @@ -497,25 +350,23 @@ public Image getQRData() { return Image.FromStream(stream); } - catch (Exception e) + catch (Exception) { //invalid QR return null; } - } } } public byte[] parseQR(Image q) { - Bitmap bitmap = new Bitmap(q); + var bitmap = new Bitmap(q); var img = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height); var hybrid = new HybridBinarizer(img); - BinaryBitmap binaryMap = new BinaryBitmap(hybrid); + var binaryMap = new BinaryBitmap(hybrid); var reader = new QRCodeReader().decode(binaryMap, null); - byte[] data = Array.ConvertAll(reader.RawBytes, (a) => (byte)(a)); - return data; + return Array.ConvertAll(reader.RawBytes, a => (byte)a); } public byte[] shiftArray(byte[] b) @@ -528,7 +379,7 @@ public byte[] shiftArray(byte[] b) byte B = b[i]; lb = (byte)((B & 0xF0) >> 4); array[i] = (byte)(rb << 4 | lb); - rb = (byte)((B & 0xF)); + rb = (byte)(B & 0xF); } return array; @@ -574,15 +425,14 @@ public RentalTeam decryptQRCode(Image QR) var qrue = data.Skip(3).ToArray(); //MEME CRYPTO!!! De-Meme the data - if (!Core.MemeCrypto.VerifyMemePOKE(qrue, out var qrt)) + if (!MemeCrypto.VerifyMemePOKE(qrue, out var qrt)) { Console.WriteLine("it failed"); return null; } else { - - //unencrypt the data in the plaintext. + //unencrypt the data in the plaintext. byte[] qrDec = qr_t(qrt); //build the rental team. diff --git a/PGLRentalLegality/ZXing/MDecoder.cs b/PGLRentalLegality/ZXing/MDecoder.cs deleted file mode 100644 index ae054aa1..00000000 --- a/PGLRentalLegality/ZXing/MDecoder.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Drawing; - -using System.Diagnostics; - -using com.google.zxing.qrcode; -using com.google.zxing; -using com.google.zxing.common; -using com.google.zxing.qrcode.decoder; -using com.google.zxing.qrcode.detector; - -namespace QRDecoder -{ - class MDecoder - { - private Bitmap srcPicture; - - public void setPicture(Bitmap pic) - { - this.srcPicture = pic; - } - - public Bitmap getPicture() - { - return this.srcPicture; - } - - public string MDecode(Bitmap pic) - { - this.srcPicture = pic; - - string decode; - - try - { - decode = findQrCodeText(new com.google.zxing.qrcode.QRCodeReader(), this.srcPicture); - } - catch (Exception exp) - { - decode = null; - } - - return decode; - } - - [DebuggerHidden] - public string findQrCodeText(com.google.zxing.Reader decoder, Bitmap bitmap) - { - var rgb = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height); - var hybrid = new com.google.zxing.common.HybridBinarizer(rgb); - com.google.zxing.BinaryBitmap binBitmap = new com.google.zxing.BinaryBitmap(hybrid); - string decodedString = decoder.decode(binBitmap, null).Text; - return decodedString; - } - - [DebuggerHidden] - public string Detect(Bitmap bitmap) - { - try - { - com.google.zxing.LuminanceSource source = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height); - var binarizer = new HybridBinarizer(source); - var binBitmap = new BinaryBitmap(binarizer); - BitMatrix bm = binBitmap.BlackMatrix; - Detector detector = new Detector(bm); - DetectorResult result = detector.detect(); - - string retStr = "Found at points "; - foreach (ResultPoint point in result.Points) - { - retStr += point.ToString() + ", "; - } - - return retStr; - } - catch - { - return "Failed to detect QR code."; - } - } - } -} diff --git a/PGLRentalLegality/ZXing/RGBLuminanceSource.cs b/PGLRentalLegality/ZXing/RGBLuminanceSource.cs index d0bb1b37..bc7fa085 100644 --- a/PGLRentalLegality/ZXing/RGBLuminanceSource.cs +++ b/PGLRentalLegality/ZXing/RGBLuminanceSource.cs @@ -6,7 +6,6 @@ public class RGBLuminanceSource : LuminanceSource { - private sbyte[] luminances; private bool isRotated = false; private bool __isRegionSelect = false; @@ -76,7 +75,7 @@ public RGBLuminanceSource(byte[] d, int W, int H,bool Is8Bit) luminances = new sbyte[W * H]; Buffer.BlockCopy(d,0, luminances,0, W * H); } - + public RGBLuminanceSource(byte[] d, int W, int H, bool Is8Bit,Rectangle Region) : base(W, H) { diff --git a/SmogonGenner/SmogonGenner.cs b/SmogonGenner/SmogonGenner.cs index dd70fb89..7abb4494 100644 --- a/SmogonGenner/SmogonGenner.cs +++ b/SmogonGenner/SmogonGenner.cs @@ -55,7 +55,7 @@ private void AddPluginControl(ToolStripDropDownItem tools) { var ctrl = new ToolStripMenuItem(Name); tools.DropDownItems.Add(ctrl); - ctrl.Click += new EventHandler(SmogonGenning); + ctrl.Click += SmogonGenning; ctrl.Image = SmogonGennerResources.smogongenner; } @@ -75,14 +75,9 @@ private void SmogonGenning(object sender, EventArgs e) PKM rough = PKMEditor.PreparePKM(); string speciesName = Util.GetSpeciesList("en")[rough.Species]; string form = new ShowdownSet(ShowdownSet.GetShowdownText(rough)).Form; - string url = ""; - if (form != null) - { - string urlSpecies = ConvertSpeciesToURLSpecies(speciesName); - if (form != "Mega" || form != "") url = String.Format("https://www.smogon.com/dex/sm/pokemon/{0}-{1}/", urlSpecies.ToLower(), ConvertFormToURLForm(form, urlSpecies).ToLower()); - } - else url = String.Format("https://www.smogon.com/dex/sm/pokemon/{0}/", ConvertSpeciesToURLSpecies(speciesName).ToLower()); + string url = GetURL(speciesName, form); string smogonPage = GetSmogonPage(url); + string[] split1 = smogonPage.Split(new string[] { "\",\"abilities\":" }, StringSplitOptions.None); List sets = new List(); for (int i = 1; i < split1.Length; i++) @@ -100,7 +95,7 @@ private void SmogonGenning(object sender, EventArgs e) showdownsets = showdownsets + ConvertSetToShowdown(set, showdownSpec) + Environment.NewLine + Environment.NewLine; } showdownsets.TrimEnd(); - if (showdownsets == "") + if (showdownsets.Length == 0) { MessageBox.Show("No movesets available. Perhaps you could help out? Check the Contributions & Corrections forum.\n\nForum: https://www.smogon.com/forums/forums/contributions-corrections.388/"); return; @@ -108,7 +103,19 @@ private void SmogonGenning(object sender, EventArgs e) Clipboard.SetText(showdownsets); try { AutomaticLegality.ImportModded(); } catch { MessageBox.Show("Something went wrong"); } - MessageBox.Show(alertText(showdownSpec, sets.Count, GetTitles(smogonPage))); + MessageBox.Show(AlertText(showdownSpec, sets.Count, GetTitles(smogonPage))); + } + + private static string GetURL(string speciesName, string form) + { + if (form == null) + return string.Format("https://www.smogon.com/dex/sm/pokemon/{0}/", ConvertSpeciesToURLSpecies(speciesName).ToLower()); + + string urlSpecies = ConvertSpeciesToURLSpecies(speciesName); + if (form != "Mega" || form != "") + return string.Format("https://www.smogon.com/dex/sm/pokemon/{0}-{1}/", urlSpecies.ToLower(), ConvertFormToURLForm(form, urlSpecies).ToLower()); + + return string.Empty; } private Dictionary> GetTitles(string smogonPage) @@ -121,7 +128,7 @@ private Dictionary> GetTitles(string smogonPage) string key = format.Split('"')[1]; List values = new List(); string[] Names = format.Split(new string[] { "\"name\"" }, StringSplitOptions.None); - for (int i = 1; i < Names.Count(); i++) + for (int i = 1; i < Names.Length; i++) { values.Add(Names[i].Split('"')[1]); } @@ -130,7 +137,7 @@ private Dictionary> GetTitles(string smogonPage) return titles; } - private string alertText(string showdownSpec, int count, Dictionary> titles) + private string AlertText(string showdownSpec, int count, Dictionary> titles) { string alertText = showdownSpec + ":" + String.Concat(Enumerable.Repeat(Environment.NewLine, 2)); foreach (KeyValuePair> entry in titles) @@ -152,8 +159,9 @@ private string GetSmogonPage(string url) } catch (Exception e) { - MessageBox.Show("An error occured while trying to obtain the contents of the URL. This is most likely an issue with your Internet Connection. The exact error is as follows: " + e.ToString() + "\nURL tried to access: " + url); - return "Error :" + e.ToString(); + MessageBox.Show( + $"An error occured while trying to obtain the contents of the URL. This is most likely an issue with your Internet Connection. The exact error is as follows: {e}\nURL tried to access: {url}"); + return "Error :" + e; } } @@ -170,8 +178,8 @@ private string ConvertSetToShowdown(string set, string species) if (splitmoves.Length > 3) moves.Add(splitmoves[3].Split('"')[0]); if (splitmoves.Length > 4) moves.Add(splitmoves[4].Split('"')[0]); string nature = set.Split(new string[] { "\"natures\":[\"" }, StringSplitOptions.None)[1].Split('"')[0]; - string[] evs = parseEVIVs(set.Split(new string[] { "\"evconfigs\":" }, StringSplitOptions.None)[1].Split(new string[] { ",\"ivconfigs\":" }, StringSplitOptions.None)[0], false); - string[] ivs = parseEVIVs(set.Split(new string[] { "\"ivconfigs\":" }, StringSplitOptions.None)[1].Split(new string[] { ",\"natures\":" }, StringSplitOptions.None)[0], true); + string[] evs = ParseEVIVs(set.Split(new string[] { "\"evconfigs\":" }, StringSplitOptions.None)[1].Split(new string[] { ",\"ivconfigs\":" }, StringSplitOptions.None)[0], false); + string[] ivs = ParseEVIVs(set.Split(new string[] { "\"ivconfigs\":" }, StringSplitOptions.None)[1].Split(new string[] { ",\"natures\":" }, StringSplitOptions.None)[0], true); var result = new List(); if (item != "") result.Add(species + " @ " + item); else result.Add(species); @@ -186,7 +194,7 @@ private string ConvertSetToShowdown(string set, string species) return string.Join(Environment.NewLine, result); } - private string[] parseEVIVs(string liststring, bool iv) + private string[] ParseEVIVs(string liststring, bool iv) { string[] ivdefault = new string[] { "31", "31", "31", "31", "31", "31" }; string[] evdefault = new string[] { "0", "0", "0", "0", "0", "0" }; diff --git a/SmogonGenner/SmogonGenner.csproj b/SmogonGenner/SmogonGenner.csproj index 7d49d257..db7cc350 100644 --- a/SmogonGenner/SmogonGenner.csproj +++ b/SmogonGenner/SmogonGenner.csproj @@ -37,12 +37,6 @@ - - - - - - diff --git a/URLGenning/URLGenning.cs b/URLGenning/URLGenning.cs index b5b9a547..fcd0fc9c 100644 --- a/URLGenning/URLGenning.cs +++ b/URLGenning/URLGenning.cs @@ -54,7 +54,7 @@ private void AddPluginControl(ToolStripDropDownItem tools) { var ctrl = new ToolStripMenuItem(Name); tools.DropDownItems.Add(ctrl); - ctrl.Click += new EventHandler(URLGen); + ctrl.Click += URLGen; ctrl.Image = URLGenningResources.urlimport; } @@ -113,14 +113,12 @@ private string MetaDataURL(string url) private bool CheckPokePaste(string url) { - if (url.Contains("pokepast.es/")) return true; - return false; + return url.Contains("pokepast.es/"); } private bool CheckPasteBin(string url) { - if (url.Contains("pastebin.com/")) return true; - return false; + return url.Contains("pastebin.com/"); } private Dictionary GetMetadata(string url) @@ -156,13 +154,12 @@ private string GetText(string url) { var request = (HttpWebRequest)WebRequest.Create(url); var response = (HttpWebResponse)request.GetResponse(); - var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); - return responseString; + return new StreamReader(response.GetResponseStream()).ReadToEnd(); } catch (Exception e) { - MessageBox.Show("An error occured while trying to obtain the contents of the URL. This is most likely an issue with your Internet Connection. The exact error is as follows: " + e.ToString()); - return "Error :" + e.ToString(); + MessageBox.Show("An error occured while trying to obtain the contents of the URL. This is most likely an issue with your Internet Connection. The exact error is as follows: " + e); + return "Error :" + e; } } } diff --git a/URLGenning/URLGenning.csproj b/URLGenning/URLGenning.csproj index 3a394505..f8c1ea88 100644 --- a/URLGenning/URLGenning.csproj +++ b/URLGenning/URLGenning.csproj @@ -37,12 +37,6 @@ - - - - - -