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()));
        }
Exemple #2
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(2600, token).ConfigureAwait(false);

                while (await IsInBattle(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);
            }
        }
Exemple #3
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, token).ConfigureAwait(false);
                    await PressAndHold(CAPTURE, 2_000, 1_000, token).ConfigureAwait(false);
                }
                return(true);
            }

            return(false);
        }
Exemple #4
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);
                }
            }
        }
        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);
                }
            }
        }
Exemple #6
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);
            }
        }
Exemple #7
0
 private void ShowSimulatorSetTooltip(Control pb, PKM pk)
 {
     if (pk.Species == 0)
     {
         ShowSet.RemoveAll();
     }
     else
     {
         ShowSet.SetToolTip(pb, ShowdownSet.GetShowdownText(pk));
     }
 }
Exemple #8
0
        private void SmogonGenner(object sender, EventArgs e)
        {
            string speciesName = PKME_Tabs.CB_Species.Text;
            string form        = new ShowdownSet(ShowdownSet.GetShowdownText(PKME_Tabs.PreparePKM())).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 smogonPage = GetSmogonPage(url);

            string[]      split1 = smogonPage.Split(new string[] { "\",\"abilities\":" }, StringSplitOptions.None);
            List <string> sets   = new List <string>();

            for (int i = 1; i < split1.Length; i++)
            {
                sets.Add(split1[i].Split(new string[] { "\"]}" }, StringSplitOptions.None)[0]);
            }
            string showdownSpec = speciesName;

            if (form != null)
            {
                if (form != "Mega" || form != "")
                {
                    showdownSpec += ("-" + form);
                }
            }
            string showdownsets = "";

            foreach (string set in sets)
            {
                showdownsets = showdownsets + ConvertSetToShowdown(set, showdownSpec) + Environment.NewLine + Environment.NewLine;
            }
            showdownsets.TrimEnd();
            if (showdownsets == "")
            {
                WinFormsUtil.Alert("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;
            }
            Clipboard.SetText(showdownsets);
            try { ClickShowdownImportPKMModded(sender, e); }
            catch { WinFormsUtil.Alert("Something went wrong"); }
            WinFormsUtil.Alert(alertText(showdownSpec, sets.Count, GetTitles(smogonPage)));
        }
Exemple #9
0
        /// <summary>
        /// Tries to regenerate the <see cref="pk"/> into a valid pkm.
        /// </summary>
        /// <param name="tr">Source/Destination trainer</param>
        /// <param name="pk">Currently invalid pkm data</param>
        /// <returns>Legalized PKM (hopefully legal)</returns>
        public static PKM Legalize(this ITrainerInfo tr, PKM pk)
        {
            var set   = new ShowdownSet(ShowdownSet.GetShowdownText(pk));
            var legal = tr.GetLegalFromTemplate(pk, set, out var satisfied);

            if (satisfied)
            {
                return(legal);
            }

            var dest      = new PokeTrainerDetails(pk.Clone());
            var resetForm = ShowdownUtil.IsInvalidForm(set.Form);

            legal = BruteForce.ApplyDetails(pk, set, resetForm, dest);
            legal.SetTrainerData(dest);
            return(legal);
        }
Exemple #10
0
        public QRView(PKM pkm)
        {
            InitializeComponent();

            Header.Text    = "PKHeX Mobile!" + Environment.NewLine + $"Data Format: {pkm.GetType().Name}";
            Preview.Source = (SKBitmapImageSource)pkm.Sprite();

            // get high resolution QR with dimensions best suited to the device's dimensions
            // we don't overlay the pkm sprite in this QR since we do it above
            var di    = DeviceDisplay.MainDisplayInfo;
            var width = Math.Min(di.Height, di.Width);
            var img   = QRBuilder.GetQR(pkm, (int)(width * 0.8));

            QR.Source = (SKBitmapImageSource)img;

            Desc.Text = ShowdownSet.GetShowdownText(pkm);
        }
        private async void B_ExportShowdownPKM_Click(object sender, EventArgs e)
        {
            try
            {
                await Clipboard.SetTextAsync(ShowdownSet.GetShowdownText(VM.Pane)).ConfigureAwait(false);

                await UserDialogs.Instance
                .AlertAsync("Set the exported Showdown Set to the device clipboard!")
                .ConfigureAwait(false);
            }
            catch
            {
                await UserDialogs.Instance
                .AlertAsync("Failed to set Showdown Set to Clipboard.")
                .ConfigureAwait(false);
            }
        }
Exemple #12
0
        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         = GetURL(speciesName, form);
            string smogonPage  = GetSmogonPage(url);

            string[]      split1 = smogonPage.Split(new string[] { "\",\"abilities\":" }, StringSplitOptions.None);
            List <string> sets   = new List <string>();

            for (int i = 1; i < split1.Length; i++)
            {
                sets.Add(split1[i].Split(new string[] { "\"]}" }, StringSplitOptions.None)[0]);
            }
            string showdownSpec = speciesName;

            if (form != null)
            {
                if (form != "Mega" || form != "")
                {
                    showdownSpec += ("-" + form);
                }
            }
            string showdownsets = "";

            foreach (string set in sets)
            {
                showdownsets = showdownsets + ConvertSetToShowdown(set, showdownSpec) + Environment.NewLine + Environment.NewLine;
            }
            showdownsets.TrimEnd();
            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;
            }
            Clipboard.SetText(showdownsets);
            try { AutomaticLegality.ImportModded(); }
            catch { MessageBox.Show("Something went wrong"); }
            MessageBox.Show(AlertText(showdownSpec, sets.Count, GetTitles(smogonPage)));
        }
        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");
            }

            newShowdown.Insert(1, $"OT: {pkm.OT_Name}");
            return(Format.Code(string.Join("\n", newShowdown).TrimEnd()));
        }
        private async Task <bool> HandleEncounter(PK8 pk, bool legends, CancellationToken token)
        {
            encounterCount++;
            Log($"Encounter: {encounterCount}{Environment.NewLine}{ShowdownSet.GetShowdownText(pk)}{Environment.NewLine}");
            Counts.AddEncounteredSpecies(pk);
            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(!Hub.Config.StopConditions.CatchEncounter || Hub.Config.Encounter.EncounteringType == EncounterMode.StrongSpawn ? $"{Ping}Result found! Stopping routine execution; restart the bot(s) to search again." : "Result found! Attempting to catch...");
                if (Hub.Config.StopConditions.CaptureVideoClip)
                {
                    await Task.Delay(Hub.Config.StopConditions.ExtraTimeWaitCaptureVideo).ConfigureAwait(false);
                    await PressAndHold(CAPTURE, 2_000, 1_000, token).ConfigureAwait(false);
                }

                if (Hub.Config.StopConditions.CatchEncounter && (Hub.Config.Encounter.EncounteringType == EncounterMode.VerticalLine || Hub.Config.Encounter.EncounteringType == EncounterMode.HorizontalLine))
                {
                    await CatchWildPokemon(pk, token).ConfigureAwait(false);
                }

                return(true);
            }

            return(false);
        }
        protected override async Task MainLoop(CancellationToken token)
        {
            Log("Identifying trainer data of the host console.");
            await IdentifyTrainer(token).ConfigureAwait(false);

            await SetCurrentBox(0, token).ConfigureAwait(false);

            var existing = await ReadBoxPokemon(InjectBox, InjectSlot, token).ConfigureAwait(false);

            if (existing.Species != 0 && existing.ChecksumValid)
            {
                Log("Destination slot is occupied! Dumping the Pokémon found there...");
                DumpPokemon(DumpSetting.DumpFolder, "saved", existing);
            }
            Log("Clearing destination slot to start the bot.");
            await SetBoxPokemon(Blank, InjectBox, InjectSlot, token).ConfigureAwait(false);

            Log("Starting main EggBot loop.");
            Config.IterateNextRoutine();
            while (!token.IsCancellationRequested && Config.NextRoutineType == PokeRoutineType.EggFetch)
            {
                // Walk a step left, then right => check if egg was generated on this attempt.
                // Repeat until an egg is generated.

                var attempts = await StepUntilEgg(token).ConfigureAwait(false);

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

                Log($"Egg available after {attempts} attempts! Clearing destination slot.");
                await SetBoxPokemon(Blank, InjectBox, InjectSlot, token).ConfigureAwait(false);

                for (int i = 0; i < 6; i++)
                {
                    await Click(A, 0_400, token).ConfigureAwait(false);
                }

                // Safe to mash B from here until we get out of all menus.
                while (!await IsOnOverworld(Hub.Config, token).ConfigureAwait(false))
                {
                    await Click(B, 0_400, token).ConfigureAwait(false);
                }

                Log("Egg received. Checking details.");
                var pk = await ReadBoxPokemon(InjectBox, InjectSlot, token).ConfigureAwait(false);

                if (pk.Species == 0)
                {
                    Log("Invalid data detected in destination slot. Restarting loop.");
                    continue;
                }

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

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

                if (StopConditionSettings.EncounterFound(pk, DesiredIVs, Hub.Config.StopConditions))
                {
                    if (Hub.Config.Egg.ContinueAfterMatch)
                    {
                        Log($"{Ping}Result found! Continuing to collect more eggs.");
                        continue;
                    }
                    Log($"{Ping}Result found! Stopping routine execution; restart the bot(s) to search again.");
                    await DetachController(token).ConfigureAwait(false);

                    return;
                }
            }

            // If aborting the sequence, we might have the stick set at some position. Clear it just in case.
            await SetStick(LEFT, 0, 0, 0, CancellationToken.None).ConfigureAwait(false); // reset
        }
