Exemplo n.º 1
0
        /// <summary>
        /// Main function that auto legalizes based on the legality
        /// </summary>
        /// <remarks>Leverages <see cref="Core"/>'s <see cref="EncounterMovesetGenerator"/> to create a <see cref="PKM"/> from a <see cref="ShowdownSet"/>.</remarks>
        /// <param name="dest">Destination for the generated pkm</param>
        /// <param name="template">rough pkm that has all the <see cref="set"/> values entered</param>
        /// <param name="set">Showdown set object</param>
        /// <param name="satisfied">If the final result is satisfactory, otherwise use deprecated bruteforce auto legality functionality</param>
        public static PKM GetLegalFromTemplate(this ITrainerInfo dest, PKM template, ShowdownSet set, out bool satisfied)
        {
            set = set.PreProcessShowdownSet();
            var Form = SanityCheckForm(template, ref set);

            template.ApplySetDetails(set);
            template.SetRecordFlags(); // Validate TR moves for the encounter
            var destType = template.GetType();
            var destVer  = (GameVersion)dest.Game;

            if (destVer <= 0 && dest is SaveFile s)
            {
                destVer = s.Version;
            }

            var gamelist = GameUtil.GetVersionsWithinRange(template, template.Format).OrderByDescending(c => c.GetGeneration()).ToArray();

            EncounterMovesetGenerator.PriorityList = new[] { EncounterOrder.Egg, EncounterOrder.Static, EncounterOrder.Trade, EncounterOrder.Slot, EncounterOrder.Mystery };
            var encounters = EncounterMovesetGenerator.GenerateEncounters(pk: template, moves: set.Moves, gamelist);

            if (template.Species <= 721)
            {
                encounters = encounters.Concat(GetFriendSafariEncounters(template));
            }
            foreach (var enc in encounters)
            {
                var ver = enc is IVersion v ? v.Version : destVer;
                var gen = enc is IGeneration g ? g.Generation : dest.Generation;
                var tr  = UseTrainerData ? TrainerSettings.GetSavedTrainerData(ver, gen) : TrainerSettings.DefaultFallback(gen);
                var raw = SanityCheckEncounters(enc).ConvertToPKM(tr);
                if (raw.IsEgg) // PGF events are sometimes eggs. Force hatch them before proceeding
                {
                    raw.HandleEggEncounters(enc, tr);
                }
                var pk = PKMConverter.ConvertToType(raw, destType, out _);
                if (pk == null)
                {
                    continue;
                }

                ApplySetDetails(pk, set, Form, raw, dest, enc);
                if (set.CanGigantamax && pk is IGigantamax gmax)
                {
                    if (!gmax.CanGigantamax)
                    {
                        continue;
                    }
                }

                var la = new LegalityAnalysis(pk);
                if (la.Valid)
                {
                    satisfied = true;
                    return(pk);
                }
                Debug.WriteLine(la.Report());
            }
            satisfied = false;
            return(template);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Proper method to hypertrain based on Showdown Sets. Also handles edge cases like ultrabeasts
        /// </summary>
        /// <param name="pk">passed pkm object</param>
        /// <param name="set">showdown set to base hypertraining on</param>
        private static void SetHyperTrainingFlags(this PKM pk, ShowdownSet set)
        {
            if (!(pk is IHyperTrain t))
            {
                return;
            }
            pk.SetSuggestedHyperTrainingData(); // Set IV data based on showdownset

            // Fix HT flags as necessary
            t.HT_ATK = (set.IVs[1] >= 3 || !t.HT_ATK) && ((set.IVs[1] >= 3 && pk.IVs[1] < 3 && pk.CurrentLevel == 100) || t.HT_ATK);
            t.HT_SPE = (set.IVs[3] >= 3 || !t.HT_SPE) && ((set.IVs[3] >= 3 && pk.IVs[3] < 3 && pk.CurrentLevel == 100) || t.HT_SPE);

            // Handle special cases here for ultrabeasts
            switch (pk.Species)
            {
            case (int)Species.Kartana when pk.Nature == (int)Nature.Timid && ((set.IVs[1] <= 19 && pk.CurrentLevel == 100) || (set.IVs[1] <= 21 && pk.CurrentLevel == 50)):     // Speed boosting Timid Kartana ATK IVs <= 19
                t.HT_ATK = false;
                break;

            case (int)Species.Stakataka when pk.Nature == (int)Nature.Lonely && ((set.IVs[2] <= 15 && pk.CurrentLevel == 100) || (set.IVs[2] <= 17 && pk.CurrentLevel == 50)):     // Atk boosting Lonely Stakataka DEF IVs <= 15
                t.HT_DEF = false;
                break;

            case (int)Species.Pyukumuku when set.IVs[2] == 0 && set.IVs[5] == 0 && pk.Ability == (int)Ability.InnardsOut:     // 0 Def / 0 Spd Pyukumuku with innards out
                t.HT_DEF = false;
                t.HT_SPD = false;
                break;
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Modifies the provided <see cref="pk"/> to the specifications required by <see cref="set"/>.
        /// </summary>
        /// <param name="pk">Converted final pkm to apply details to</param>
        /// <param name="set">Set details required</param>
        /// <param name="Form">Alternate form required</param>
        /// <param name="unconverted">Original pkm data</param>
        /// <param name="handler">Trainer to handle the Pokémon</param>
        /// <param name="enc">Encounter details matched to the Pokémon</param>
        private static void ApplySetDetails(PKM pk, ShowdownSet set, int Form, PKM unconverted, ITrainerInfo handler, IEncounterable enc)
        {
            var pidiv       = MethodFinder.Analyze(pk);
            var abilitypref = GetAbilityPreference(pk, enc);

            pk.SetVersion(unconverted); // Preemptive Version setting
            pk.SetSpeciesLevel(set, Form, enc);
            pk.SetRecordFlags(set.Moves);
            pk.SetMovesEVsItems(set);
            pk.SetHandlerandMemory(handler);
            pk.SetNatureAbility(set, abilitypref);
            pk.SetIVsPID(set, pidiv.Type, set.HiddenPowerType, unconverted);
            pk.SetHyperTrainingFlags(set); // Hypertrain
            pk.SetEncryptionConstant(enc);
            pk.FixFatefulFlag(enc);
            pk.SetShinyBoolean(set.Shiny, enc);
            pk.FixGender(set);
            pk.SetSuggestedRibbons(SetAllLegalRibbons);
            pk.SetSuggestedMemories();
            pk.SetHTLanguage();
            pk.SetDynamaxLevel();
            pk.SetSuggestedBall(SetMatchingBalls);
            pk.ApplyMarkings(UseMarkings, UseCompetitiveMarkings);
            pk.SetHappiness();
            pk.SetBelugaValues();
            pk.FixEdgeCases();
        }
Exemplo n.º 4
0
        private static void SetNature(PKM pk, ShowdownSet set)
        {
            var val = Math.Min((int)Nature.Quirky, Math.Max((int)Nature.Hardy, set.Nature));

            pk.SetNature(val);
            if (pk.Species == (int)Species.Toxtricity)
            {
                if (pk.AltForm == EvolutionMethod.GetAmpLowKeyResult(val))
                {
                    pk.Nature = val; // StatNature already set
                }
                return;
            }

            // Try setting the actual nature (in the event the StatNature was set instead)
            var orig = pk.Nature;

            if (orig == val)
            {
                return;
            }

            var la = new LegalityAnalysis(pk);

            pk.Nature = val;
            var la2  = new LegalityAnalysis(pk);
            var enc1 = la.EncounterOriginal;
            var enc2 = la2.EncounterOriginal;

            if (!ReferenceEquals(enc1, enc2) && !(enc1 is EncounterEgg) || la2.Info.Parse.Any(z => z.Identifier == CheckIdentifier.Nature && !z.Valid))
            {
                pk.Nature = orig;
            }
        }
Exemplo n.º 5
0
 public static async Task ReplyWithLegalizedSetAsync(this ISocketMessageChannel channel, string content, int gen)
 {
     content = ReusableActions.StripCodeBlock(content);
     var set = new ShowdownSet(content);
     var sav = AutoLegalityWrapper.GetTrainerInfo(gen);
     await channel.ReplyWithLegalizedSetAsync(sav, set).ConfigureAwait(false);
 }
Exemplo n.º 6
0
        private async Task <bool> HandleEncounter(PK8 pk, bool legends, CancellationToken token)
        {
            encounterCount++;
            Log($"Encounter: {encounterCount}{Environment.NewLine}{ShowdownSet.GetShowdownText(pk)}{Environment.NewLine}");
            if (legends)
            {
                Counts.AddCompletedLegends();
            }
            else
            {
                Counts.AddCompletedEncounters();
            }

            if (DumpSetting.Dump && !string.IsNullOrEmpty(DumpSetting.DumpFolder))
            {
                DumpPokemon(DumpSetting.DumpFolder, legends ? "legends" : "encounters", pk);
            }

            if (StopConditionSettings.EncounterFound(pk, DesiredIVs, Hub.Config.StopConditions))
            {
                Log("Result found! Stopping routine execution; restart the bot(s) to search again.");
                if (Hub.Config.StopConditions.CaptureVideoClip)
                {
                    await Task.Delay(Hub.Config.StopConditions.ExtraTimeWaitCaptureVideo).ConfigureAwait(false);
                    await PressAndHold(CAPTURE, 2_000, 1_000, token).ConfigureAwait(false);
                }
                return(true);
            }

            return(false);
        }
Exemplo n.º 7
0
        public dynamic Showdown([FromForm][Required] string set, [FromForm] string generation)
        {
            ShowdownSet showdown;

            try
            {
                showdown = new ShowdownSet(set);
                var            sav    = SaveUtil.GetBlankSAV(Utils.GetGameVersion(generation), "Scatman");
                PKM            newPKM = sav.GetLegalFromSet(showdown, out var result);
                PokemonSummary pks    = new PokemonSummary(newPKM, GameInfo.Strings);
                if (pks.Species == "")
                {
                    throw new System.ArgumentException("Your Pokemon does not exist!");
                }

                DefaultContractResolver contractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                };


                Response.ContentType = "application/json";
                return(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(pks, new JsonSerializerSettings
                {
                    ContractResolver = contractResolver,
                    Formatting = Formatting.Indented
                })));
            } catch (Exception e) {
                dynamic error = new JObject();
                error.message = e.Message;
                return(StatusCode(400, error));
            }
        }
Exemplo n.º 8
0
        public void SimulatorParseDuplicate(string text, int moveCount)
        {
            var set    = new ShowdownSet(text);
            var actual = set.Moves.Count(z => z != 0);

            actual.Should().Be(moveCount);
        }
 public static async Task ReplyWithLegalizedSetAsync(this ISocketMessageChannel channel, string content)
 {
     content = ReusableActions.StripCodeBlock(content);
     var set = new ShowdownSet(content);
     var sav = TrainerSettings.GetSavedTrainerData(set.Format);
     await channel.ReplyWithLegalizedSetAsync(sav, set).ConfigureAwait(false);
 }
Exemplo n.º 10
0
        private async Task <PKM> ShowdownImportFromClipboard(PKM template)
        {
            var txt = await DataUtil.GetClipboardText().ConfigureAwait(false);

            if (txt == null)
            {
                return(null);
            }

            var set = new ShowdownSet(txt);

            if (set.Species < 0)
            {
                await UserDialogs.Instance
                .AlertAsync("No valid Showdown Set data was found. Please try again.")
                .ConfigureAwait(false);

                return(null);
            }

            var pkm = template.Clone();

            if (set.Nickname?.Length > pkm.NickLength)
            {
                set.Nickname = set.Nickname.Substring(0, pkm.NickLength);
            }

            pkm.ApplySetDetails(set);
            return(pkm);
        }
Exemplo n.º 11
0
        public async Task TradeAsync([Summary("Showdown Set")][Remainder] string content)
        {
            const int gen = 8;

            content = ReusableActions.StripCodeBlock(content);
            var set = new ShowdownSet(content);
            var sav = AutoLegalityWrapper.GetTrainerInfo(gen);

            var pkm  = sav.GetLegal(set, out var result);
            var la   = new LegalityAnalysis(pkm);
            var spec = GameInfo.Strings.Species[set.Species];
            var msg  = la.Valid
                ? $"Here's your ({result}) legalized PKM for {spec} ({la.EncounterOriginal.Name})!"
                : $"Oops! I wasn't able to create something from that. Here's my best attempt for that {spec}!";

            if ((!la.Valid && SysCordInstance.Self.Hub.Config.VerifyLegality) || !(pkm is PK8 pk8))
            {
                await ReplyAsync(msg).ConfigureAwait(false);

                return;
            }

            pk8.ResetPartyStats();

            var code = Info.GetRandomTradeCode();
            var sudo = Context.User.GetIsSudo();

            await AddTradeToQueueAsync(code, Context.User.Username, pk8, sudo).ConfigureAwait(false);
        }
Exemplo n.º 12
0
        private static void ApplyEncounterAttributes(PKM pk, ShowdownSet set, EncounterStatic el)
        {
            pk.Met_Location     = el.Location;
            pk.Met_Level        = el.Level;
            pk.CurrentLevel     = 100;
            pk.FatefulEncounter = el.Fateful;
            if (el.RibbonWishing && pk is IRibbonSetEvent4 e4)
            {
                e4.RibbonWishing = true;
            }
            pk.SetRelearnMoves(el.Relearn);

            if (set.Shiny && (el.Shiny == Shiny.Always || el.Shiny == Shiny.Random))
            {
                pk.SetShiny();
            }
            else if (el.Shiny == Shiny.Never && pk.IsShiny)
            {
                pk.PID ^= 0x10000000;
            }
            else
            {
                pk.SetPIDGender(pk.Gender);
            }
        }
Exemplo n.º 13
0
        private static AutoModErrorCode ImportSetToTabs(ShowdownSet set)
        {
            // ALM Settings
            SetAPILegalitySettings();

            if (DialogResult.Yes != WinFormsUtil.Prompt(MessageBoxButtons.YesNo, "Import this set?", set.Text))
            {
                return(AutoModErrorCode.NoSingleImport);
            }
            if (set.InvalidLines.Count > 0)
            {
                return(AutoModErrorCode.InvalidLines);
            }

            Debug.WriteLine($"Commencing Import of {GameInfo.Strings.Species[set.Species]}");
            var timer = Stopwatch.StartNew();

            var sav   = SaveFileEditor.SAV;
            var legal = sav.GetLegalFromSet(set, out var _);

            Debug.WriteLine("Single Set Genning Complete. Loading final data to tabs.");
            PKMEditor.PopulateFields(legal);

            // Debug Statements
            timer.Stop();
            var timespan = timer.Elapsed;

            Debug.WriteLine($"Time to complete {nameof(ImportSetToTabs)}: {timespan.Minutes:00} minutes {timespan.Seconds:00} seconds {timespan.Milliseconds / 10:00} milliseconds");
            return(AutoModErrorCode.None);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Exports the <see cref="box"/> to <see cref="ShowdownSet"/> as a single string.
        /// </summary>
        /// <param name="sav">Save File to export from</param>
        /// <param name="box">Box to export from</param>
        /// <returns>Concatenated string of all sets in the specified box.</returns>
        public static string GetShowdownSetsFromBox(this SaveFile sav, int box)
        {
            var data = sav.GetBoxData(box);
            var sep  = Environment.NewLine + Environment.NewLine;

            return(ShowdownSet.GetShowdownSets(data, sep));
        }
Exemplo n.º 15
0
        public static string GetFormattedShowdownText(PKM pkm)
        {
            var newShowdown = new List <string>();
            var showdown    = ShowdownSet.GetShowdownText(pkm);

            foreach (var line in showdown.Split('\n'))
            {
                newShowdown.Add(line);
            }

            if (pkm.IsEgg)
            {
                newShowdown.Add("\nPokémon is an Egg");
            }
            if (pkm.Ball > (int)Ball.None)
            {
                newShowdown.Insert(newShowdown.FindIndex(z => z.Contains(" Nature")), $"Ball: {(Ball)pkm.Ball} Ball");
            }
            if (pkm.IsShiny)
            {
                var index = newShowdown.FindIndex(x => x.Contains("Shiny: Yes"));
                if (pkm.ShinyXor == 0)
                {
                    newShowdown[index] = "Shiny: Square\r";
                }
                else
                {
                    newShowdown[index] = "Shiny: Star\r";
                }
            }

            newShowdown.InsertRange(1, new string[] { $"OT: {pkm.OT_Name}", $"TID: {pkm.DisplayTID}", $"SID: {pkm.DisplaySID}", $"OTGender: {(Gender)pkm.OT_Gender}", $"Language: {(LanguageID)pkm.Language}" });
            return(Format.Code(string.Join("\n", newShowdown).TrimEnd()));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Main method that calls both API legality and Bruteforce
        /// </summary>
        /// <param name="tr">Trainer Data that was passed in</param>
        /// <param name="set">Showdown set being used</param>
        /// <param name="template">template PKM to legalize</param>
        /// <param name="msg">Legalization result (API, Bruteforce, Failure)</param>
        /// <returns>Legalized pkm</returns>
        private static PKM GetLegalFromSet(this ITrainerInfo tr, ShowdownSet set, PKM template, out LegalizationResult msg)
        {
            if (AllowAPI)
            {
                bool success = tr.TryAPIConvert(set, template, out PKM pk);
                if (success)
                {
                    msg = LegalizationResult.Regenerated;
                    return(pk);
                }
                if (!AllowBruteForce)
                {
                    msg = LegalizationResult.Failed;
                    return(pk);
                }
            }

            if (AllowBruteForce)
            {
                msg = LegalizationResult.BruteForce;
                return(tr.GetBruteForcedLegalMon(set, template));
            }

            msg = LegalizationResult.Failed;
            return(template);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Imports a <see cref="set"/> to create a new <see cref="PKM"/> with a context of <see cref="tr"/>.
        /// </summary>
        /// <param name="tr">Source/Destination trainer</param>
        /// <param name="set">Set data to import</param>
        /// <param name="msg">Result code indicating success or failure</param>
        /// <returns>Legalized PKM (hopefully legal)</returns>
        public static PKM GetLegalFromSet(this ITrainerInfo tr, ShowdownSet set, out LegalizationResult msg)
        {
            var template = PKMConverter.GetBlank(tr.Generation, (GameVersion)tr.Game);

            template.ApplySetDetails(set);
            return(tr.GetLegalFromSet(set, template, out msg));
        }
Exemplo n.º 18
0
        public void SimulatorGetEncounters()
        {
            var set = new ShowdownSet(SetGlaceonUSUMTutor);
            var pk7 = new PK7 {
                Species = set.Species, AltForm = set.FormIndex, Moves = set.Moves
            };
            var encs = EncounterMovesetGenerator.GenerateEncounters(pk7, set.Moves, GameVersion.MN);

            Assert.True(!encs.Any());
            pk7.HT_Name = "PKHeX";
            encs        = EncounterMovesetGenerator.GenerateEncounters(pk7, set.Moves, GameVersion.MN);
            var first = encs.FirstOrDefault();

            Assert.True(first != null);

            var egg  = (EncounterEgg)first;
            var info = new SimpleTrainerInfo();
            var pk   = egg.ConvertToPKM(info);

            Assert.True(pk.Species != set.Species);

            var la = new LegalityAnalysis(pk);

            Assert.True(la.Valid);

            var test = EncounterMovesetGenerator.GeneratePKMs(pk7, info).ToList();

            foreach (var t in test)
            {
                var la2 = new LegalityAnalysis(t);
                Assert.True(la2.Valid);
            }
        }
Exemplo n.º 19
0
        private async Task WalkInLine(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                var attempts = await StepUntilEncounter(token).ConfigureAwait(false);

                if (attempts < 0) // aborted
                {
                    continue;
                }

                Log($"Encounter found after {attempts} attempts! Checking details.");

                var pk = await ReadPokemon(WildPokemonOffset, token).ConfigureAwait(false);

                if (pk.Species == 0)
                {
                    Log("Invalid data detected. Restarting loop.");
                    // add stuff for recovering
                    continue;
                }

                encounterCount++;
                Log($"Encounter: {encounterCount}{Environment.NewLine}{ShowdownSet.GetShowdownText(pk)}{Environment.NewLine}");
                Counts.AddCompletedEncounters();

                if (DumpSetting.Dump && !string.IsNullOrEmpty(DumpSetting.DumpFolder))
                {
                    DumpPokemon(DumpSetting.DumpFolder, "encounters", pk);
                }

                if (StopCondition(pk))
                {
                    Log("Result found! Stopping routine execution; restart the bot(s) to search again.");
                    return;
                }
                else if (pk.Ability == 119 || pk.Ability == 107) // pokemon with announced abilites
                {
                    await Task.Delay(2700, token).ConfigureAwait(false);
                }

                await Task.Delay(4600, token).ConfigureAwait(false);

                while (!await IsCorrectScreen(CurrentScreen_Overworld, token).ConfigureAwait(false) || !await IsCorrectScreen(CurrentScreen_WildArea, token).ConfigureAwait(false))
                {
                    await FleeToOverworld(token).ConfigureAwait(false);
                }

                if (Mode == EncounterMode.VerticalLine)
                {
                    await SetStick(LEFT, 0, -30000, 2500, token).ConfigureAwait(false);
                }
                else if (Mode == EncounterMode.HorizontalLine)
                {
                    await SetStick(LEFT, -30000, 0, 2500, token).ConfigureAwait(false);
                }
                await ResetStick(token).ConfigureAwait(false);
            }
        }
Exemplo n.º 20
0
        public void SimulatorGetParse()
        {
            var set = new ShowdownSet(SetGlaceonUSUMTutor);

            string Sanitize(string str) => str.Replace("\r\n", "").Replace("\n", "");

            Assert.IsTrue(Sanitize(SetGlaceonUSUMTutor) == Sanitize(set.Text));
        }
Exemplo n.º 21
0
 /// <summary>
 /// General method to preprocess sets excluding invalid formes. (handled in a future method)
 /// </summary>
 /// <param name="set">Showdown set passed to the function</param>
 private static ShowdownSet PreProcessShowdownSet(this ShowdownSet set)
 {
     if ((set.Species == (int)Species.Indeedee || set.Species == (int)Species.Meowstic) && set.Form == "F")
     {
         set = new ShowdownSet(set.Text.Replace("(M)", "(F)"));
     }
     return(set);
 }
Exemplo n.º 22
0
        public static List <ShowdownTeamSet> GetTeams(string paste)
        {
            string[] lines  = paste.Split(new[] { "\n" }, StringSplitOptions.None);
            var      result = new List <ShowdownTeamSet>();

            for (int i = 0; i < lines.Length; i++)
            {
                var line = lines[i]?.Trim();
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                if (!IsLineShowdownTeam(line))
                {
                    continue;
                }

                var split = line.Split(new[] { "===" }, 0);
                if (split.Length != 3)
                {
                    continue;
                }

                var split2 = split[1].Trim().Split(']');
                if (split2.Length != 2)
                {
                    continue;
                }

                var format = split2[0].Substring(1);
                var name   = split2[1].TrimStart();
                // find end

                int end = i + 1;
                while (end < lines.Length)
                {
                    if (IsLineShowdownTeam(lines[end]))
                    {
                        break;
                    }
                    end++;
                }

                var teamlines = lines.Skip(i + 1).Take(end - i - 1).Where(z => !string.IsNullOrWhiteSpace(z));
                var sets      = ShowdownSet.GetShowdownSets(teamlines).ToList();
                if (sets.Count <= 0)
                {
                    continue;
                }
                result.Add(new ShowdownTeamSet {
                    Format = format, TeamName = name, Team = sets
                });

                i = end;
            }
            return(result);
        }
Exemplo n.º 23
0
 public void SimulatorGetParse()
 {
     foreach (var setstr in Sets)
     {
         var set   = new ShowdownSet(setstr).Text;
         var lines = set.Split('\n').Select(z => z.Trim());
         Assert.IsTrue(lines.All(z => setstr.Contains(z)), setstr);
     }
 }
Exemplo n.º 24
0
        private async Task WalkInLine(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                var attempts = await StepUntilEncounter(token).ConfigureAwait(false);

                if (attempts < 0) // aborted
                {
                    continue;
                }

                Log($"Encounter found after {attempts} attempts! Checking details...");

                // Reset stick while we wait for the encounter to load.
                await ResetStick(token).ConfigureAwait(false);

                var pk = await ReadPokemon(WildPokemonOffset, token).ConfigureAwait(false);

                if (pk.Species == 0)
                {
                    Log("Invalid data detected. Restarting loop.");

                    // Flee and continue looping.
                    while (await IsInBattle(token).ConfigureAwait(false))
                    {
                        await FleeToOverworld(token).ConfigureAwait(false);
                    }
                    continue;
                }

                encounterCount++;
                Log($"Encounter: {encounterCount}{Environment.NewLine}{ShowdownSet.GetShowdownText(pk)}{Environment.NewLine}");
                Counts.AddCompletedEncounters();

                if (DumpSetting.Dump && !string.IsNullOrEmpty(DumpSetting.DumpFolder))
                {
                    DumpPokemon(DumpSetting.DumpFolder, "encounters", pk);
                }

                if (StopCondition(pk))
                {
                    Log("Result found! Stopping routine execution; restart the bot(s) to search again.");
                    return;
                }

                // In some areas, the menu offset can flicker undesirably while battle is loading.
                await Task.Delay(4_000, token).ConfigureAwait(false);

                await ReadUntilChanged(BattleMenuOffset, BattleMenuReady, 15_000, 0_100, true, token).ConfigureAwait(false);

                Log("Running away...");
                while (await IsInBattle(token).ConfigureAwait(false))
                {
                    await FleeToOverworld(token).ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 25
0
        private static PKM GetBruteForcedLegalMon(this ITrainerInfo tr, ShowdownSet set, PKM template)
        {
            var resetForm = ShowdownUtil.IsInvalidForm(set.Form);
            var trainer   = TrainerSettings.GetSavedTrainerData(template, tr);
            var legal     = BruteForce.ApplyDetails(template, set, resetForm, trainer);

            legal.SetAllTrainerData(trainer);
            return(legal);
        }
Exemplo n.º 26
0
        private async Task WalkInLine(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                var attempts = await StepUntilEncounter(token).ConfigureAwait(false);

                if (attempts < 0) // aborted
                {
                    continue;
                }

                Log($"Encounter found after {attempts} attempts! Checking details.");

                // Reset stick while we wait for the encounter to load.
                await ResetStick(token).ConfigureAwait(false);

                var pk = await ReadPokemon(WildPokemonOffset, token).ConfigureAwait(false);

                if (pk.Species == 0)
                {
                    Log("Invalid data detected. Restarting loop.");

                    // Flee and continue looping.
                    while (await IsInBattle(token).ConfigureAwait(false))
                    {
                        await FleeToOverworld(token).ConfigureAwait(false);
                    }
                    continue;
                }

                encounterCount++;
                Log($"Encounter: {encounterCount}{Environment.NewLine}{ShowdownSet.GetShowdownText(pk)}{Environment.NewLine}");
                Counts.AddCompletedEncounters();

                if (DumpSetting.Dump && !string.IsNullOrEmpty(DumpSetting.DumpFolder))
                {
                    DumpPokemon(DumpSetting.DumpFolder, "encounters", pk);
                }

                if (StopCondition(pk))
                {
                    Log("Result found! Stopping routine execution; restart the bot(s) to search again.");
                    return;
                }
                if (EncounterBotUtil.DisplayedAbilities.Contains(pk.Ability)) // pokemon with announced abilites
                {
                    await Task.Delay(2_700, token).ConfigureAwait(false);
                }

                await Task.Delay(2_700, token).ConfigureAwait(false);

                while (await IsInBattle(token).ConfigureAwait(false))
                {
                    await FleeToOverworld(token).ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 27
0
        private static int SanityCheckForm(PKM template, ref ShowdownSet set)
        {
            int Form = template.AltForm;

            if (set.Form != null && FixFormes(set, out set))
            {
                Form = set.FormIndex;
            }
            return(Form);
        }
Exemplo n.º 28
0
 private static PKM GetLegalFromSet(this ITrainerInfo tr, ShowdownSet set, PKM template, out LegalizationResult msg, bool allowAPI = true)
 {
     if (allowAPI && tr.TryAPIConvert(set, template, out PKM pk))
     {
         msg = LegalizationResult.Regenerated;
         return(pk);
     }
     msg = LegalizationResult.BruteForce;
     return(tr.GetBruteForcedLegalMon(set, template));
 }
Exemplo n.º 29
0
        private async Task DoEternatusEncounter(CancellationToken token)
        {
            while (!token.IsCancellationRequested && Config.NextRoutineType == PokeRoutineType.EncounterBot)
            {
                await SetStick(LEFT, 0, 20_000, 500, token).ConfigureAwait(false);
                await SetStick(LEFT, 0, 0, 1_000, token).ConfigureAwait(false);

                var pk = await ReadPokemon(RaidPokemonOffset, token).ConfigureAwait(false);

                if (pk.Species == 0)
                {
                    Connection.Log("Invalid data detected. Restarting loop.");
                    // add stuff for recovering
                    continue;
                }

                encounterCount++;
                Connection.Log($"Encounter: {encounterCount}:{Environment.NewLine}{ShowdownSet.GetShowdownText(pk)}{Environment.NewLine}{Environment.NewLine}");
                Counts.AddCompletedLegends();

                if (DumpSetting.Dump && !string.IsNullOrEmpty(DumpSetting.DumpFolder))
                {
                    DumpPokemon(DumpSetting.DumpFolder, "legends", pk);
                }

                if (StopCondition(pk))
                {
                    Connection.Log("Result found! Stopping routine execution; restart the bot(s) to search again.");
                    return;
                }

                Connection.Log("Resetting raid by restarting the game");
                // Close out of the game
                await Click(HOME, 1_600, token).ConfigureAwait(false);
                await Click(X, 0_800, token).ConfigureAwait(false);
                await Click(A, 4_000, token).ConfigureAwait(false); // Closing software prompt

                Connection.Log("Closed out of the game!");

                // Open game and select profile
                await Click(A, 1_000, token).ConfigureAwait(false);
                await Click(A, 1_000, token).ConfigureAwait(false);

                Connection.Log("Restarting the game!");

                // Switch Logo lag, skip cutscene, game load screen
                await Task.Delay(14_000, token).ConfigureAwait(false);
                await Click(A, 1_000, token).ConfigureAwait(false);

                await Task.Delay(3_500, token).ConfigureAwait(false);

                Connection.Log("Back in the overworld!");
                await ResetStick(token).ConfigureAwait(false);
            }
        }
Exemplo n.º 30
0
        private static AutoModErrorCode ImportSetToTabs(ShowdownSet set, bool skipDialog = false)
        {
            var regen = new RegenTemplate(set, SaveFileEditor.SAV.Generation);

            if (!skipDialog && DialogResult.Yes != WinFormsUtil.Prompt(MessageBoxButtons.YesNo, "Import this set?", regen.Text))
            {
                return(AutoModErrorCode.NoSingleImport);
            }

            if (set.InvalidLines.Count > 0)
            {
                return(AutoModErrorCode.InvalidLines);
            }

            Debug.WriteLine($"Commencing Import of {GameInfo.Strings.Species[set.Species]}");
            var timer = Stopwatch.StartNew();

            var sav   = SaveFileEditor.SAV;
            var legal = sav.GetLegalFromSet(regen, out var msg);

            timer.Stop();

            if (msg is LegalizationResult.Timeout or LegalizationResult.Failed)
            {
                Legalizer.Dump(regen, msg == LegalizationResult.Failed);

                string?analysis = null;
                if (msg is LegalizationResult.Failed)
                {
                    analysis = regen.SetAnalysis(sav, sav.BlankPKM);
                }

                var errorstr          = msg == LegalizationResult.Failed ? "failed to generate" : "timed out";
                var invalid_set_error = (analysis == null ? $"Set {errorstr}." : $"Set Invalid: {analysis}") +
                                        "\n\nIf you are sure this set is valid, please create an issue on GitHub and upload the error_log.txt file in the issue." +
                                        "\n\nAlternatively, join the support Discord and post the same file in the #autolegality-livehex-help channel.";
                var res = WinFormsUtil.ALMError(invalid_set_error);
                if (res == DialogResult.Yes)
                {
                    Process.Start("https://discord.gg/tDMvSRv");
                }
                else if (res == DialogResult.No)
                {
                    Process.Start("https://github.com/architdate/PKHeX-Plugins/issues");
                }
            }

            Debug.WriteLine("Single Set Genning Complete. Loading final data to tabs.");
            PKMEditor.PopulateFields(legal);

            var timespan = timer.Elapsed;

            Debug.WriteLine($"Time to complete {nameof(ImportSetToTabs)}: {timespan.Minutes:00} minutes {timespan.Seconds:00} seconds {timespan.Milliseconds / 10:00} milliseconds");
            return(AutoModErrorCode.None);
        }