Exemple #16
0
        protected override async Task MainLoop(CancellationToken token)
        {
            Log("Identifying trainer data of the host console.");
            await IdentifyTrainer(token).ConfigureAwait(false);

            var originalTextSpeed = await EnsureTextSpeedFast(token).ConfigureAwait(false);

            Log("Checking destination slot for revived fossil Pokémon to see if anything is in the slot...");
            var existing = await GetBoxSlotQuality(InjectBox, InjectSlot, token).ConfigureAwait(false);

            if (existing.Quality != SlotQuality.Overwritable)
            {
                PrintBadSlotMessage(existing);
                return;
            }

            Log("Checking item counts...");
            var pouchData = await Connection.ReadBytesAsync(PokeDataOffsets.ItemTreasureAddress, 80, token).ConfigureAwait(false);

            var counts      = FossilCount.GetFossilCounts(pouchData);
            int reviveCount = counts.PossibleRevives(FossilSpecies);

            if (reviveCount == 0)
            {
                Log("Insufficient fossil pieces to start. Please obtain at least one of each required fossil piece before starting.");
                return;
            }

            Log("Starting main FossilBot loop.");
            Config.IterateNextRoutine();
            while (!token.IsCancellationRequested && Config.NextRoutineType == PokeRoutineType.FossilBot)
            {
                await ReviveFossil(counts, token).ConfigureAwait(false);

                Log("Fossil revived. Checking details.");

                var pk = await ReadBoxPokemon(InjectBox, InjectSlot, token).ConfigureAwait(false);

                if (pk.Species == 0 || !pk.ChecksumValid)
                {
                    Log("Invalid data detected in destination slot. Restarting loop.");
                    continue;
                }

                encounterCount++;
                Log($"Encounter: {encounterCount}:{Environment.NewLine}{ShowdownSet.GetShowdownText(pk)}{Environment.NewLine}{Environment.NewLine}");
                if (DumpSetting.Dump)
                {
                    DumpPokemon(DumpSetting.DumpFolder, "fossil", pk);
                }

                Counts.AddCompletedFossils();

                if (StopCondition(pk))
                {
                    if (Settings.ContinueAfterMatch)
                    {
                        Log("Result found! Continuing to collect more fossils.");
                        continue;
                    }
                    Log("Result found! Stopping routine execution; re-start the bot(s) to search again.");
                    return;
                }

                if (encounterCount % reviveCount != 0)
                {
                    continue;
                }

                Log($"Ran out of fossils to revive {FossilSpecies}.");
                if (Settings.InjectWhenEmpty)
                {
                    Log("Restoring original pouch data.");
                    await Connection.WriteBytesAsync(pouchData, PokeDataOffsets.ItemTreasureAddress, token).ConfigureAwait(false);

                    await Task.Delay(200, token).ConfigureAwait(false);
                }
                else
                {
                    Log("Re-start the game then re-start the bot(s), or set \"Inject Fossils\" to True in the config.");
                    return;
                }
            }
            await SetTextSpeed(originalTextSpeed, token).ConfigureAwait(false);
        }
Exemple #17
0
        public static string GetFormattedShowdownText(PKM pkm)
        {
            var showdown = ShowdownSet.GetShowdownText(pkm);

            return(Format.Code(showdown));
        }
Exemple #18
0
        private async Task DoDogEncounter(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                Log("Looking for a new dog...");

                // At the start of each loop, an A press is needed to exit out of a prompt.
                await Click(A, 0_500, token).ConfigureAwait(false);
                await SetStick(LEFT, 0, 30000, 1_000, token).ConfigureAwait(false);

                // Encounters Zacian/Zamazenta
                await Click(A, 0_600, token).ConfigureAwait(false);

                // Cutscene loads
                await Click(A, 2_700, token).ConfigureAwait(false);

                // Click through all the menus.
                for (int i = 0; i < 4; i++)
                {
                    await Click(A, 1_000, token).ConfigureAwait(false);
                }

                Log("Encounter started! Checking details...");

                await Task.Delay(4_000, token).ConfigureAwait(false);

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

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

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

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

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

                // Wait for the entire cutscene until we can flee.
                await Task.Delay(19_500, token).ConfigureAwait(false);

                // Get rid of any stick stuff left over so we can flee properly.
                await ResetStick(token).ConfigureAwait(false);

                Log("Running away...");
                while (await IsInBattle(token).ConfigureAwait(false))
                {
                    await FleeToOverworld(token).ConfigureAwait(false);
                }

                // Extra delay to be sure we're fully out of the battle.
                await Task.Delay(0_250, token).ConfigureAwait(false);
            }
        }
Exemple #19
0
        private void LegalizeBoxes(object sender, EventArgs e)
        {
            IList <PKM> BoxData = C_SAV.SAV.BoxData;

            for (int i = 0; i < 30; i++)
            {
                PKM  illegalPK = PreparePKM();
                bool box       = false;
                if ((ModifierKeys & Keys.Control) == Keys.Control)
                {
                    box = true;
                }
                if (box)
                {
                    illegalPK = BoxData[C_SAV.CurrentBox * C_SAV.SAV.BoxSlotCount + i];
                }
                if (illegalPK.Species > 0 && !new LegalityAnalysis(illegalPK).Valid)
                {
                    ShowdownSet Set       = new ShowdownSet(ShowdownSet.GetShowdownText(illegalPK));
                    bool        resetForm = false;
                    if (Set.Form != null)
                    {
                        if (Set.Form.Contains("Mega") || Set.Form == "Primal" || Set.Form == "Busted")
                        {
                            resetForm = true;
                        }
                    }
                    PKM  legal;
                    PKM  APIGenerated = C_SAV.SAV.BlankPKM;
                    bool satisfied    = false;
                    try {
                        APIGenerated = AutoLegalityModMain.AutoLegalityMod.APILegality(illegalPK, Set, out satisfied);
                    }
                    catch {
                        satisfied = false;
                    }
                    if (!satisfied)
                    {
                        Blah b = new Blah();
                        b.SAV = C_SAV.SAV;
                        legal = b.LoadShowdownSetModded_PKSM(illegalPK, Set, resetForm, illegalPK.TID, illegalPK.SID, illegalPK.OT_Name, illegalPK.OT_Gender);
                    }
                    else
                    {
                        legal = APIGenerated;
                    }
                    legal = PKME_Tabs.SetTrainerData(illegalPK.OT_Name, illegalPK.TID, illegalPK.SID, illegalPK.OT_Gender, legal, satisfied);
                    if (box)
                    {
                        BoxData[C_SAV.CurrentBox * C_SAV.SAV.BoxSlotCount + i] = legal;
                    }
                    else
                    {
                        PKME_Tabs.PopulateFields(legal);
                        WinFormsUtil.Alert("Legalized Active Pokemon.");
                        return;
                    }
                }
            }
            C_SAV.SAV.BoxData = BoxData;
            C_SAV.ReloadSlots();
            WinFormsUtil.Alert("Legalized Box Pokemon");
        }
Exemple #20
0
        private async Task WalkInLine(CancellationToken token)
        {
            if (hub.Config.Encounter.CatchEncounter && !hub.Config.Encounter.StrongSpawn)
            {
                Log("Checking Poké Ball count...");
                pouchData = await Connection.ReadBytesAsync(PokeBallOffset, 116, token).ConfigureAwait(false);

                var counts = EncounterCount.GetBallCounts(pouchData);
                catchCount = counts.PossibleCatches(Ball.Master);

                if (catchCount == 0)
                {
                    Log("Insufficient Master Balls. Please obtain at least one before starting.");
                    return;
                }
            }

            while (!token.IsCancellationRequested)
            {
                if (hub.Config.Encounter.StrongSpawn)
                {
                    await StrongSpawn(token).ConfigureAwait(false);
                }

                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();
                Counts.AddEncounteredSpecies(pk);

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

                // Offsets are flickery so make sure we see it 3 times.
                for (int i = 0; i < 3; i++)
                {
                    await ReadUntilChanged(BattleMenuOffset, BattleMenuReady, 5_000, 0_100, true, token).ConfigureAwait(false);
                }

                if (StopCondition(pk))
                {
                    if (hub.Config.CaptureVideoClip)
                    {
                        await PressAndHold(CAPTURE, 2_000, 1_000, token).ConfigureAwait(false);
                    }

                    if (hub.Config.Encounter.CatchEncounter && !hub.Config.Encounter.StrongSpawn)
                    {
                        await SetLastUsedBall(Ball.Master, token).ConfigureAwait(false);

                        Log($"Result found! Attempting to catch...");
                        await CatchWildPokemon(pk, token).ConfigureAwait(false);

                        if (!hub.Config.Encounter.InjectPokeBalls && encounterCount != 0 && encounterCount % catchCount == 0)
                        {
                            return;
                        }

                        await WalkInLine(token).ConfigureAwait(false);
                    }

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

                Log("Running away...");
                while (await IsInBattle(token).ConfigureAwait(false) && !hub.Config.Encounter.StrongSpawn)
                {
                    await FleeToOverworld(token).ConfigureAwait(false);
                }
            }
        }
Exemple #21
0
        protected override async Task MainLoop(CancellationToken token)
        {
            Log("Identifying trainer data of the host console.");
            await IdentifyTrainer(token).ConfigureAwait(false);

            await SetCurrentBox(0, token).ConfigureAwait(false);

            var existing = await ReadBoxPokemon(InjectBox, InjectSlot, token).ConfigureAwait(false);

            if (existing.Species != 0 && existing.ChecksumValid)
            {
                Log("Destination slot is occupied! Dumping the Pokémon found there...");
                DumpPokemon(DumpSetting.DumpFolder, "saved", existing);
            }
            Log("Clearing destination slot to start the bot.");
            await SetBoxPokemon(Blank, InjectBox, InjectSlot, token).ConfigureAwait(false);

            Log("Checking item counts...");
            var pouchData = await Connection.ReadBytesAsync(ItemTreasureAddress, 80, Config.ConnectionType, token).ConfigureAwait(false);

            var counts      = FossilCount.GetFossilCounts(pouchData);
            int reviveCount = counts.PossibleRevives(Hub.Config.Fossil.Species);

            if (reviveCount == 0)
            {
                Log("Insufficient fossil pieces. Please obtain at least one of each required fossil piece first.");
                return;
            }

            Log("Starting main FossilBot loop.");
            Config.IterateNextRoutine();
            while (!token.IsCancellationRequested && Config.NextRoutineType == PokeRoutineType.FossilBot)
            {
                if (encounterCount != 0 && encounterCount % reviveCount == 0)
                {
                    Log($"Ran out of fossils to revive {Hub.Config.Fossil.Species}.");
                    if (Hub.Config.Fossil.InjectWhenEmpty)
                    {
                        Log("Restoring original pouch data.");
                        await Connection.WriteBytesAsync(pouchData, ItemTreasureAddress, Config.ConnectionType, token).ConfigureAwait(false);

                        await Task.Delay(500, token).ConfigureAwait(false);
                    }
                    else
                    {
                        Log("Restart the game and the bot(s) or set \"Inject Fossils\" to True in the config.");
                        return;
                    }
                }

                await ReviveFossil(counts, token).ConfigureAwait(false);

                Log("Fossil revived. Checking details...");

                var pk = await ReadBoxPokemon(InjectBox, InjectSlot, token).ConfigureAwait(false);

                if (pk.Species == 0 || !pk.ChecksumValid)
                {
                    Log("Invalid data detected in destination slot. Restarting loop.");
                    continue;
                }

                encounterCount++;
                Log($"Encounter: {encounterCount}:{Environment.NewLine}{ShowdownSet.GetShowdownText(pk)}{Environment.NewLine}{Environment.NewLine}");
                if (DumpSetting.Dump)
                {
                    DumpPokemon(DumpSetting.DumpFolder, "fossil", pk);
                }

                Counts.AddCompletedFossils();
                Counts.AddEncounteredSpecies(pk);

                if (StopConditionSettings.EncounterFound(pk, DesiredIVs, Hub.Config.StopConditions))
                {
                    if (Hub.Config.StopConditions.CaptureVideoClip)
                    {
                        await Task.Delay(Hub.Config.StopConditions.ExtraTimeWaitCaptureVideo).ConfigureAwait(false);
                        await PressAndHold(CAPTURE, 2_000, 1_000, token).ConfigureAwait(false);
                    }

                    if (Hub.Config.Fossil.ContinueAfterMatch)
                    {
                        Log($"{Ping}Result found! Continuing to collect more fossils.");
                    }
                    else
                    {
                        Log($"{Ping}Result found! Stopping routine execution; restart the bot(s) to search again.");
                        await DetachController(token).ConfigureAwait(false);

                        return;
                    }
                }

                Log("Clearing destination slot.");
                await SetBoxPokemon(Blank, InjectBox, InjectSlot, token).ConfigureAwait(false);
            }
        }
Exemple #22
0
        private async Task <PokeTradeResult> PerformLinkCodeTrade(SAV8SWSH sav, PokeTradeDetail <PK8> poke, CancellationToken token)
        {
            // Update Barrier Settings
            UpdateBarrier(poke.IsSynchronized);
            poke.TradeInitialize(this);
            Hub.Config.Stream.EndEnterCode(this);

            if (await CheckIfSoftBanned(token).ConfigureAwait(false))
            {
                await Unban(token).ConfigureAwait(false);
            }

            var pkm = poke.TradeData;

            if (pkm.Species != 0)
            {
                await SetBoxPokemon(pkm, InjectBox, InjectSlot, token, sav).ConfigureAwait(false);
            }

            if (!await IsOnOverworld(Hub.Config, token).ConfigureAwait(false))
            {
                await ExitTrade(Hub.Config, true, token).ConfigureAwait(false);

                return(PokeTradeResult.RecoverStart);
            }

            while (await CheckIfSearchingForLinkTradePartner(token).ConfigureAwait(false))
            {
                Log("Still searching, reset bot position.");
                await ResetTradePosition(Hub.Config, token).ConfigureAwait(false);
            }

            Log("Opening Y-Comm Menu");
            await Click(Y, 2_000, token).ConfigureAwait(false);

            Log("Selecting Link Trade");
            await Click(A, 1_500, token).ConfigureAwait(false);

            Log("Selecting Link Trade Code");
            await Click(DDOWN, 500, token).ConfigureAwait(false);

            for (int i = 0; i < 2; i++)
            {
                await Click(A, 1_500, token).ConfigureAwait(false);
            }

            // All other languages require an extra A press at this menu.
            if (GameLang != LanguageID.English && GameLang != LanguageID.Spanish)
            {
                await Click(A, 1_500, token).ConfigureAwait(false);
            }

            // Loading Screen
            await Task.Delay(1_000, token).ConfigureAwait(false);

            if (poke.Type != PokeTradeType.Random)
            {
                Hub.Config.Stream.StartEnterCode(this);
            }
            await Task.Delay(1_000, token).ConfigureAwait(false);

            var code = poke.Code;

            Log($"Entering Link Trade Code: {code:0000 0000}...");
            await EnterTradeCode(code, Hub.Config, token).ConfigureAwait(false);

            // Wait for Barrier to trigger all bots simultaneously.
            WaitAtBarrierIfApplicable(token);
            await Click(PLUS, 1_000, token).ConfigureAwait(false);

            Hub.Config.Stream.EndEnterCode(this);

            // Confirming and return to overworld.
            var delay_count = 0;

            while (!await IsOnOverworld(Hub.Config, token).ConfigureAwait(false))
            {
                if (delay_count >= 5)
                {
                    await ExitTrade(Hub.Config, true, token).ConfigureAwait(false);

                    return(PokeTradeResult.RecoverPostLinkCode);
                }

                for (int i = 0; i < 5; i++)
                {
                    await Click(A, 0_800, token).ConfigureAwait(false);
                }
                delay_count++;
            }

            poke.TradeSearching(this);
            await Task.Delay(0_500, token).ConfigureAwait(false);

            // Wait for a Trainer...
            Log("Waiting for trainer...");
            bool partnerFound = await WaitForPokemonChanged(LinkTradePartnerPokemonOffset, Hub.Config.Trade.TradeWaitTime * 1_000, 0_200, token).ConfigureAwait(false);

            if (token.IsCancellationRequested)
            {
                return(PokeTradeResult.Aborted);
            }
            if (!partnerFound)
            {
                await ResetTradePosition(Hub.Config, token).ConfigureAwait(false);

                return(PokeTradeResult.NoTrainerFound);
            }

            // Select Pokemon
            // pkm already injected to b1s1
            await Task.Delay(5_500, token).ConfigureAwait(false); // necessary delay to get to the box properly

            var TrainerName = await GetTradePartnerName(TradeMethod.LinkTrade, token).ConfigureAwait(false);

            Log($"Found Trading Partner: {TrainerName}...");

            if (!await IsInBox(token).ConfigureAwait(false))
            {
                await ExitTrade(Hub.Config, true, token).ConfigureAwait(false);

                return(PokeTradeResult.RecoverOpenBox);
            }

            // Confirm Box 1 Slot 1
            if (poke.Type == PokeTradeType.Specific || poke.Type == PokeTradeType.TradeCord || poke.Type == PokeTradeType.Giveaway)
            {
                for (int i = 0; i < 5; i++)
                {
                    await Click(A, 0_500, token).ConfigureAwait(false);
                }
            }

            poke.SendNotification(this, $"Found Trading Partner: {TrainerName}. Waiting for a Pokémon...");

            if (poke.Type == PokeTradeType.Dump)
            {
                return(await ProcessDumpTradeAsync(poke, token).ConfigureAwait(false));
            }

            // Wait for User Input...
            var pk = await ReadUntilPresent(LinkTradePartnerPokemonOffset, 25_000, 1_000, token).ConfigureAwait(false);

            var oldEC = await Connection.ReadBytesAsync(LinkTradePartnerPokemonOffset, 4, token).ConfigureAwait(false);

            if (pk == null)
            {
                await ExitTrade(Hub.Config, true, token).ConfigureAwait(false);

                return(PokeTradeResult.TrainerTooSlow);
            }

            if (poke.Type == PokeTradeType.Seed)
            {
                // Immediately exit, we aren't trading anything.
                return(await EndSeedCheckTradeAsync(poke, pk, token).ConfigureAwait(false));
            }

            if (poke.Type == PokeTradeType.Random) // distribution
            {
                // Allow the trade partner to do a Ledy swap.
                var trade = Hub.Ledy.GetLedyTrade(pk, Hub.Config.Distribution.LedySpecies);
                if (trade != null)
                {
                    pkm            = trade.Receive;
                    poke.TradeData = pkm;

                    poke.SendNotification(this, "Injecting the requested Pokémon.");
                    await Click(A, 0_800, token).ConfigureAwait(false);
                    await SetBoxPokemon(pkm, InjectBox, InjectSlot, token, sav).ConfigureAwait(false);

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

                for (int i = 0; i < 5; i++)
                {
                    await Click(A, 0_500, token).ConfigureAwait(false);
                }
            }
            else if (poke.Type == PokeTradeType.FixOT)
            {
                var clone = (PK8)pk.Clone();
                var adOT  = System.Text.RegularExpressions.Regex.Match(clone.OT_Name, @"(YT$)|(YT\w*$)|(Lab$)|(\.\w*)|(TV$)|(PKHeX)|(FB:)|(SysBot)|(AuSLove)|(ShinyMart)|(Blainette)").Value != "" ||
                            System.Text.RegularExpressions.Regex.Match(clone.Nickname, @"(YT$)|(YT\w*$)|(Lab$)|(\.\w*)|(TV$)|(PKHeX)|(FB:)|(SysBot)|(AuSLove)|(ShinyMart)|(Blainette)").Value != "";

                var extraInfo = $"\nBall: {(Ball)clone.Ball}\nShiny: {(clone.ShinyXor == 0 ? "Square" : clone.ShinyXor <= 16 ? "Star" : "No")}{(clone.FatefulEncounter ? "" : $"\nOT: {TrainerName}")}";
                var laInit    = new LegalityAnalysis(clone);
                if (laInit.Valid && adOT)
                {
                    clone.OT_Name       = clone.FatefulEncounter ? clone.OT_Name : $"{TrainerName}";
                    clone.PKRS_Infected = false;
                    clone.PKRS_Cured    = false;
                    clone.PKRS_Days     = 0;
                    clone.PKRS_Strain   = 0;
                }
                else if (!laInit.Valid)
                {
                    Log($"FixOT request has detected an invalid Pokémon from {poke.Trainer.TrainerName}: {(Species)clone.Species}");
                    if (DumpSetting.Dump)
                    {
                        DumpPokemon(DumpSetting.DumpFolder, "hacked", clone);
                    }

                    poke.SendNotification(this, $"```fix\nShown Pokémon is invalid. Attempting to regenerate... \n{laInit.Report()}```");
                    if (clone.FatefulEncounter)
                    {
                        clone.SetDefaultNickname(laInit);
                        var mg = EncounterEvent.GetAllEvents().Where(x => x.Species == clone.Species && x.Form == clone.AltForm && x.IsShiny == clone.IsShiny && x.OT_Name == clone.OT_Name).ToList();
                        if (mg.Count > 0)
                        {
                            clone = TradeExtensions.CherishHandler(mg.First());
                        }
                        else
                        {
                            clone = (PK8)AutoLegalityWrapper.GetTrainerInfo(8).GetLegal(AutoLegalityWrapper.GetTemplate(new ShowdownSet(ShowdownSet.GetShowdownText(clone) + extraInfo)), out _);
                        }
                    }
                    else
                    {
                        clone = (PK8)AutoLegalityWrapper.GetTrainerInfo(8).GetLegal(AutoLegalityWrapper.GetTemplate(new ShowdownSet(ShowdownSet.GetShowdownText(clone) + extraInfo)), out _);
                    }
                    var laRegen = new LegalityAnalysis(clone);
                    if (laRegen.Valid)
                    {
                        poke.SendNotification(this, $"```fix\nRegenerated and legalized your {(Species)clone.Species}!```");
                    }
                }
                else if (!adOT && laInit.Valid)
                {
                    poke.SendNotification(this, "```fix\nNo ad detected in Nickname or OT, and the Pokémon is legal. Exiting trade.```");
                    await ExitTrade(Hub.Config, true, token).ConfigureAwait(false);

                    return(PokeTradeResult.Aborted);
                }

                clone = (PK8)TradeExtensions.TrashBytes(clone, new LegalityAnalysis(clone));
                var la = new LegalityAnalysis(clone);
                if (!la.Valid)
                {
                    var report = la.Report();
                    Log(report);
                    poke.SendNotification(this, "This Pokémon is not legal per PKHeX's legality checks. I was unable to fix this. Exiting trade.");
                    poke.SendNotification(this, report);
                    await ExitTrade(Hub.Config, true, token).ConfigureAwait(false);

                    return(PokeTradeResult.IllegalTrade);
                }

                if (Hub.Config.Legality.ResetHOMETracker)
                {
                    clone.Tracker = 0;
                }

                poke.SendNotification(this, $"```fix\nNow confirm the trade!```");
                Log($"{(!laInit.Valid ? "Legalized" : "Fixed Nickname/OT for")} {(Species)clone.Species}!");

                bool changed = await ReadUntilChanged(LinkTradePartnerPokemonOffset, oldEC, 10_000, 0_200, false, token).ConfigureAwait(false);

                if (changed)
                {
                    Log($"{poke.Trainer.TrainerName} changed the shown Pokémon ({(Species)clone.Species})");
                    poke.SendNotification(this, $"```fix\nSend away the originally shown Pokémon, please.```");
                    changed = !await ReadUntilChanged(LinkTradePartnerPokemonOffset, oldEC, 15_000, 0_200, true, token).ConfigureAwait(false);
                }

                var pk2 = await ReadUntilPresent(LinkTradePartnerPokemonOffset, 3_000, 1_000, token).ConfigureAwait(false);

                if (changed || pk2 == null || SearchUtil.HashByDetails(pk2) != SearchUtil.HashByDetails(pk))
                {
                    Log("Trading partner did not wish to send away their ad-mon.");
                    await ExitTrade(Hub.Config, true, token).ConfigureAwait(false);

                    return(PokeTradeResult.TrainerTooSlow);
                }

                await Click(A, 0_800, token).ConfigureAwait(false);
                await SetBoxPokemon(clone, InjectBox, InjectSlot, token, sav).ConfigureAwait(false);

                pkm = clone;

                for (int i = 0; i < 5; i++)
                {
                    await Click(A, 0_500, token).ConfigureAwait(false);
                }
            }
            else if (poke.Type == PokeTradeType.Clone)
            {
                // Inject the shown Pokémon.
                var clone = (PK8)pk.Clone();

                if (Hub.Config.Discord.ReturnPK8s)
                {
                    poke.SendNotification(this, clone, "Here's what you showed me!");
                }

                var la = new LegalityAnalysis(clone);
                if (!la.Valid)
                {
                    Log($"Clone request (from {poke.Trainer.TrainerName}) has detected an invalid Pokémon: {(Species)clone.Species}.");
                    if (DumpSetting.Dump)
                    {
                        DumpPokemon(DumpSetting.DumpFolder, "hacked", clone);
                    }

                    var report = la.Report();
                    Log(report);
                    poke.SendNotification(this, "This Pokémon is not legal per PKHeX's legality checks. I am forbidden from cloning this. Exiting trade.");
                    poke.SendNotification(this, report);

                    await ExitTrade(Hub.Config, true, token).ConfigureAwait(false);

                    return(PokeTradeResult.IllegalTrade);
                }

                if (Hub.Config.Legality.ResetHOMETracker)
                {
                    clone.Tracker = 0;
                }

                poke.SendNotification(this, $"**Cloned your {(Species)clone.Species}!**\nNow press B to cancel your offer and trade me a Pokémon you don't want.");
                Log($"Cloned a {(Species)clone.Species}. Waiting for user to change their Pokémon...");

                // Separate this out from WaitForPokemonChanged since we compare to old EC from original read.
                partnerFound = await ReadUntilChanged(LinkTradePartnerPokemonOffset, oldEC, 15_000, 0_200, false, token).ConfigureAwait(false);

                if (!partnerFound)
                {
                    poke.SendNotification(this, "**HEY CHANGE IT NOW OR I AM LEAVING!!!**");
                    // They get one more chance.
                    partnerFound = await ReadUntilChanged(LinkTradePartnerPokemonOffset, oldEC, 15_000, 0_200, false, token).ConfigureAwait(false);
                }

                var pk2 = await ReadUntilPresent(LinkTradePartnerPokemonOffset, 3_000, 1_000, token).ConfigureAwait(false);

                if (!partnerFound || pk2 == null || SearchUtil.HashByDetails(pk2) == SearchUtil.HashByDetails(pk))
                {
                    Log("Trading partner did not change their Pokémon.");
                    await ExitTrade(Hub.Config, true, token).ConfigureAwait(false);

                    return(PokeTradeResult.TrainerTooSlow);
                }

                await Click(A, 0_800, token).ConfigureAwait(false);
                await SetBoxPokemon(clone, InjectBox, InjectSlot, token, sav).ConfigureAwait(false);

                pkm = clone;

                for (int i = 0; i < 5; i++)
                {
                    await Click(A, 0_500, token).ConfigureAwait(false);
                }
            }

            await Click(A, 3_000, token).ConfigureAwait(false);

            for (int i = 0; i < 5; i++)
            {
                await Click(A, 1_500, token).ConfigureAwait(false);
            }

            delay_count = 0;
            while (!await IsInBox(token).ConfigureAwait(false))
            {
                await Click(A, 3_000, token).ConfigureAwait(false);

                delay_count++;
                if (delay_count >= 50)
                {
                    break;
                }
                if (await IsOnOverworld(Hub.Config, token).ConfigureAwait(false)) // In case we are in a Trade Evolution/PokeDex Entry and the Trade Partner quits we land on the Overworld
                {
                    break;
                }
            }

            await Task.Delay(1_000 + Util.Rand.Next(0_700, 1_000), token).ConfigureAwait(false);

            await ExitTrade(Hub.Config, false, token).ConfigureAwait(false);

            Log("Exited Trade!");

            if (token.IsCancellationRequested)
            {
                return(PokeTradeResult.Aborted);
            }

            // Trade was Successful!
            var traded = await ReadBoxPokemon(InjectBox, InjectSlot, token).ConfigureAwait(false);

            // Pokémon in b1s1 is same as the one they were supposed to receive (was never sent).
            if (poke.Type != PokeTradeType.FixOT && SearchUtil.HashByDetails(traded) == SearchUtil.HashByDetails(pkm))
            {
                Log("User did not complete the trade.");
                return(PokeTradeResult.TrainerTooSlow);
            }
            else
            {
                // As long as we got rid of our inject in b1s1, assume the trade went through.
                Log("User completed the trade.");
                poke.TradeFinished(this, traded);

                // Only log if we completed the trade.
                var counts = Hub.Counts;
                if (poke.Type == PokeTradeType.Random)
                {
                    counts.AddCompletedDistribution();
                }
                else if (poke.Type == PokeTradeType.Clone)
                {
                    counts.AddCompletedClones();
                }
                else if (poke.Type == PokeTradeType.FixOT)
                {
                    counts.AddCompletedFixOTs();
                }
                else if (poke.Type == PokeTradeType.TradeCord)
                {
                    counts.AddCompletedTradeCords();
                }
                else if (poke.Type == PokeTradeType.Giveaway)
                {
                    counts.AddCompletedGiveaways();
                }
                else
                {
                    Hub.Counts.AddCompletedTrade();
                }

                if (DumpSetting.Dump && !string.IsNullOrEmpty(DumpSetting.DumpFolder))
                {
                    var subfolder = poke.Type.ToString().ToLower();
                    DumpPokemon(DumpSetting.DumpFolder, subfolder, traded); // received
                    if (poke.Type == PokeTradeType.Specific || poke.Type == PokeTradeType.Clone || poke.Type == PokeTradeType.FixOT || poke.Type == PokeTradeType.TradeCord || poke.Type == PokeTradeType.Giveaway)
                    {
                        DumpPokemon(DumpSetting.DumpFolder, "traded", pkm); // sent to partner
                    }
                }
            }

            return(PokeTradeResult.Success);
        }
Exemple #23
0
        protected override async Task MainLoop(CancellationToken token)
        {
            Log("Identifying trainer data of the host console.");
            await IdentifyTrainer(token).ConfigureAwait(false);

            var originalTextSpeed = await EnsureTextSpeedFast(token).ConfigureAwait(false);

            await SetCurrentBox(0, token).ConfigureAwait(false);

            Log("Checking destination slot...");
            var existing = await GetBoxSlotQuality(InjectBox, InjectSlot, token).ConfigureAwait(false);

            if (existing.Quality != SlotQuality.Overwritable)
            {
                PrintBadSlotMessage(existing);
                return;
            }

            Log("Starting main EggBot loop.");
            Config.IterateNextRoutine();
            var blank = new PK8();

            while (!token.IsCancellationRequested && Config.NextRoutineType == PokeRoutineType.EggFetch)
            {
                // Walk a step left, then right => check if egg was generated on this attempt.
                // Repeat until an egg is generated.

                var attempts = await StepUntilEgg(token).ConfigureAwait(false);

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

                Log($"Egg available after {attempts} attempts! Clearing destination slot.");
                await SetBoxPokemon(blank, InjectBox, InjectSlot, token).ConfigureAwait(false);

                for (int i = 0; i < 4; i++)
                {
                    await Click(A, 0_400, token).ConfigureAwait(false);
                }

                // Safe to mash B from here until we get out of all menus. Currentscreen becomes 0xFFFFFFFF.
                while (!await IsOnOverworldFossil(token).ConfigureAwait(false))
                {
                    await Click(B, 0_400, token).ConfigureAwait(false);
                }

                Log("Egg received. Checking details.");
                var pk = await ReadBoxPokemon(InjectBox, InjectSlot, token).ConfigureAwait(false);

                if (pk.Species == 0)
                {
                    Log("Invalid data detected in destination slot. Restarting loop.");
                    continue;
                }

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

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

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

            // If aborting the sequence, we might have the stick set at some position. Clear it just in case.
            await SetStick(LEFT, 0, 0, 0, CancellationToken.None).ConfigureAwait(false); // reset
            await SetTextSpeed(originalTextSpeed, token).ConfigureAwait(false);
        }
Exemple #24
0
        protected override async Task MainLoop(CancellationToken token)
        {
            Connection.Log("Identifying trainer data of the host console.");
            await IdentifyTrainer(token).ConfigureAwait(false);

            Connection.Log("Checking destination slot for eggs to see if anything is in the slot...");
            var existing = await GetBoxSlotQuality(InjectBox, InjectSlot, token).ConfigureAwait(false);

            if (existing.Quality != SlotQuality.Overwritable)
            {
                PrintBadSlotMessage(existing);
                return;
            }

            Connection.Log("Starting main EggBot loop.");
            var blank = new PK8();

            while (!token.IsCancellationRequested && Config.NextRoutineType == PokeRoutineType.EggFetch)
            {
                // Walk a step left, then right => check if egg was generated on this attempt.
                // Repeat until an egg is generated.
                var attempts = await StepUntilEgg(token).ConfigureAwait(false);

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

                Connection.Log($"Egg available after {attempts} attempts! Clearing destination slot.");
                await SetBoxPokemon(blank, InjectBox, InjectSlot, token).ConfigureAwait(false);

                for (int i = 0; i < 4; i++)
                {
                    await Click(A, 500, token).ConfigureAwait(false);
                }
                await Task.Delay(4000, token).ConfigureAwait(false);

                await Click(A, 1850, token).ConfigureAwait(false);
                await Click(A, 1850, token).ConfigureAwait(false);
                await Click(A, 450, token).ConfigureAwait(false);

                Connection.Log("Egg received. Checking details.");
                var pk = await ReadBoxPokemon(InjectBox, InjectSlot, token).ConfigureAwait(false);

                if (pk.Species == 0)
                {
                    Connection.Log("Invalid data detected in destination slot. Restarting loop.");
                    continue;
                }

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

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

                encounterCount++;
                if (!StopCondition(pk))
                {
                    continue;
                }

                Connection.Log("Result found! Stopping routine execution; re-start the bot(s) to search again.");
                break;
            }

            // If aborting the sequence, we might have the stick set at some position. Clear it just in case.
            await SetStick(LEFT, 0, 0, 0, CancellationToken.None).ConfigureAwait(false); // reset
        }
Exemple #25
0
        private void B_ReadPKM_Click(object sender, EventArgs e)
        {
            var offset = (uint)NUD_Read.Value;

            if (!GetPKM(offset, out var pkm))
            {
                WinFormsUtil.Alert("No PKM in slot.");
                return;
            }
            Plugin.PKMEditor.PopulateFields(pkm);
            L_LastViewed.Text    = "Last Viewed:" + Environment.NewLine + Environment.NewLine + ShowdownSet.GetShowdownText(pkm);
            L_LastViewed.Visible = true;
        }
 public RegenTemplate(PKM pk) : this(new ShowdownSet(ShowdownSet.GetShowdownText(pk)))
 {
     this.FixGender(pk.PersonalInfo);
 }
Exemple #27
0
        private void Legalize(object sender, EventArgs e)
        {
            AutomaticLegality.PKMEditor         = PKMEditor;
            AutomaticLegality.SaveFileEditor    = SaveFileEditor;
            AutoLegalityMod.AutoLegalityMod.SAV = SaveFileEditor.SAV;
            IList <PKM> BoxData = SaveFileEditor.SAV.BoxData;

            for (int i = 0; i < 30; i++)
            {
                PKM  illegalPK = PKMEditor.PreparePKM();
                bool box       = false;
                if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
                {
                    box = true;
                }

                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));
                    bool        resetForm = false;
                    if (Set.Form != null)
                    {
                        if (Set.Form.Contains("Mega") || Set.Form == "Primal" || Set.Form == "Busted")
                        {
                            resetForm = true;
                        }
                    }
                    PKM  legal;
                    PKM  APIGenerated = SaveFileEditor.SAV.BlankPKM;
                    bool satisfied    = false;
                    try { APIGenerated = AutoLegalityMod.AutoLegalityMod.APILegality(illegalPK, Set, out satisfied); }
                    catch { satisfied = false; }
                    if (!satisfied)
                    {
                        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;
                    }

                    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;
                    }
                    else
                    {
                        PKMEditor.PopulateFields(legal);
                        MessageBox.Show("Legalized Active Pokemon.");
                        return;
                    }
                }
            }
            SaveFileEditor.SAV.BoxData = BoxData;
            SaveFileEditor.ReloadSlots();
            MessageBox.Show("Legalized Box Pokemon");
        }
Exemple #28
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);
                }

                // Offsets are flickery so make sure we see it 3 times.
                for (int i = 0; i < 3; i++)
                {
                    await ReadUntilChanged(BattleMenuOffset, BattleMenuReady, 5_000, 0_100, true, token).ConfigureAwait(false);
                }

                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;
                }

                Log("Running away...");
                while (await IsInBattle(token).ConfigureAwait(false))
                {
                    await FleeToOverworld(token).ConfigureAwait(false);
                }
            }
        }
        private static bool AddToTradeQueue(this SocketCommandContext Context, PK8 pk8, int code, string trainerName, bool sudo, PokeRoutineType type, PokeTradeType t, out string msg)
        {
            var user   = Context.User;
            var userID = user.Id;
            var name   = user.Username;

            var trainer  = new PokeTradeTrainerInfo(trainerName);
            var notifier = new DiscordTradeNotifier <PK8>(pk8, trainer, code, Context);
            var detail   = new PokeTradeDetail <PK8>(pk8, trainer, notifier, t, code: code);
            var trade    = new TradeEntry <PK8>(detail, userID, type, name);

            var hub   = SysCordInstance.Self.Hub;
            var Info  = hub.Queues.Info;
            var added = Info.AddToTradeQueue(trade, userID, sudo);

            if (added == QueueResultAdd.AlreadyInQueue)
            {
                msg = "Sorry, you are already in the queue.";
                return(false);
            }

            var position = Info.CheckPosition(userID, type);

            var ticketID = "";

            if (TradeStartModule.IsStartChannel(Context.Channel.Id))
            {
                ticketID = $", unique ID: {detail.ID}";
            }

            var pokeName = "";

            if (t == PokeTradeType.Specific || t == PokeTradeType.EggRoll && pk8.Species != 0)
            {
                pokeName = $" Receiving: {(t == PokeTradeType.EggRoll ? "Mysterious egg" : hub.Config.Trade.ItemMuleSpecies == (Species)pk8.Species && pk8.HeldItem != 0 ? $"{(Species)pk8.Species + " (" + ShowdownSet.GetShowdownText(pk8).Split('@','\n')[1].Trim() + ")"}" : $"{(Species)pk8.Species}")}.";
            }
            msg = $"{user.Mention} - Added to the {type} queue{ticketID}. Current Position: {position.Position}.{pokeName}";

            var botct = Info.Hub.Bots.Count;

            if (position.Position > botct)
            {
                var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct);
                msg += $" Estimated: {eta:F1} minutes.";
            }
            return(true);
        }
Exemple #30
0
        private static bool AddToTradeQueue(this SocketCommandContext Context, PK8 pk8, int code, string trainerName, RequestSignificance sig, PokeRoutineType type, PokeTradeType t, SocketUser trader, out string msg, string requestedIgn = "")
        {
            var user   = trader;
            var userID = user.Id;
            var name   = user.Username;

            var trainer  = new PokeTradeTrainerInfo(trainerName);
            var notifier = new DiscordTradeNotifier <PK8>(pk8, trainer, code, Context, user);
            var detail   = new PokeTradeDetail <PK8>(pk8, trainer, notifier, t, code, userID, sig == RequestSignificance.Favored, requestedIgn);
            var trade    = new TradeEntry <PK8>(detail, userID, type, name);

            var hub   = SysCordInstance.Self.Hub;
            var Info  = hub.Queues.Info;
            var added = Info.AddToTradeQueue(trade, userID, sig == RequestSignificance.Favored);

            if (added == QueueResultAdd.AlreadyInQueue)
            {
                msg = "Sorry, you are already in the queue.";
                return(false);
            }

            var position = Info.CheckPosition(userID, type);
            var ticketID = "";

            if (TradeStartModule.IsStartChannel(Context.Channel.Id))
            {
                ticketID = $", unique ID: {detail.ID}";
            }

            var pokeName = "";

            if (t == PokeTradeType.LanTrade || t == PokeTradeType.Specific || t == PokeTradeType.EggRoll && Info.Hub.Config.Discord.DisplayPokeName && pk8.Species != 0)
            {
                pokeName = $" Receiving: {(t == PokeTradeType.EggRoll ? "Mysterious Egg" : hub.Config.Trade.ItemMuleSpecies == (Species)pk8.Species && pk8.HeldItem != 0 ? $"{(Species)pk8.Species + " (" + ShowdownSet.GetShowdownText(pk8).Split('@', '\n')[1].Trim() + ")"}" : $"{(Species)pk8.Species}")}{(pk8.IsEgg && t != PokeTradeType.EggRoll ? " (Egg)" : "")}.";
            }

            if (t == PokeTradeType.LanRoll && Info.Hub.Config.Discord.DisplayPokeName && pk8.Species != 0)
            {
                pokeName = $" Receiving: An Illegal Egg.";
            }

            string overallPosition = "";

            if (Info.Hub.Config.Discord.PostOverallQueueCount)
            {
                if (position.QueueCount != position.OverallQueueCount)
                {
                    if (type == PokeRoutineType.SeedCheck && hub.Config.Queues.FlexMode == FlexYieldMode.LessCheatyFirst)
                    {
                        overallPosition = $" | __Overall: {position.Position}/{position.OverallQueueCount}__";
                    }
                    else
                    {
                        overallPosition = $" | __Overall: {position.OverallPosition}/{position.OverallQueueCount}__";
                    }
                }
                else
                {
                    overallPosition = $"";
                }
            }

            var ignName = "";

            if (t == PokeTradeType.LanTrade || t == PokeTradeType.LanRoll)
            {
                if (requestedIgn != string.Empty)
                {
                    ignName = $" Looking for {requestedIgn}.";
                }
            }

            msg = $"{user.Mention} - Added to the **{type}** queue{ticketID}. Current Position: __{type}: {position.Position}/{position.QueueCount}__{overallPosition}.{pokeName}{ignName}";

            var botct = Info.Hub.Bots.Count;

            if (position.Position > botct)
            {
                var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct);
                msg += $" Estimated: {eta:F1} minutes.";
            }
            return(true);
        }