示例#1
0
        private async Task CatchWildPokemon(PK8 pk, CancellationToken token)
        {
            var check = await ReadPokemon(WildPokemonOffset, token).ConfigureAwait(false);

            if (encounterCount != 0 && encounterCount % catchCount == 0)
            {
                Log($"Ran out of Master Balls to catch {SpeciesName.GetSpeciesName(pk.Species, 2)}.");
                if (Hub.Config.StopConditions.InjectPokeBalls)
                {
                    Log("Restoring original pouch data.");
                    await Connection.WriteBytesAsync(pouchData, PokeBallOffset, Config.ConnectionType, token).ConfigureAwait(false);

                    await Task.Delay(500, token).ConfigureAwait(false);
                }
                else
                {
                    Log($"{Ping}Result found! Stopping routine execution; restart the bot(s) to search again.");
                    return;
                }
            }

            await SetLastUsedBall(Ball.Master, token).ConfigureAwait(false);
            await Click(B, 1_000, token).ConfigureAwait(false);
            await Click(X, 1_000, token).ConfigureAwait(false);
            await Click(A, 3_000, token).ConfigureAwait(false); // Throw ball

            await Click(B, 1_000, token).ConfigureAwait(false);
            await Click(B, 1_000, token).ConfigureAwait(false); // Just in case we didn't

            await Click(X, 1_000, token).ConfigureAwait(false);
            await Click(A, 1_000, token).ConfigureAwait(false); // Attempt again to be sure

            while (!await IsOnOverworld(Hub.Config, token).ConfigureAwait(false) && check.Species != 0)
            {
                await Click(B, 0_400, token).ConfigureAwait(false);
            }

            if (await IsOnOverworld(Hub.Config, token).ConfigureAwait(false) && !await IsInBattle(token).ConfigureAwait(false))
            {
                Log($"{Ping}Caught {SpeciesName.GetSpeciesName(pk.Species, 2)}! Resuming routine...");
                await WalkInLine(token).ConfigureAwait(false);
            }
        }
示例#2
0
        private async Task DoRegiEncounter(CancellationToken token)
        {
            while (!token.IsCancellationRequested && Config.NextRoutineType == PokeRoutineType.EncounterBot)
            {
                while (!await IsInBattle(token).ConfigureAwait(false))
                {
                    await Click(A, 2_000, token).ConfigureAwait(false);
                }

                var pk = await ReadUntilPresent(Hub.Config.Encounter.EncounteringType == EncounterMode.Regi?WildPokemonOffset : RaidPokemonOffset, 2_000, 0_200, token).ConfigureAwait(false);

                if (pk == null)
                {
                    Log("Invalid data detected. Restarting loop.");
                    continue;
                }
                else
                {
                    if (await HandleEncounter(pk, true, token).ConfigureAwait(false))
                    {
                        return;
                    }
                }

                Log($"Resetting {SpeciesName.GetSpeciesNameGeneration(pk.Species, 2, 8)} by restarting the game");
                await CloseGame(Hub.Config, token).ConfigureAwait(false);

                await Click(A, 1_000 + Hub.Config.Timings.ExtraTimeLoadProfile, token).ConfigureAwait(false);
                await Click(A, 1_000 + Hub.Config.Timings.ExtraTimeCheckDLC, token).ConfigureAwait(false);
                await Click(DUP, 0_600, token).ConfigureAwait(false);
                await Click(A, 0_600, token).ConfigureAwait(false);

                Log("Restarting the game and mashing A until in battle!");

                await Task.Delay(11_000 + Hub.Config.Timings.ExtraTimeLoadGame, token).ConfigureAwait(false);

                for (int i = 0; i < 5; i++)
                {
                    await Click(A, 1_000, token).ConfigureAwait(false);
                }
            }
        }
示例#3
0
    protected override byte[] GetNonNickname(int language)
    {
        var name = SpeciesName.GetSpeciesNameGeneration(Species, language, Format);
        var len  = Nickname_Trash.Length;

        byte[] data = new byte[len];
        SetString(name.AsSpan(), data, len, StringConverterOption.Clear50);
        if (!Korean)
        {
            // Decimal point<->period fix
            for (int i = 0; i < data.Length; i++)
            {
                if (data[i] == 0xF2)
                {
                    data[i] = 0xE8;
                }
            }
        }
        return(data);
    }
示例#4
0
        private void UpdateNickname(object sender, EventArgs e)
        {
            if (!CHK_Nicknamed.Checked)
            {
                // Fetch Current Species and set it as Nickname Text
                int species = WinFormsUtil.GetIndex(CB_Species);
                if (species == 0 || species > (int)Species.Volcanion)
                {
                    TB_Nickname.Text = string.Empty;
                }
                else
                {
                    // get language
                    TB_Nickname.Text = SpeciesName.GetSpeciesNameGeneration(species, SAV.Language, 6);
                }
            }
            TB_Nickname.ReadOnly = !CHK_Nicknamed.Checked;

            Write_Entry(this, EventArgs.Empty);
        }
示例#5
0
        private async Task CatchWildPokemon(PK8 pk, CancellationToken token)
        {
            var check = await ReadPokemon(WildPokemonOffset, token).ConfigureAwait(false);

            if (encounterCount != 0 && encounterCount % catchCount == 0)
            {
                Log($"Ran out of Master Balls to catch {SpeciesName.GetSpeciesName(pk.Species, 2)}.");
                if (hub.Config.Encounter.InjectPokeBalls)
                {
                    Log("Restoring original pouch data.");
                    await Connection.WriteBytesAsync(pouchData, PokeBallOffset, token).ConfigureAwait(false);

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

            await Click(B, 1_000, token).ConfigureAwait(false);
            await Click(X, 1_000, token).ConfigureAwait(false);
            await Click(A, 3_000, token).ConfigureAwait(false); //Throw ball

            await Click(B, 1_000, token).ConfigureAwait(false);
            await Click(B, 1_000, token).ConfigureAwait(false); //Just in case we didn't

            await Click(X, 1_000, token).ConfigureAwait(false);
            await Click(A, 1_000, token).ConfigureAwait(false); //Attempt again to be sure

            while (!await IsOnOverworld(hub.Config, token).ConfigureAwait(false) && check.Species != 0)
            {
                await Click(B, 0_400, token).ConfigureAwait(false);
            }

            if (await IsOnOverworld(hub.Config, token).ConfigureAwait(false) && !await IsInBattle(token).ConfigureAwait(false))
            {
                Log($"{Ping}Caught {SpeciesName.GetSpeciesName(pk.Species, 2)} in a Master Ball! Resuming routine...");
            }
        }
示例#6
0
        public void ListPokemon()
        {
            var strings = GameInfo.GetStrings("ja");

            foreach (var monster in savedata.PartyData)
            {
                Console.WriteLine(string.Join("\t",
                                              ((LanguageID)monster.Language).ToString(),
                                              monster.CurrentLevel.ToString(),
                                              SpeciesName.GetSpeciesName(monster.Species, 1),
                                              monster.Nickname.ToString(),
                                              monster.OT_Name));

                var moves = "";
                foreach (var move in monster.Moves)
                {
                    moves += strings.movelist[move] + "\t";
                }
                Console.WriteLine(moves);
            }
        }
示例#7
0
        private Tuple <ulong, ulong> PerformSeedSearch()
        {
            Log("Searching for a matching seed... Search may take a while.");
            SeedSearchUtil.SpecificSeedSearch(RaidInfo, out long frames, out ulong seed, out ulong threeDay, out string ivSpread);
            if (ivSpread == string.Empty)
            {
                Log($"No results found within the specified search range.");
                return(new Tuple <ulong, ulong>(0, 0));
            }

            var species  = RaidInfo.Den.IsEvent ? RaidInfo.RaidDistributionEncounter.Species : RaidInfo.RaidEncounter.Species;
            var specName = SpeciesName.GetSpeciesNameGeneration((int)species, 2, 8);
            var form     = TradeExtensions.FormOutput((int)(RaidInfo.Den.IsEvent ? RaidInfo.RaidDistributionEncounter.Species : RaidInfo.RaidEncounter.Species), (int)(RaidInfo.Den.IsEvent ? RaidInfo.RaidDistributionEncounter.AltForm : RaidInfo.RaidEncounter.AltForm), out _);
            var results  = $"\n\nDesired species: {(uint)RaidInfo.Den.Stars + 1}★ - {specName}{form}\n" +
                           $"\n{ivSpread}\n" +
                           $"\nStarting seed: {RaidInfo.Den.Seed:X16}\n" +
                           $"Target frame seed: {seed:X16}\n" +
                           $"Three day roll: {threeDay:X16}\n" +
                           $"Skips to target frame: {frames:N0}\n";

            EchoUtil.Echo(results);
            return(new Tuple <ulong, ulong>(seed, threeDay));
        }
示例#8
0
文件: Text.cs 项目: 04sama/PKHeX
        private void B_ApplyTrash_Click(object sender, EventArgs e)
        {
            string species = SpeciesName.GetSpeciesNameGeneration(WinFormsUtil.GetIndex(CB_Species),
                WinFormsUtil.GetIndex(CB_Language), (int) NUD_Generation.Value);

            if (string.IsNullOrEmpty(species)) // no result
                species = CB_Species.Text;

            byte[] current = SetString(TB_Text.Text);
            byte[] data = SetString(species);
            if (data.Length <= current.Length)
            {
                WinFormsUtil.Alert("Trash byte layer is hidden by current text.",
                    $"Current Bytes: {current.Length}" + Environment.NewLine + $"Layer Bytes: {data.Length}");
                return;
            }
            if (data.Length > Bytes.Count)
            {
                WinFormsUtil.Alert("Trash byte layer is too long to apply.");
                return;
            }
            for (int i = current.Length; i < data.Length; i++)
                Bytes[i].Value = data[i];
        }
示例#9
0
 bool ValidateParameters()
 {
     return(SpeciesName.ToLower() != "new species");
 }
示例#10
0
 async Task <ObservableCollection <PokemonForm> > LoadFormsAsync(SpeciesName species, GameVersion version, int language)
 {
     return(await _pokemonService.LoadFormsAsync(species, version, language, _tokenSource.Token));
 }
示例#11
0
        private async Task Overworld(CancellationToken token, bool birds = false)
        {
            GameVersion version = await LGWhichGameVersion(token).ConfigureAwait(false);

            List <int[]> movementslist = ParseMovements();
            bool         firstrun      = movementslist.Count > 0;
            Stopwatch    stopwatch     = new Stopwatch();
            uint         prev          = 0;
            uint         newspawn;
            uint         catchcombo;
            uint         speciescombo;
            int          i              = 0;
            bool         freeze         = false;
            bool         searchforshiny = Hub.Config.LGPE_OverworldScan.OnlyShiny;
            bool         found;

            if (movementslist.Count > 0)
            {
                Log($"{Environment.NewLine}----------------------------------------{Environment.NewLine}" +
                    $"ATTENTION{Environment.NewLine}Any wild battles will broke the movement routine, resulting in the pg moving to unwanted areas!{Environment.NewLine}" +
                    $"----------------------------------------{Environment.NewLine}" +
                    $"ATTENTION{Environment.NewLine}Unexpected behaviour can occur if a Pokémon is detected while changing area. It is higlhy recommended to avoid that.{Environment.NewLine}" +
                    $"-----------------------------------------{Environment.NewLine}");
            }

            //Catch combo to increment spawn quality and shiny rate (Thanks to Lincoln-LM for the offsets)
            if ((int)Hub.Config.LGPE_OverworldScan.ChainSpecies > 0)
            {
                speciescombo = await LGReadSpeciesCombo(token).ConfigureAwait(false);

                if ((speciescombo != (uint)Hub.Config.LGPE_OverworldScan.ChainSpecies) && (Hub.Config.LGPE_OverworldScan.ChainSpecies != 0))
                {
                    Log($"Current catch combo being on {(speciescombo == 0 ? "None" : SpeciesName.GetSpeciesName((int)speciescombo, 2))}, changing to {Hub.Config.LGPE_OverworldScan.ChainSpecies}.");
                    await LGEditSpeciesCombo((uint)Hub.Config.LGPE_OverworldScan.ChainSpecies, token).ConfigureAwait(false);

                    speciescombo = await LGReadSpeciesCombo(token).ConfigureAwait(false);

                    Log($"Current catch combo being now on {(speciescombo == 0 ? "None" : SpeciesName.GetSpeciesName((int)speciescombo, 2))}.");
                }
            }

            if (Hub.Config.LGPE_OverworldScan.ChainCount > 0)
            {
                catchcombo = await LGReadComboCount(token).ConfigureAwait(false);

                if (catchcombo < (uint)Hub.Config.LGPE_OverworldScan.ChainCount)
                {
                    Log($"Current catch combo being {catchcombo}, incrementing to {Hub.Config.LGPE_OverworldScan.ChainCount}.");
                    await LGEditComboCount((uint)Hub.Config.LGPE_OverworldScan.ChainCount, token).ConfigureAwait(false);

                    catchcombo = await LGReadComboCount(token).ConfigureAwait(false);

                    Log($"Current catch combo being now {catchcombo}.");
                }
            }

            //Main Loop
            while (!token.IsCancellationRequested)
            {
                if (searchforshiny)
                {
                    await LGZaksabeast(token, version).ConfigureAwait(false);
                }

                //Main Loop
                while (!freeze && !token.IsCancellationRequested)
                {
                    if (await LGCountMilliseconds(Hub.Config, token).ConfigureAwait(false) > 0 || !searchforshiny)
                    {
                        //Force the Fortune Teller Nature value, value is reset at the end of the day
                        if (Hub.Config.LGPE_OverworldScan.SetFortuneTellerNature != Nature.Random && !await LGIsNatureTellerEnabled(token).ConfigureAwait(false))
                        {
                            await LGEnableNatureTeller(token).ConfigureAwait(false);
                            await LGEditWildNature(Hub.Config.LGPE_OverworldScan.SetFortuneTellerNature, token).ConfigureAwait(false);

                            Log($"Fortune Teller enabled, Nature set to {await LGReadWildNature(token).ConfigureAwait(false)}.");
                        }

                        //PG Movements. The routine need to continue and check the overworld spawns, cannot be stuck at changing stick position.
                        if (movementslist.Count > 0)
                        {
                            if (stopwatch.ElapsedMilliseconds >= movementslist.ElementAt(i)[2] || firstrun)
                            {
                                if (firstrun)
                                {
                                    firstrun = false;
                                }
                                await ResetStick(token).ConfigureAwait(false);
                                await SetStick(RIGHT, (short)(movementslist.ElementAt(i)[0]), (short)(movementslist.ElementAt(i)[1]), 0_001, token).ConfigureAwait(false);

                                i++;
                                if (i == movementslist.Count)
                                {
                                    i = 0;
                                }
                                stopwatch.Restart();
                            }
                        }

                        //Check is inside an unwanted encounter
                        if (await LGIsInCatchScreen(token).ConfigureAwait(false))
                        {
                            await EscapeWildEncounter(token).ConfigureAwait(false);
                        }

                        //Check new spawns
                        newspawn = BitConverter.ToUInt16(await Connection.ReadBytesAsync(LastSpawn, 2, token).ConfigureAwait(false), 0);
                        if (newspawn != prev)
                        {
                            if (newspawn != 0)
                            {
                                encounterCount++;
                                if (IsPKLegendary((int)newspawn))
                                {
                                    Counts.AddLGPELegendaryScans();
                                }
                                else
                                {
                                    Counts.AddLGPEOverworldScans();
                                }
                                Log($"New spawn ({encounterCount}): {newspawn} {SpeciesName.GetSpeciesName((int)newspawn, 4)}");
                            }
                            prev = newspawn;
                            if (!searchforshiny &&
                                ((!birds && (int)newspawn == (int)Hub.Config.LGPE_OverworldScan.StopOnSpecies) ||
                                 (!birds && (int)Hub.Config.LGPE_OverworldScan.StopOnSpecies == 0) ||
                                 (birds && ((int)newspawn == 144 || (int)newspawn == 145 || (int)newspawn == 146))))
                            {
                                await Click(X, 1_000, token).ConfigureAwait(false);
                                await Click(HOME, 1_000, token).ConfigureAwait(false);

                                if (!String.IsNullOrEmpty(Hub.Config.Discord.UserTag))
                                {
                                    Log($"<@{Hub.Config.Discord.UserTag}> stop conditions met, restart the bot(s) to search again.");
                                }
                                else
                                {
                                    Log("Stop conditions met, restart the bot(s) to search again.");
                                }
                                return;
                            }
                        }
                    }
                    else if (searchforshiny)
                    {
                        freeze = true;
                    }
                }

                await LGUnfreeze(token, version).ConfigureAwait(false);

                freeze   = false;
                newspawn = BitConverter.ToUInt16(await Connection.ReadBytesAsync(LastSpawn, 2, token).ConfigureAwait(false), 0);

                //Stop Conditions
                if (birds && ((int)newspawn == 144 || (int)newspawn == 145 || (int)newspawn == 146) && !token.IsCancellationRequested)
                {
                    found = true;
                }
                else if ((!birds && (int)Hub.Config.LGPE_OverworldScan.StopOnSpecies > 0 && (int)newspawn == (int)Hub.Config.LGPE_OverworldScan.StopOnSpecies) ||
                         (!birds && (int)Hub.Config.LGPE_OverworldScan.StopOnSpecies == 0))
                {
                    found = true;
                }
                else
                {
                    found = false;
                }

                encounterCount++;
                if (IsPKLegendary((int)newspawn))
                {
                    Counts.AddLGPELegendaryScans();
                }
                else
                {
                    Counts.AddLGPEOverworldScans();
                }

                if (!found && !token.IsCancellationRequested)
                {
                    Log($"New spawn ({encounterCount}): {newspawn} Shiny {SpeciesName.GetSpeciesName((int)newspawn, 4)}");
                }
                else if (found && !token.IsCancellationRequested)
                {
                    await ResetStick(token).ConfigureAwait(false);

                    if (!String.IsNullOrEmpty(Hub.Config.Discord.UserTag))
                    {
                        Log($"<@{Hub.Config.Discord.UserTag}> Shiny Target {SpeciesName.GetSpeciesName((int)newspawn, 4)} found!");
                    }
                    else
                    {
                        Log($"Shiny Target {SpeciesName.GetSpeciesName((int)newspawn, 4)} found!");
                    }
                    await Click(X, 1_000, token).ConfigureAwait(false);
                    await Click(HOME, 1_000, token).ConfigureAwait(false);

                    return;
                }
            }
            await ResetStick(token).ConfigureAwait(false);

            if (searchforshiny)
            {
                await LGUnfreeze(token, version).ConfigureAwait(false);
            }
        }
        public static string SetAnalysis(this IBattleTemplate set, ITrainerInfo sav, PKM blank)
        {
            if (blank.Version == 0)
            {
                blank.Version = sav.Game;
            }
            var species_name = SpeciesName.GetSpeciesNameGeneration(set.Species, (int)LanguageID.English, sav.Generation);
            var analysis     = set.Form == 0 ? string.Format(SPECIES_UNAVAILABLE, species_name)
                                     : string.Format(SPECIES_UNAVAILABLE_FORM, species_name, set.FormName);

            // Species checks
            var gv = (GameVersion)sav.Game;

            if (!gv.ExistsInGame(set.Species, set.Form))
            {
                return(analysis); // Species does not exist in the game
            }
            // Species exists -- check if it has at least one move.
            // If it has no moves and it didn't generate, that makes the mon still illegal in game (moves are set to legal ones)
            var moves = set.Moves.Where(z => z != 0).ToArray();
            var count = set.Moves.Count(z => z != 0);

            // Reusable data
            var batchedit = false;
            IReadOnlyList <StringInstruction>?filters = null;

            if (set is RegenTemplate r)
            {
                filters   = r.Regen.Batch.Filters;
                batchedit = APILegality.AllowBatchCommands && r.Regen.HasBatchSettings;
            }
            var destVer = (GameVersion)sav.Game;

            if (destVer <= 0 && sav is SaveFile s)
            {
                destVer = s.Version;
            }
            var gamelist = APILegality.FilteredGameList(blank, destVer, batchedit ? filters : null);

            // Move checks
            List <IEnumerable <int> > move_combinations = new();

            for (int i = count; i >= 1; i--)
            {
                move_combinations.AddRange(GetKCombs(moves, i));
            }

            int[] original_moves = new int[4];
            set.Moves.CopyTo(original_moves, 0);
            int[] successful_combination = GetValidMoves(set, sav, move_combinations, blank, gamelist);
            if (!new HashSet <int>(original_moves.Where(z => z != 0)).SetEquals(successful_combination))
            {
                var invalid_moves = string.Join(", ", original_moves.Where(z => !successful_combination.Contains(z) && z != 0).Select(z => $"{(Move)z}"));
                return(successful_combination.Length > 0 ? string.Format(INVALID_MOVES, species_name, invalid_moves) : ALL_MOVES_INVALID);
            }

            // All moves possible, get encounters
            blank.ApplySetDetails(set);
            blank.SetMoves(original_moves);
            blank.SetRecordFlags(Array.Empty <int>());

            var encounters   = EncounterMovesetGenerator.GenerateEncounters(pk: blank, moves: original_moves, gamelist).ToList();
            var initialcount = encounters.Count;

            if (set is RegenTemplate rt && rt.Regen.EncounterFilters is { } x)
            {
                encounters.RemoveAll(enc => !BatchEditing.IsFilterMatch(x, enc));
            }

            // No available encounters
            if (encounters.Count == 0)
            {
                return(string.Format(EXHAUSTED_ENCOUNTERS, initialcount, initialcount));
            }

            // Level checks, check if level is impossible to achieve
            if (encounters.All(z => !APILegality.IsRequestedLevelValid(set, z)))
            {
                return(string.Format(LEVEL_INVALID, species_name, encounters.Min(z => z.LevelMin)));
            }
            encounters.RemoveAll(enc => !APILegality.IsRequestedLevelValid(set, enc));

            // Shiny checks, check if shiny is impossible to achieve
            Shiny shinytype = set.Shiny ? Shiny.Always : Shiny.Never;

            if (set is RegenTemplate ret && ret.Regen.HasExtraSettings)
            {
                shinytype = ret.Regen.Extra.ShinyType;
            }
            if (encounters.All(z => !APILegality.IsRequestedShinyValid(set, z)))
            {
                return(string.Format(SHINY_INVALID, shinytype));
            }
            encounters.RemoveAll(enc => !APILegality.IsRequestedShinyValid(set, enc));

            // Alpha checks
            if (encounters.All(z => !APILegality.IsRequestedAlphaValid(set, z)))
            {
                return(ALPHA_INVALID);
            }
            encounters.RemoveAll(enc => !APILegality.IsRequestedAlphaValid(set, enc));

            // Ability checks
            var abilityreq = APILegality.GetRequestedAbility(blank, set);

            if (abilityreq == AbilityRequest.NotHidden && encounters.All(z => z is EncounterStatic {
                Ability: AbilityPermission.OnlyHidden
            }))
示例#13
0
        /// <summary>
        /// Control the Character according to player input
        /// </summary>
        public void ControlLocalPlayer(float deltaTime, Camera cam, bool moveCam = true)
        {
            if (!DisableControls)
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    keys[i].SetState();
                }
            }
            else
            {
                foreach (Key key in keys)
                {
                    if (key == null)
                    {
                        continue;
                    }
                    key.Reset();
                }
            }

            if (moveCam)
            {
                if (needsAir && !Shielded &&
                    pressureProtection < 80.0f &&
                    (AnimController.CurrentHull == null || AnimController.CurrentHull.LethalPressure > 50.0f))
                {
                    float pressure = AnimController.CurrentHull == null ? 100.0f : AnimController.CurrentHull.LethalPressure;

                    cam.Zoom = MathHelper.Lerp(cam.Zoom,
                                               (pressure / 50.0f) * Rand.Range(1.0f, 1.05f),
                                               (pressure - 50.0f) / 50.0f);
                }

                if (IsHumanoid)
                {
                    if (!(SpeciesName.ToLowerInvariant() == "human") && GameMain.NilMod.UseCreatureZoomBoost)
                    {
                        cam.ZoomModifier = -0.10f;
                        cam.OffsetAmount = MathHelper.Lerp(cam.OffsetAmount, MathHelper.Clamp((300.0f * GameMain.NilMod.CreatureZoomMultiplier), 300f, 500f), deltaTime);
                    }
                    else
                    {
                        cam.OffsetAmount = MathHelper.Lerp(cam.OffsetAmount, 250.0f, deltaTime);
                    }
                }
                else
                {
                    float tempmass = Mass;
                    if (GameMain.NilMod.UseCreatureZoomBoost)
                    {
                        //increased visibility range when controlling large a non-humanoid
                        if ((tempmass) >= 1000)
                        {
                            tempmass         = 1200f;
                            cam.ZoomModifier = -1f;
                        }
                        else if ((tempmass) >= 800)
                        {
                            tempmass         = 1000f;
                            cam.ZoomModifier = -1f;
                        }
                        else if ((tempmass) >= 600)
                        {
                            tempmass         = 800f;
                            cam.ZoomModifier = -1f;
                        }
                        else if ((tempmass) >= 400)
                        {
                            tempmass         = 600f;
                            cam.ZoomModifier = -0.5f;
                        }
                        else if ((tempmass) >= 300)
                        {
                            tempmass         = 500f;
                            cam.ZoomModifier = -0.4f;
                        }
                        else if ((tempmass) >= 200)
                        {
                            tempmass         = 450f;
                            cam.ZoomModifier = -0.3f;
                        }
                        else if ((tempmass) >= 150)
                        {
                            tempmass         = 400f;
                            cam.ZoomModifier = -0.3f;
                        }
                        else if ((tempmass) >= 100)
                        {
                            tempmass         = 350f;
                            cam.ZoomModifier = -0.3f;
                        }
                        else if ((tempmass) >= 0)
                        {
                            tempmass         = 300f;
                            cam.ZoomModifier = -0.3f;
                        }
                    }
                    cam.OffsetAmount = MathHelper.Lerp(cam.OffsetAmount, MathHelper.Clamp((tempmass * GameMain.NilMod.CreatureZoomMultiplier), 250.0f, 1600.0f), deltaTime);
                }
            }

            cursorPosition = cam.ScreenToWorld(PlayerInput.MousePosition);
            if (AnimController.CurrentHull != null && AnimController.CurrentHull.Submarine != null)
            {
                cursorPosition -= AnimController.CurrentHull.Submarine.Position;
            }

            Vector2 mouseSimPos = ConvertUnits.ToSimUnits(cursorPosition);

            if (moveCam)
            {
                if (GUI.PauseMenuOpen || IsUnconscious ||
                    (GameMain.GameSession?.CrewManager?.CrewCommander != null && GameMain.GameSession.CrewManager.CrewCommander.IsOpen))
                {
                    if (deltaTime > 0.0f)
                    {
                        cam.OffsetAmount = 0.0f;
                    }
                }
                else if (DebugConsole.IsOpen && (Lights.LightManager.ViewTarget == this && Vector2.DistanceSquared(AnimController.Limbs[0].SimPosition, mouseSimPos) > 1.0f))
                {
                    Body      body      = Submarine.CheckVisibility(AnimController.Limbs[0].SimPosition, mouseSimPos);
                    Structure structure = body == null ? null : body.UserData as Structure;

                    float sightDist = Submarine.LastPickedFraction;
                    if (body?.UserData is Structure && !((Structure)body.UserData).CastShadow)
                    {
                        sightDist = 1.0f;
                    }
                    cam.ZoomModifier = -0.4f;
                    //cam.OffsetAmount = MathHelper.Lerp(cam.OffsetAmount, Math.Max(250.0f, sightDist * 500.0f), 0.05f);
                    if (deltaTime > 0.0f)
                    {
                        cam.OffsetAmount = 300.0f;
                    }
                }
                else if (Lights.LightManager.ViewTarget == this && Vector2.DistanceSquared(AnimController.Limbs[0].SimPosition, mouseSimPos) > 1.0f)
                {
                    Body      body      = Submarine.CheckVisibility(AnimController.Limbs[0].SimPosition, mouseSimPos);
                    Structure structure = body == null ? null : body.UserData as Structure;

                    float sightDist = Submarine.LastPickedFraction;
                    if (body?.UserData is Structure && !((Structure)body.UserData).CastShadow)
                    {
                        sightDist = 1.0f;
                    }
                    cam.OffsetAmount = MathHelper.Lerp(cam.OffsetAmount, Math.Max(250.0f, sightDist * 500.0f), 0.05f);
                }
            }

            DoInteractionUpdate(deltaTime, mouseSimPos);

            DisableControls = false;
        }
        private void WriteStatus(NetBuffer msg)
        {
            if (GameMain.Client != null)
            {
                DebugConsole.ThrowError("Client attempted to write character status to a networked message");
                return;
            }

            msg.Write(isDead);
            if (isDead)
            {
                msg.Write((byte)causeOfDeath);

                if (AnimController?.LimbJoints == null)
                {
                    //0 limbs severed
                    msg.Write((byte)0);
                }
                else
                {
                    List <int> severedJointIndices = new List <int>();
                    for (int i = 0; i < AnimController.LimbJoints.Length; i++)
                    {
                        if (AnimController.LimbJoints[i] != null && AnimController.LimbJoints[i].IsSevered)
                        {
                            severedJointIndices.Add(i);
                        }
                    }
                    msg.Write((byte)severedJointIndices.Count);
                    foreach (int jointIndex in severedJointIndices)
                    {
                        msg.Write((byte)jointIndex);
                    }
                }
            }
            else
            {
                if (GameMain.NilMod.HideConciousCreatureHealth && (!(AIController is HumanAIController || SpeciesName.ToLowerInvariant() == "human")) && Stun <= 2f)
                {
                    msg.WriteRangedSingle(100f, 0f, 100f, 8);
                }
                else
                {
                    msg.WriteRangedSingle(health, minHealth, maxHealth, 8);
                }

                msg.Write(oxygen < 100.0f);
                if (oxygen < 100.0f)
                {
                    msg.WriteRangedSingle(oxygen, -100.0f, 100.0f, 8);
                }

                msg.Write(bleeding > 0.0f);
                if (bleeding > 0.0f)
                {
                    msg.WriteRangedSingle(Math.Max(0.35f, bleeding), 0.0f, 5.0f, 8);
                }

                msg.Write(Stun > 0.0f);
                if (Stun > 0.0f)
                {
                    msg.WriteRangedSingle(MathHelper.Clamp(Stun, 0.0f, MaxStun), 0.0f, MaxStun, 8);
                }

                msg.Write(IsRagdolled);

                msg.Write(HuskInfectionState > 0.0f);
            }
        }
示例#15
0
        public async Task LanRollAsync([Summary("User Requested IGN")][Remainder] string ign = "")
        {
            if (ign.Length > 12)
            {
                await ReplyAsync("IGN cannot exceed 12 characters.").ConfigureAwait(false);

                return;
            }

            var code = Info.GetRandomTradeCode();

            int[] existantMon =
            { 1,         2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  25,  26,  27,  28,  29, 30, 31, 32,
              33,   34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,  45,  50,  51,  52,  53, 54,
              55,   58,  59,  60,  61,  62,  63,  64,  65,  66,  67,  68,  72,  73,  77,  78,  79, 80,
              81,   82,  83,  90,  91,  92,  93,  94,  95,  98,  99, 102, 103, 104, 105, 106, 107,
              108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
              123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137,
              138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 163,
              164, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 182, 183, 184, 185,
              186, 194, 195, 196, 197, 199, 202, 206, 208, 211, 212, 213, 214, 215, 220,
              221, 222, 223, 224, 225, 226, 227, 230, 233, 236, 237, 238, 239, 240, 241,
              242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256,
              257, 258, 259, 260, 263, 264, 270, 271, 272, 273, 274, 275, 278, 279, 280,
              281, 282, 290, 291, 292, 293, 294, 295, 298, 302, 303, 304, 305, 306, 309,
              310, 315, 318, 319, 320, 321, 324, 328, 329, 330, 333, 334, 337, 338, 339,
              340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 355, 356, 359, 360,
              361, 362, 363, 364, 365, 369, 371, 372, 373, 374, 375, 376, 377, 378, 379,
              380, 381, 382, 383, 384, 385, 403, 404, 405, 406, 407, 415, 416, 420, 421,
              422, 423, 425, 426, 427, 428, 434, 436, 437, 438, 439, 440, 442, 443, 444,
              445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 458, 459, 460, 461, 462,
              463, 464, 465, 466, 467, 468, 470, 471, 473, 474, 475, 477, 478, 479, 480,
              481, 482, 483, 484, 485, 486, 487, 488, 494, 506, 507, 508, 509, 510, 517,
              518, 519, 520, 521, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534,
              535, 536, 537, 538, 539, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552,
              553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567,
              568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 582, 583, 584,
              587, 588, 589, 590, 591, 592, 593, 595, 596, 597, 598, 599, 600, 601, 605,
              606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620,
              621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635,
              636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 649, 659, 660,
              661, 662, 663, 674, 675, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686,
              687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701,
              702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716,
              717, 718, 719, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 736, 737,
              738, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755,
              756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770,
              771, 772, 773, 776, 777, 778, 780, 781, 782, 783, 784, 785, 786, 787, 788,
              789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803,
              804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818,
              819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833,
              834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848,
              849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863,
              864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878,
              879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893,
              894, 895, 896, 897, 898 };

            var rng = new System.Random();
            var set = new ShowdownSet($"Egg({SpeciesName.GetSpeciesName(rng.Next(new Zukan8Index(Zukan8Type.None, 1).Index, GameUtil.GetMaxSpeciesID(GameVersion.SWSH)), 2)})");

            while (!existantMon.ToList().Contains(set.Species))
            {
                set = new ShowdownSet($"Egg({SpeciesName.GetSpeciesName(rng.Next(new Zukan8Index(Zukan8Type.None, 1).Index, GameUtil.GetMaxSpeciesID(GameVersion.SWSH)), 2)})");
            }

            var template = AutoLegalityWrapper.GetTemplate(set);
            var sav      = AutoLegalityWrapper.GetTrainerInfo(gen);
            var pkm      = (PK8)sav.GetLegal(template, out _);;

            LanRollTrade(pkm);

            pkm.ClearRecordFlags();
            pkm.GetSuggestedRelearnMoves();

            pkm.ResetPartyStats();
            var sig = Context.User.GetFavor();
            await Context.AddToQueueAsync(code, Context.User.Username, sig, pkm, PokeRoutineType.LanRoll, PokeTradeType.LanRoll, Context.User, ign).ConfigureAwait(false);
        }
        private async Task Overworld(CancellationToken token, bool birds = false)
        {
            GameVersion version = await LGWhichGameVersion(token).ConfigureAwait(false);

            List <int[]> movementslist = ParseMovements();
            bool         firstrun      = movementslist.Count > 0;
            Stopwatch    stopwatch     = new Stopwatch();
            uint         prev          = 0;
            uint         newspawn;
            uint         catchcombo;
            uint         speciescombo;
            int          i              = 0;
            int          j              = 0;
            bool         freeze         = false;
            bool         searchforshiny = Hub.Config.LGPE_OverworldScan.OnlyShiny;
            bool         found          = false;

            if (movementslist.Count > 0)
            {
                Log($"ATTENTION!{Environment.NewLine}Any wild encounter will broke the movement routine, resulting in the pg moving to unwanted places!{Environment.NewLine}" +
                    $"----------------------------------------{Environment.NewLine}" +
                    $"ATTENTION!\nUnexpected behaviour can occur if a shiny is detected while changing area. It his higlhy recommended to avoid that.{Environment.NewLine}" +
                    $"-----------------------------------------{Environment.NewLine}");
            }

            //Catch combo to increment spawn quality and shiny rate (Thanks to Lincoln-LM for the offsets)
            if ((int)Hub.Config.LGPE_OverworldScan.ChainSpecies > 0)
            {
                speciescombo = BitConverter.ToUInt16(await SwitchConnection.ReadBytesAbsoluteAsync(await ParsePointer(SpeciesComboPointer, token).ConfigureAwait(false), 2, token).ConfigureAwait(false), 0);
                if ((speciescombo != (uint)Hub.Config.LGPE_OverworldScan.ChainSpecies) && (Hub.Config.LGPE_OverworldScan.ChainSpecies != 0))
                {
                    Log($"Current catch combo being on {(speciescombo == 0 ? "None" : SpeciesName.GetSpeciesName((int)speciescombo, 2))}, changing to {Hub.Config.LGPE_OverworldScan.ChainSpecies}.");
                    await SwitchConnection.WriteBytesAbsoluteAsync(BitConverter.GetBytes((uint)Hub.Config.LGPE_OverworldScan.ChainSpecies), await ParsePointer(SpeciesComboPointer, token).ConfigureAwait(false), token).ConfigureAwait(false);

                    speciescombo = BitConverter.ToUInt16(await SwitchConnection.ReadBytesAbsoluteAsync(await ParsePointer(SpeciesComboPointer, token).ConfigureAwait(false), 2, token).ConfigureAwait(false), 0);
                    Log($"Current catch combo being now on {(speciescombo == 0 ? "None" : SpeciesName.GetSpeciesName((int)speciescombo, 2))}.");
                }
            }
            if (Hub.Config.LGPE_OverworldScan.ChainCount > 0)
            {
                catchcombo = BitConverter.ToUInt16(await SwitchConnection.ReadBytesAbsoluteAsync(await ParsePointer(CatchComboPointer, token).ConfigureAwait(false), 2, token).ConfigureAwait(false), 0);
                if (catchcombo < (uint)Hub.Config.LGPE_OverworldScan.ChainCount)
                {
                    Log($"Current catch combo being {catchcombo}, incrementing to {Hub.Config.LGPE_OverworldScan.ChainCount}.");
                    await SwitchConnection.WriteBytesAbsoluteAsync(BitConverter.GetBytes((uint)Hub.Config.LGPE_OverworldScan.ChainCount), await ParsePointer(CatchComboPointer, token).ConfigureAwait(false), token).ConfigureAwait(false);

                    catchcombo = BitConverter.ToUInt16(await SwitchConnection.ReadBytesAbsoluteAsync(await ParsePointer(CatchComboPointer, token).ConfigureAwait(false), 2, token).ConfigureAwait(false), 0);
                    Log($"Current catch combo being now {catchcombo}.");
                }
            }

            while (!token.IsCancellationRequested)
            {
                if (searchforshiny)
                {
                    await LGZaksabeast(token, version).ConfigureAwait(false);
                }
                while (freeze == false && !token.IsCancellationRequested && !found)
                {
                    if (await LGCountMilliseconds(Hub.Config, token).ConfigureAwait(false) > 0 || !searchforshiny)
                    {
                        //The routine need to continue and check the overworld spawns, cannot be stuck at changing stick position.
                        if (movementslist.Count > 0)
                        {
                            if (stopwatch.ElapsedMilliseconds >= movementslist.ElementAt(j)[2] || firstrun)
                            {
                                if (firstrun)
                                {
                                    firstrun = false;
                                }
                                //Log($"Moved for {stopwatch.ElapsedMilliseconds}ms.");
                                await ResetStick(token).ConfigureAwait(false);
                                await SetStick(RIGHT, (short)(movementslist.ElementAt(j)[0]), (short)(movementslist.ElementAt(j)[1]), 0_001, token).ConfigureAwait(false);

                                j++;
                                if (j == movementslist.Count)
                                {
                                    j = 0;
                                }
                                stopwatch.Restart();
                            }
                        }

                        //Check is inside an unwanted encounter
                        if (await LGIsInCatchScreen(token).ConfigureAwait(false))
                        {
                            await ResetStick(token).ConfigureAwait(false);

                            Log($"Unwanted encounter detected!");
                            int y = 0;
                            while (await LGIsInCatchScreen(token).ConfigureAwait(false) && !token.IsCancellationRequested)
                            {
                                y++;
                                await Task.Delay(8_000, token).ConfigureAwait(false);

                                if (y > 2)
                                {
                                    await Click(B, 1_200, token).ConfigureAwait(false);
                                }
                                await Click(B, 1_200, token).ConfigureAwait(false);
                                await Click(A, 1_000, token).ConfigureAwait(false);

                                await Task.Delay(6_500, token).ConfigureAwait(false);
                            }
                            Log($"Exited wild encounter.");
                        }

                        //Check new spawns
                        newspawn = BitConverter.ToUInt16(await Connection.ReadBytesAsync(LastSpawn1, 2, token).ConfigureAwait(false), 0);
                        if (newspawn != prev)
                        {
                            if (newspawn != 0)
                            {
                                i++;
                                if (IsPKLegendary((int)newspawn))
                                {
                                    Counts.AddCompletedLegends();
                                }
                                else
                                {
                                    Counts.AddCompletedEncounters();
                                }
                                Log($"New spawn ({i}): {newspawn} {SpeciesName.GetSpeciesName((int)newspawn, 4)}");
                            }
                            prev = newspawn;
                            if (!searchforshiny &&
                                ((!birds && (int)newspawn == (int)Hub.Config.LGPE_OverworldScan.StopOnSpecies) ||
                                 (!birds && (int)Hub.Config.LGPE_OverworldScan.StopOnSpecies == 0) ||
                                 (birds && ((int)newspawn == 144 || (int)newspawn == 145 || (int)newspawn == 146))))
                            {
                                await Click(X, 1_000, token).ConfigureAwait(false);
                                await Click(HOME, 1_000, token).ConfigureAwait(false);

                                if (!String.IsNullOrEmpty(Hub.Config.Discord.UserTag))
                                {
                                    Log($"<@{Hub.Config.Discord.UserTag}> stop conditions met, restart the bot(s) to search again.");
                                }
                                else
                                {
                                    Log("Stop conditions met, restart the bot(s) to search again.");
                                }
                                return;
                            }
                        }
                    }
                    else if (searchforshiny)
                    {
                        freeze = true;
                    }
                }

                if (searchforshiny && !token.IsCancellationRequested)
                {
                    Log("A Shiny has been detected.");
                }

                //Unfreeze to restart the routine, or log the Shiny species.
                await LGUnfreeze(token, version).ConfigureAwait(false);

                newspawn = BitConverter.ToUInt16(await Connection.ReadBytesAsync(LastSpawn1, 2, token).ConfigureAwait(false), 0);

                //Stop Conditions logic
                if (birds && ((int)newspawn == 144 || (int)newspawn == 145 || (int)newspawn == 146) && !token.IsCancellationRequested)
                {
                    found = true;
                }
                else if ((!birds && (int)Hub.Config.LGPE_OverworldScan.StopOnSpecies > 0 && (int)newspawn == (int)Hub.Config.LGPE_OverworldScan.StopOnSpecies) ||
                         (!birds && (int)Hub.Config.LGPE_OverworldScan.StopOnSpecies == 0))
                {
                    found = true;
                }
                else
                {
                    found = false;
                }

                if (!found && !token.IsCancellationRequested)
                {
                    freeze = false;
                    Log($"Shiny {SpeciesName.GetSpeciesName((int)newspawn, 4)} is not the target, the routine will continue.");
                }
                else if (!token.IsCancellationRequested)
                {
                    await ResetStick(token).ConfigureAwait(false);

                    if (!String.IsNullOrEmpty(Hub.Config.Discord.UserTag))
                    {
                        Log($"<@{Hub.Config.Discord.UserTag}> Shiny {SpeciesName.GetSpeciesName((int)newspawn, 4)} found!");
                    }
                    else
                    {
                        Log($"Shiny {SpeciesName.GetSpeciesName((int)newspawn, 4)} found!");
                    }
                    await Click(X, 1_000, token).ConfigureAwait(false);
                    await Click(HOME, 1_000, token).ConfigureAwait(false);

                    return;
                }
            }
            await ResetStick(token).ConfigureAwait(false);

            if (searchforshiny)
            {
                await LGUnfreeze(token, version).ConfigureAwait(false);
            }
        }
示例#17
0
        private static bool CommonErrorHandling2(PKM pk)
        {
            var report = GetReport(pk);

            // f*****g M2
            if (GameVersion.FRLG.Contains(pk.Version) && UsesEventBasedMethod(pk.Species, pk.Moves, PIDType.Method_2))
            {
                M2EventFix(pk, pk.IsShiny);
                report = GetReport(pk);
            }

            if (UsesEventBasedMethod(pk.Species, pk.Moves, PIDType.BACD_R) && pk.Version == (int)GameVersion.R)
            {
                BACD_REventFix(pk, pk.IsShiny);
                report = GetReport(pk);
            }

            if (report.Contains(LNickMatchLanguageFail))
            {
                pk.Nickname = SpeciesName.GetSpeciesNameGeneration(pk.Species, pk.Language, pk.Format); // failsafe to reset nick
                report      = GetReport(pk);
            }
            if (report.Contains(LStatIncorrectCP))
            {
                ((PB7)pk).ResetCP();
                report = GetReport(pk);
            }
            if (report.Contains(LAbilityMismatch)) //V223 = Ability mismatch for encounter.
            {
                pk.RefreshAbility((uint)pk.AbilityNumber < 6 ? pk.AbilityNumber >> 1 : 0);
                report = GetReport(pk);
                if (report.Contains(LAbilityMismatch)) //V223 = Ability mismatch for encounter.
                {
                    AlternateAbilityRefresh(pk);
                }
                report = GetReport(pk);
            }
            if (report.Contains(LTransferEggLocationTransporter)) //V61 = Invalid Met Location, expected Transporter.
            {
                pk.Met_Location = 30001;
                report          = GetReport(pk);
            }
            if (report.Contains(LBallEncMismatch)) //V118 = Can't have ball for encounter type.
            {
                if (pk.B2W2)
                {
                    pk.Ball = 25; //Dream Ball
                    report  = GetReport(pk);
                }
                else
                {
                    pk.Ball = 0;
                    report  = GetReport(pk);
                }
            }
            if (report.Contains(LEncUnreleasedEMewJP)) //V353 = Non japanese Mew from Faraway Island. Unreleased event.
            {
                bool shiny = pk.IsShiny;
                pk.Language         = 1;
                pk.FatefulEncounter = true;
                pk.Nickname         = SpeciesName.GetSpeciesNameGeneration(pk.Species, pk.Language, 3);
                pk.PID = PKX.GetRandomPID(pk.Species, pk.Gender, pk.Version, pk.Nature, pk.Format, (uint)(pk.AbilityNumber * 0x10001));
                if (shiny)
                {
                    pk.SetShinySID();
                }
                report = GetReport(pk);
            }
            if (report.Contains(LPIDEqualsEC)) //V208 = Encryption Constant matches PID.
            {
                pk.SetRandomEC();
                report = GetReport(pk);
            }
            if (report.Contains(LTransferPIDECEquals)) //V216 = PID should be equal to EC!
            {
                pk.EncryptionConstant = pk.PID;
                report = GetReport(pk);
            }
            if (report.Contains(LTransferPIDECBitFlip)) //V215 = PID should be equal to EC [with top bit flipped]!
            {
                pk.PID = PKX.GetRandomPID(pk.Species, pk.Gender, pk.Version, pk.Nature, pk.Format, (uint)(pk.AbilityNumber * 0x10001));
                if (pk.IsShiny)
                {
                    pk.SetShiny();
                }
                report = GetReport(pk);
            }
            if (report.Contains(LPIDGenderMismatch)) //V251 = PID-Gender mismatch.
            {
                pk.Gender = pk.Gender == 0 ? 1 : 0;
                report    = GetReport(pk);
            }
            if (report.Contains(LG3OTGender) || report.Contains(LG1OTGender)) //V407 = OT from Colosseum/XD cannot be female. V408 = Female OT from Generation 1 / 2 is invalid.
            {
                pk.OT_Gender = 0;
                report       = GetReport(pk);
            }
            if (report.Contains(LLevelMetBelow)) //V85 = Current level is below met level.
            {
                pk.CurrentLevel = 100;
                report          = GetReport(pk);
            }
            if (report.Contains(string.Format(LRibbonFMissing_0, "National"))) //V600 = Missing Ribbons: {0} (National in this case)
            {
                if (pk is IRibbonSetEvent3 e3)
                {
                    e3.RibbonNational = true;
                }
                report = GetReport(pk);
            }
            if (report.Contains(string.Format(LRibbonFInvalid_0, "National"))) //V601 = Invalid Ribbons: {0} (National in this case)
            {
                if (pk is IRibbonSetEvent3 e3)
                {
                    e3.RibbonNational = false;
                }
                report = GetReport(pk);
            }
            if (report.Contains(LOTLong)) //V38 = OT Name too long.
            {
                pk.OT_Name = "ARCH";
                report     = GetReport(pk);
            }
            if (report.Contains(LG1CharOT)) //V421 = OT from Generation 1/2 uses unavailable characters.
            {
                pk.OT_Name = "ARCH";
                report     = GetReport(pk);
            }
            if (report.Contains(LGeoNoCountryHT))
            {
                var g = (IGeoTrack)pk;
                g.Geo1_Country = 1;
                report         = GetReport(pk);
            }
            if (report.Contains(LMemoryMissingHT)) //V150 = Memory: Handling Trainer Memory missing.
            {
                pk.HT_Memory     = 3;
                pk.HT_TextVar    = 9;
                pk.HT_Intensity  = 1;
                pk.HT_Feeling    = Util.Rand.Next(0, 10); // 0-9
                pk.HT_Friendship = pk.OT_Friendship;
                report           = GetReport(pk);
            }
            if (report.Contains(LMemoryMissingOT)) //V152 = Memory: Original Trainer Memory missing.
            {
                pk.OT_Memory    = 3;
                pk.OT_TextVar   = 9;
                pk.OT_Intensity = 1;
                pk.OT_Feeling   = Util.Rand.Next(0, 10); // 0-9
                report          = GetReport(pk);
            }
            if (report.Contains(string.Format(LMemoryFeelInvalid, "OT")) || report.Contains(string.Format(LMemoryFeelInvalid, "HT"))) //V255 = {0} Memory: Invalid Feeling (0 = OT/HT)
            {
                pk.HT_Memory     = 3;
                pk.HT_TextVar    = 9;
                pk.HT_Intensity  = 1;
                pk.HT_Feeling    = Memories.GetRandomFeeling(pk.HT_Memory);
                pk.HT_Friendship = pk.OT_Friendship;
                pk.OT_Memory     = 3;
                pk.OT_TextVar    = 9;
                pk.OT_Intensity  = 1;
                pk.OT_Feeling    = Memories.GetRandomFeeling(pk.OT_Memory);
                report           = GetReport(pk);
            }
            if (report.Contains(LMemoryIndexIDOT0)) //V130 = Can't have any OT Memory.
            {
                pk.ClearOTMemory();
                report = GetReport(pk);
            }
            if (report.Contains(LGeoMemoryMissing)) //V137 = GeoLocation Memory: Memories should be present.
            {
                var g = (IGeoTrack)pk;
                g.Geo1_Country = 1;
                report         = GetReport(pk);
            }
            if (report.Contains(LBallEncMismatch)) //V118 = Can't have ball for encounter type.
            {
                pk.Ball = 4;
                report  = GetReport(pk);
            }
            if (report.Contains(LGeoHardwareInvalid)) //Geolocation: Country is not in 3DS region.
            {
                pk.Country       = 0;
                pk.Region        = 0;
                pk.ConsoleRegion = 2;
                report           = GetReport(pk);
            }
            if (report.Contains(LFormBattle)) //V310 = Form cannot exist outside of a battle.
            {
                if (pk.Species == 718 && pk.Ability == 211)
                {
                    pk.AltForm = 3; // Zygarde Edge case
                }
                else
                {
                    pk.AltForm = 0;
                }
                report = GetReport(pk);
            }
            if (report.Contains(LFatefulMissing)) //V324 = Special ingame Fateful Encounter flag missing.
            {
                pk.FatefulEncounter = true;
                report = GetReport(pk);
            }
            if (report.Contains(LFatefulInvalid)) //V325 = Fateful Encounter should not be checked.

            {
                pk.FatefulEncounter = false;
                report = GetReport(pk);
            }
            if (report.Contains(LEncTypeMismatch)) //V381 = Encounter Type does not match encounter.
            {
                var match = new LegalityAnalysis(pk).Info.EncounterMatch;
                var type  = GetRequiredEncounterType(pk, match);

                if (!type.Contains(pk.EncounterType))
                {
                    pk.EncounterType = Convert.ToInt32(Math.Log((int)type, 2));
                }
                else
                {
                    Debug.WriteLine("This should never happen");
                }
                report = GetReport(pk);
            }
            if (report.Contains(LEvoInvalid)) //V86 = Evolution not valid (or level/trade evolution unsatisfied).
            {
                pk.Met_Level--;
                report = GetReport(pk);
            }
            if (report.Contains(LPIDTypeMismatch)) //V411 = Encounter Type PID mismatch.
            {
                SetPIDSID(pk, pk.IsShiny, pk.Version == (int)GameVersion.CXD);

                if (new LegalityAnalysis(pk).Valid)
                {
                    return(false);
                }

                report = GetReport(pk);
                if (report.Equals(LPIDTypeMismatch)) // V411 = Encounter Type PID mismatch.
                {
                    return(true);
                }

                if (report.Contains(LPIDGenderMismatch)) // V251 = PID-Gender mismatch.
                {
                    pk.Gender = pk.Gender == 0 ? 1 : 0;
                    report    = GetReport(pk);
                    if (new LegalityAnalysis(pk).Valid)
                    {
                        return(false);
                    }
                }
            }
            if (report.Contains(LHyperPerfectAll)) // V41 = Can't Hyper Train a Pokémon with perfect IVs.
            {
                ((IHyperTrain)pk).HyperTrainClear();
                report = GetReport(pk);
            }
            if (report.Contains(LHyperPerfectOne)) // V42 = Can't Hyper Train a perfect IV.
            {
                pk.ClearHyperTrainedPerfectIVs();
            }

            return(false);
        }
示例#18
0
        public async Task EggRaffleAsync()
        {
            if (!Info.Hub.Config.Trade.EggRaffle)
            {
                await ReplyAsync($"EggRaffle is currently disabled!").ConfigureAwait(false);

                return;
            }
            else if (!Info.Hub.Config.Trade.EggRaffleChannels.Contains(Context.Channel.Id.ToString()) && !Info.Hub.Config.Trade.EggRaffleChannels.Equals(""))
            {
                await ReplyAsync($"You're typing the command in the wrong channel!").ConfigureAwait(false);

                return;
            }

            if (Info.Hub.Config.Trade.EggRaffleCooldown < 0)
            {
                Info.Hub.Config.Trade.EggRaffleCooldown = default;
            }

            if (!System.IO.File.Exists("EggRngBlacklist.txt"))
            {
                System.IO.File.Create("EggRngBlacklist.txt").Close();
            }

            System.IO.StreamReader reader = new System.IO.StreamReader("EggRngBlacklist.txt");
            var content = reader.ReadToEnd();

            reader.Close();

            var id    = $"{Context.Message.Author.Id}";
            var parse = System.Text.RegularExpressions.Regex.Match(content, @"(" + id + @") - (\S*\ \S*\ \w*)", System.Text.RegularExpressions.RegexOptions.Multiline);

            if (content.Contains($"{Context.Message.Author.Id}"))
            {
                var timer         = System.DateTime.Parse(parse.Groups[2].Value).AddHours(Info.Hub.Config.Trade.EggRaffleCooldown);
                var timeremaining = timer - System.DateTime.Now;
                if (System.DateTime.Now >= timer)
                {
                    content = content.Replace(parse.Groups[0].Value, $"{id} - {System.DateTime.Now}").TrimEnd();
                    System.IO.StreamWriter writer = new System.IO.StreamWriter("EggRngBlacklist.txt");
                    writer.WriteLine(content);
                    writer.Close();
                }
                else
                {
                    await ReplyAsync($"{Context.User.Mention}, please try again in {timeremaining.Hours:N0}h : {timeremaining.Minutes:N0}m : {timeremaining.Seconds:N0}s!").ConfigureAwait(false);

                    return;
                }
            }
            else
            {
                System.IO.File.AppendAllText("EggRngBlacklist.txt", $"{Context.Message.Author.Id} - {System.DateTime.Now}{System.Environment.NewLine}");
            }

            var code = Info.GetRandomTradeCode();

            int[] validEgg = { 1,     4,   7,  10,  27,  37,  43,  50,  52,  54,  58,  60,  63,  66,  72,
                               77,   79,  81,  83,  90,  92,  95,  98, 102, 104, 108, 109, 111, 114, 115,
                               116, 118, 120, 122, 123, 127, 128, 129, 131, 133, 137, 163, 170, 172, 173,
                               174, 175, 177, 194, 206, 211, 213, 214, 215, 220, 222, 223, 225, 227, 236,
                               241, 246, 263, 270, 273, 278, 280, 290, 293, 298, 302, 303, 309, 318, 320,
                               324, 328, 337, 338, 339, 341, 343, 349, 355, 360, 361, 403, 406, 415, 420,
                               422, 425, 427, 434, 436, 438, 439, 440, 446, 447, 449, 451, 453, 458, 459,
                               479, 506, 509, 517, 519, 524, 527, 529, 532, 535, 538, 539, 543, 546, 548,
                               550, 551, 554, 556, 557, 559, 561, 562, 568, 570, 572, 574, 577, 582, 587,
                               588, 590, 592, 595, 597, 599, 605, 606, 607, 610, 613, 616, 618, 619, 621,
                               622, 624, 626, 627, 629, 631, 632, 633, 636, 659, 661, 674, 677, 679, 682,
                               684, 686, 688, 690, 692, 694, 701, 702, 704, 707, 708, 710, 712, 714, 722,
                               725, 728, 736, 742, 744, 746, 747, 749, 751, 753, 755, 757, 759, 761, 764,
                               765, 766, 767, 769, 771, 776, 777, 778, 780, 781, 782, 810, 813, 816, 819,
                               821, 824, 827, 829, 831, 833, 835, 837, 840, 843, 845, 846, 848, 850, 852,
                               854, 856, 859, 868, 870, 871, 872, 874, 875, 876, 877, 878, 884, 885 };

            int[] regional = { 27, 37, 50, 52, 77, 79, 83, 122, 222, 263, 554, 562, 618 };

            int[] shinyOdds = { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
                                3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
                                3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
                                5, 5, 5, 5, 5, 5, 5, 6, 6, 6 };

            int[] abilityIndex = { 0, 1, 2 };
            int[] formIndex1   = { 0, 1 };
            int[] formIndex2   = { 0, 1, 2 };

            var rng        = new System.Random();
            int shinyRng   = rng.Next(0, shinyOdds.Length);
            int abilityRng = rng.Next(0, abilityIndex.Length);
            var set        = new ShowdownSet($"Egg({SpeciesName.GetSpeciesName(rng.Next(new Zukan8Index(Zukan8Type.None, 1).Index, GameUtil.GetMaxSpeciesID(GameVersion.SWSH)), 2)})");

            while (!validEgg.ToList().Contains(set.Species))
            {
                set = new ShowdownSet($"Egg({SpeciesName.GetSpeciesName(rng.Next(new Zukan8Index(Zukan8Type.None, 1).Index, GameUtil.GetMaxSpeciesID(GameVersion.SWSH)), 2)})");
            }

            var template = AutoLegalityWrapper.GetTemplate(set);
            var sav      = AutoLegalityWrapper.GetTrainerInfo(8);
            var pkm      = (PK8)sav.GetLegal(template, out _);

            if (regional.ToList().Contains(pkm.Species))
            {
                int formRng  = rng.Next(0, formIndex1.Length);
                int formRng2 = rng.Next(0, formIndex2.Length);

                if (pkm.Species != 52)
                {
                    pkm.SetAltForm(formIndex1[formRng]);
                }
                else
                {
                    pkm.SetAltForm(formIndex2[formRng2]);
                }

                if (pkm.AltForm != 0)
                {
                    if (pkm.Species == 27)
                    {
                        pkm.RelearnMove3 = 10;
                    }
                    else if (pkm.Species == 37)
                    {
                        pkm.RelearnMove4 = 39;
                    }
                    else if (pkm.Species == 52)
                    {
                        pkm.RelearnMove2 = 252;
                        pkm.RelearnMove3 = 45;
                    }
                    else if (pkm.Species == 83)
                    {
                        pkm.RelearnMove1 = 64;
                        pkm.RelearnMove4 = 28;
                    }
                    else if (pkm.Species == 222)
                    {
                        pkm.RelearnMove1 = 33;
                    }
                    else if (pkm.Species == 263)
                    {
                        pkm.RelearnMove2 = 43;
                        pkm.RelearnMove3 = 0;
                        pkm.RelearnMove4 = 0;
                    }
                }
            }

            EggTrade(pkm);
            pkm.Nature     = rng.Next(0, 24);
            pkm.StatNature = pkm.Nature;
            pkm.SetAbilityIndex(abilityIndex[abilityRng]);
            pkm.IVs = pkm.SetRandomIVs(3);
            BallApplicator.ApplyBallLegalRandom(pkm);

            if (shinyOdds[shinyRng] == 3)
            {
                CommonEdits.SetShiny(pkm, Shiny.Never);
                pkm.SetUnshiny();
            }
            else if (shinyOdds[shinyRng] == 5)
            {
                CommonEdits.SetShiny(pkm, Shiny.AlwaysStar);
            }
            else
            {
                CommonEdits.SetShiny(pkm, Shiny.AlwaysSquare);
            }

            var la      = new LegalityAnalysis(pkm);
            var spec    = GameInfo.Strings.Species[template.Species];
            var invalid = !(pkm is PK8) || (!la.Valid && SysCordInstance.Self.Hub.Config.Legality.VerifyLegality);

            if (invalid)
            {
                var imsg = $"Oops! I scrambled your egg! Don't tell Ramsay! Here's my best attempt for that {spec}!";
                await Context.Channel.SendPKMAsync(pkm, imsg).ConfigureAwait(false);

                return;
            }

            pkm.ResetPartyStats();
            var sudo = Context.User.GetIsSudo();

            await AddTradeToQueueAsync(code, Context.User.Username, pkm, sudo).ConfigureAwait(false);
        }
示例#19
0
 private string GetSpeciesNameFromPKM(PKM pkm) => SpeciesName.GetSpeciesName(pkm.Species, SAV.Language);
示例#20
0
        private async Task <bool> TrollAsync(string content, IBattleTemplate set)
        {
            var  defaultMeme = "https://i.imgur.com/qaCwr09.png";
            var  path        = Info.Hub.Config.Trade.MemeFileNames.Split(',');
            bool web         = false;
            bool memeEmpty   = false;

            if (path.Length < 6)
            {
                path      = new string[] { defaultMeme, defaultMeme, defaultMeme, defaultMeme, defaultMeme, defaultMeme };
                memeEmpty = true;
            }

            if (Info.Hub.Config.Trade.MemeFileNames.Contains(".com") || memeEmpty)
            {
                web = true;
            }

            if (set.HeldItem == 16)
            {
                if (web)
                {
                    await Context.Channel.SendMessageAsync($"{path[0]}").ConfigureAwait(false);
                }
                else
                {
                    await Context.Channel.SendFileAsync(path[0]).ConfigureAwait(false);
                }
                return(true);
            }
            else if (set.HeldItem == 500)
            {
                if (web)
                {
                    await Context.Channel.SendMessageAsync($"{path[1]}").ConfigureAwait(false);
                }
                else
                {
                    await Context.Channel.SendFileAsync(path[1]).ConfigureAwait(false);
                }
                return(true);
            }
            else if (content.Contains($"★"))
            {
                if (web)
                {
                    await Context.Channel.SendMessageAsync($"{path[2]}").ConfigureAwait(false);
                }
                else
                {
                    await Context.Channel.SendFileAsync(path[2]).ConfigureAwait(false);
                }
                return(true);
            }
            else if (Info.Hub.Config.Trade.ItemMuleSpecies != Species.None && set.Shiny)
            {
                if (web)
                {
                    await Context.Channel.SendMessageAsync($"{path[3]}").ConfigureAwait(false);
                }
                else
                {
                    await Context.Channel.SendFileAsync(path[3]).ConfigureAwait(false);
                }
                return(true);
            }
            else if (set.Nickname == "Egg" && set.Species >= 888 && set.Species <= 893)
            {
                if (web)
                {
                    await Context.Channel.SendMessageAsync($"{path[4]}").ConfigureAwait(false);
                }
                else
                {
                    await Context.Channel.SendFileAsync(path[4]).ConfigureAwait(false);
                }
                return(true);
            }
            else if (Info.Hub.Config.Trade.ItemMuleSpecies != Species.None && set.Species != SpeciesName.GetSpeciesID(Info.Hub.Config.Trade.ItemMuleSpecies.ToString()))
            {
                if (Info.Hub.Config.Trade.DittoTrade && set.Species == 132 || Info.Hub.Config.Trade.EggTrade && set.Nickname == "Egg")
                {
                    return(false);
                }

                if (web)
                {
                    await Context.Channel.SendMessageAsync($"{path[5]}").ConfigureAwait(false);
                }
                else
                {
                    await Context.Channel.SendFileAsync(path[5]).ConfigureAwait(false);
                }
                return(true);
            }
            return(false);
        }
示例#21
0
        /// <summary>
        /// Gets a legal <see cref="PKM"/> from a random in-game encounter's data.
        /// </summary>
        /// <param name="blank">Template data that will have its properties modified</param>
        /// <param name="tr">Trainer Data to use in generating the encounter</param>
        /// <param name="species">Species ID to generate</param>
        /// <param name="form">Form to generate; if left null, picks first encounter</param>
        /// <returns>Result legal pkm, null if data should be ignored.</returns>
        private static PKM?GetRandomEncounter(PKM blank, ITrainerInfo tr, int species, int?form, bool shiny, ref int attempt)
        {
            blank.Species = species;
            blank.Gender  = blank.GetSaneGender();
            if (species is ((int)Species.Meowstic)or((int)Species.Indeedee))
            {
                if (form == null)
                {
                    blank.Form = blank.Gender;
                }
                else
                {
                    blank.Gender = (int)form;
                }
            }

            var template = PKMConverter.GetBlank(tr.Generation, (GameVersion)tr.Game);

            if (form != null)
            {
                blank.Form = (int)form;
                var item = SetFormSpecificItem(tr.Generation, blank.Species, (int)form);
                if (item != null)
                {
                    blank.HeldItem = (int)item;
                }
                if (blank.Species == (int)Species.Keldeo && blank.Form == 1)
                {
                    blank.Move1 = (int)Move.SecretSword;
                }
            }
            if (blank.IgnoreForm(tr, blank.Form))
            {
                return(null);
            }
            attempt += 1;
            var ssettext = new ShowdownSet(blank).Text.Split('\r')[0];

            if (shiny && !SimpleEdits.ShinyLockedSpeciesForm.Contains(new Tuple <Species, int>((Species)blank.Species, blank.Form)))
            {
                ssettext += Environment.NewLine + "Shiny: Yes";
            }
            var sset = new ShowdownSet(ssettext);
            var set  = new RegenTemplate(sset);

            template.ApplySetDetails(set);
            var success = tr.TryAPIConvert(set, template, out PKM pk);

            if (success == LegalizationResult.Regenerated)
            {
                if (form == null)
                {
                    return(pk);
                }
                else if (pk.Form == (int)form)
                {
                    return(pk);
                }
            }

            // just get a legal pkm and return. Only validate form and not shininess.
            var legalencs = EncounterMovesetGenerator.GeneratePKMs(blank, tr).Where(z => new LegalityAnalysis(z).Valid);
            var firstenc  = GetFirstEncounter(legalencs, form);

            if (firstenc == null)
            {
                attempt -= 1;
                return(null);
            }
            var originspecies = firstenc.Species;

            if (originspecies != blank.Species)
            {
                firstenc.Species      = blank.Species;
                firstenc.CurrentLevel = 100;
                if (!firstenc.IsNicknamed)
                {
                    firstenc.Nickname = SpeciesName.GetSpeciesNameGeneration(firstenc.Species, firstenc.Language, firstenc.Format);
                }
                firstenc.SetMoves(firstenc.GetMoveSet(), true);
                firstenc.RefreshAbility(firstenc.AbilityNumber >> 1);
            }
            var second = PKMConverter.ConvertToType(firstenc, blank.GetType(), out _);

            if (second == null)
            {
                return(null);
            }
            second.HeldItem = blank.HeldItem;
            if (form == null || second.Form == (int)form)
            {
                return(second);
            }
            // force form and check legality as a last ditch effort.
            second.Form = (int)form;
            second.SetSuggestedFormArgument(originspecies);
            if (new LegalityAnalysis(second).Valid)
            {
                return(second);
            }
            return(null);
        }
示例#22
0
文件: CLI.cs 项目: Jungbluth11/PKHeX
        /// <summary>
        /// Creates <see cref="PKM"/> from the showdownsets and checks compatibility with the savefile.
        /// </summary>
        /// <remarks>REMEMBER: Many moves was removed in the 8th gen, so some showdownsets will eventually be incompatible with your savefile.</remarks>
        public void CreatePkM()
        {
            if (SAV == null)
            {
                Console.WriteLine("No savefile loaded yet.");
                return;
            }
            if (showdownSets.Count == 0)
            {
                Console.WriteLine("No showdown set loaded.");
                return;
            }
            foreach (ShowdownSet set in showdownSets)
            {
                PKM    pkm         = SAV.BlankPKM;
                string speciesname = SpeciesName.GetSpeciesName(set.Species, 2);
                Console.WriteLine("Creating " + speciesname);

                if (Breeding.CanHatchAsEgg(set.Species))
                {
                    EncounterEgg egg = new EncounterEgg(set.Species, set.Form, set.Level, SAV.Generation, game);
                    pkm = egg.ConvertToPKM(SAV);
                }
                else
                {
                    pkm.Species = set.Species;
                    pkm.Form    = set.Form;
                    pkm.SetGender(pkm.GetSaneGender());
                    IEncounterable[] encs = EncounterMovesetGenerator.GenerateEncounter(pkm, SAV.Generation).ToArray();
                    if (encs.Length == 0)
                    {
                        // use debut generation for Pokemon that available but not catchable in current generation e.g. Meltan
                        encs = EncounterMovesetGenerator.GenerateEncounter(pkm, pkm.DebutGeneration).ToArray();
                    }
                    foreach (IEncounterable enc in encs)
                    {
                        PKM pk = enc.ConvertToPKM(SAV);
                        // not all Pokemon in database are legal in all games
                        if (new LegalityAnalysis(pk, SAV.Personal).Valid)
                        {
                            pkm = PKMConverter.ConvertToType(pk, SAV.PKMType, out _);
                            if ((pk.Generation != SAV.Generation || pk.GO || pk.GO_HOME || pk.LGPE) && pkm is IBattleVersion b)
                            {
                                b.BattleVersion = (int)game;
                            }
                            break;
                        }
                    }
                }
                pkm.Language = SAV.Language;
                pkm.ApplySetDetails(set);
                LegalityAnalysis la     = new LegalityAnalysis(pkm, SAV.Personal);
                string           report = la.Report();
                if (report == "Legal!")
                {
                    ENTITIES.Add(pkm);
                    IsValid.Add(true);
                }
                else
                {
                    // setting blank pkm if invalid for better indexing
                    ENTITIES.Add(SAV.BlankPKM);
                    IsValid.Add(false);
                    Console.WriteLine("Warning: " + speciesname + " is invalid!");
                    Console.WriteLine(report);
                    Console.WriteLine("Ignoring " + speciesname);
                }
            }
        }
        private async Task DoSeededEncounter(CancellationToken token)
        {
            ScanMode type = Hub.Config.SWSH_OverworldScan.EncounteringType;
            SAV8     sav  = await GetFakeTrainerSAV(token).ConfigureAwait(false);

            Species dexn   = 0;
            uint    offset = 0x00;

            if (type == ScanMode.G_Articuno)
            {
                dexn   = (Species)144;
                offset = CrownTundraSnowslideSlopeSpawns;
            }
            else if (type == ScanMode.G_Zapdos)
            {
                dexn   = (Species)145;
                offset = WildAreaMotostokeSpawns;
            }
            else if (type == ScanMode.G_Moltres)
            {
                dexn   = (Species)146;
                offset = IsleOfArmorStationSpaws;
            }
            else if (type == ScanMode.IoA_Wailord)
            {
                dexn   = (Species)321;
                offset = IsleOfArmorStationSpaws;
            }

            while (!token.IsCancellationRequested && offset != 0)
            {
                await FlyToRerollSeed(token).ConfigureAwait(false);

                var pkm = await ReadOwPokemon(dexn, offset, null, sav, token).ConfigureAwait(false);

                if (pkm != null && await LogPKMs(pkm, IsPKLegendary(pkm.Species), token).ConfigureAwait(false))
                {
                    await Click(X, 2_000, token).ConfigureAwait(false);
                    await Click(R, 2_000, token).ConfigureAwait(false);
                    await Click(A, 5_000, token).ConfigureAwait(false);
                    await Click(X, 2_000, token).ConfigureAwait(false);

                    Log($"The overworld encounter has been found. The progresses has been saved and the game is paused, you can now go and catch {SpeciesName.GetSpeciesName((int)dexn, 2)}");
                    return;
                }
            }
        }
示例#24
0
        public static string SetAnalysis(this RegenTemplate set, SaveFile sav)
        {
            var species_name = SpeciesName.GetSpeciesNameGeneration(set.Species, (int)LanguageID.English, sav.Generation);
            var analysis     = set.Form == 0 ? string.Format(SPECIES_UNAVAILABLE, species_name)
                                     : string.Format(SPECIES_UNAVAILABLE_FORM, species_name, set.FormName);

            // Species checks
            var gv = (GameVersion)sav.Game;

            if (!gv.ExistsInGame(set.Species, set.Form))
            {
                return(analysis); // Species does not exist in the game
            }
            // Species exists -- check if it has atleast one move. If it has no moves and it didn't generate, that makes the mon still illegal in game (moves are set to legal ones)
            var moves = set.Moves.Where(z => z != 0);
            var count = moves.Count();

            // Reusable data
            var blank     = sav.BlankPKM;
            var batchedit = APILegality.AllowBatchCommands && set.Regen.HasBatchSettings;
            var destVer   = (GameVersion)sav.Game;

            if (destVer <= 0)
            {
                destVer = sav.Version;
            }
            var gamelist = APILegality.FilteredGameList(blank, destVer, batchedit ? set.Regen.Batch.Filters : null);

            // Move checks
            List <IEnumerable <int> > move_combinations = new();

            for (int i = count; i >= 1; i--)
            {
                move_combinations.AddRange(GetKCombs(moves, i));
            }

            int[] original_moves = new int[4];
            set.Moves.CopyTo(original_moves, 0);
            int[] successful_combination = GetValidMoves(set, sav, move_combinations, blank, gamelist);
            if (!new HashSet <int>(original_moves.Where(z => z != 0)).SetEquals(successful_combination))
            {
                var invalid_moves = string.Join(", ", original_moves.Where(z => !successful_combination.Contains(z) && z != 0).Select(z => $"{(Move)z}"));
                return(successful_combination.Length > 0 ? string.Format(INVALID_MOVES, species_name, invalid_moves) : ALL_MOVES_INVALID);
            }
            set.Moves = original_moves;

            // All moves possible, get encounters
            blank.ApplySetDetails(set);
            blank.SetRecordFlags();
            var encounters = EncounterMovesetGenerator.GenerateEncounters(pk: blank, moves: original_moves, gamelist);

            if (set.Regen.EncounterFilters != null)
            {
                encounters = encounters.Where(enc => BatchEditing.IsFilterMatch(set.Regen.EncounterFilters, enc));
            }

            // Level checks, check if level is impossible to achieve
            if (encounters.All(z => !APILegality.IsRequestedLevelValid(set, z)))
            {
                return(string.Format(LEVEL_INVALID, species_name, encounters.Min(z => z.LevelMin)));
            }
            encounters = encounters.Where(enc => APILegality.IsRequestedLevelValid(set, enc));

            // Ability checks
            var abilityreq = APILegality.GetRequestedAbility(blank, set);

            if (abilityreq == AbilityRequest.NotHidden && encounters.All(z => z is EncounterStatic {
                Ability: 4
            }))
示例#25
0
        public async Task EggRollAsync()
        {
            if (!Info.Hub.Config.Trade.EggRollChannels.Contains(Context.Channel.Id.ToString()) && !Info.Hub.Config.Trade.EggRollChannels.Equals(""))
            {
                await ReplyAsync($"You're typing the command in the wrong channel!").ConfigureAwait(false);

                return;
            }

            if (Info.Hub.Config.Trade.EggRollCooldown < 0)
            {
                Info.Hub.Config.Trade.EggRollCooldown = default;
            }

            var id   = Context.User.Id.ToString();
            var line = TradeExtensions.EggRollCooldown.FirstOrDefault(z => z.Contains(id));

            System.DateTime.TryParse(line != null ? line.Split(',')[1] : string.Empty, out System.DateTime time);
            var timer         = time.AddHours(Info.Hub.Config.Trade.EggRollCooldown);
            var timeRemaining = timer - System.DateTime.Now;

            if (System.DateTime.Now < timer)
            {
                await ReplyAsync($"{Context.User.Mention}, please try again in {timeRemaining.Hours:N0}h : {timeRemaining.Minutes:N0}m : {timeRemaining.Seconds:N0}s!").ConfigureAwait(false);

                return;
            }

            var code       = Info.GetRandomTradeCode();
            var rng        = new System.Random();
            int shinyRng   = rng.Next(0, TradeExtensions.shinyOdds.Length);
            int abilityRng = rng.Next(0, TradeExtensions.abilityIndex.Length);
            var set        = new ShowdownSet($"Egg({SpeciesName.GetSpeciesName((int)TradeExtensions.validEgg.GetValue(rng.Next(0, TradeExtensions.validEgg.Length)), 2)})");
            var template   = AutoLegalityWrapper.GetTemplate(set);
            var sav        = AutoLegalityWrapper.GetTrainerInfo(8);
            var pkm        = (PK8)sav.GetLegal(template, out _);

            if (TradeExtensions.regional.ToList().Contains(pkm.Species))
            {
                int formRng  = rng.Next(0, TradeExtensions.formIndex1.Length);
                int formRng2 = rng.Next(0, TradeExtensions.formIndex2.Length);

                if (pkm.Species != 52)
                {
                    pkm.SetAltForm(TradeExtensions.formIndex1[formRng]);
                }
                else
                {
                    pkm.SetAltForm(TradeExtensions.formIndex2[formRng2]);
                }

                if (pkm.AltForm != 0)
                {
                    switch (pkm.Species)
                    {
                    case 27: pkm.RelearnMove3 = 10; break;

                    case 37: pkm.RelearnMove4 = 39; break;

                    case 52: pkm.RelearnMove2 = 252; pkm.RelearnMove3 = 45; break;

                    case 83: pkm.RelearnMove1 = 64; pkm.RelearnMove4 = 28; break;

                    case 222: pkm.RelearnMove1 = 33; break;

                    case 263: pkm.RelearnMove2 = 43; pkm.RelearnMove3 = 0; pkm.RelearnMove4 = 0; break;
                    }
                    ;
                }
            }

            TradeExtensions.EggTrade(pkm);
            pkm.Nature     = rng.Next(0, 24);
            pkm.StatNature = pkm.Nature;
            pkm.SetAbilityIndex(TradeExtensions.abilityIndex[abilityRng]);
            pkm.IVs = pkm.SetRandomIVs(3);
            BallApplicator.ApplyBallLegalRandom(pkm);

            switch (TradeExtensions.shinyOdds[shinyRng])
            {
            case 3: CommonEdits.SetShiny(pkm, Shiny.Never); pkm.SetUnshiny(); break;

            case 5: CommonEdits.SetShiny(pkm, Shiny.AlwaysStar); break;

            case 6: CommonEdits.SetShiny(pkm, Shiny.AlwaysSquare); break;
            }
            ;

            var la      = new LegalityAnalysis(pkm);
            var spec    = GameInfo.Strings.Species[template.Species];
            var invalid = !(pkm is PK8) || (!la.Valid && SysCordInstance.Self.Hub.Config.Legality.VerifyLegality);

            if (invalid)
            {
                var imsg = $"Oops! I scrambled your egg! Don't tell Ramsay! Here's my best attempt for that {spec}!";
                await Context.Channel.SendPKMAsync(pkm, imsg).ConfigureAwait(false);

                return;
            }

            pkm.ResetPartyStats();
            var sudo = Context.User.GetIsSudo();
            await Context.AddToQueueAsync(code, Context.User.Username, sudo, pkm, PokeRoutineType.EggRoll, PokeTradeType.EggRoll).ConfigureAwait(false);
        }
示例#26
0
        private static PKM SetToEgg(PKM pkm, int origin, GameVersion gameVersion)
        {
            int dayCare      = origin <= 4 ? Locations.Daycare4 : Locations.Daycare5;
            int metLevel     = origin <= 4 ? 0 : 1;
            int currentLevel = origin <= 4 ? 5 : 1;

            // 非初级形态
            PKM tmp = pkm.Clone();

            tmp.IsEgg        = true;
            tmp.Egg_Location = dayCare;
            tmp.Data[0xA8]   = tmp.Data[0xA8 + 1] = 0;    //Milotic
            List <CheckResult> checkResult = EncounterFinder.FindVerifiedEncounter(tmp).Parse;

            if (checkResult.IsPropStrInEleList("Comment", LegalityCheckStrings.LEvoInvalid))
            {
                return(null);
            }

            int language = pkm.Language;

            pkm.Nickname     = SpeciesName.GetSpeciesNameGeneration((int)Species.None, language, pkm.Format);
            pkm.IsNicknamed  = true;
            pkm.IsEgg        = true;
            pkm.HeldItem     = 0;
            pkm.CurrentLevel = currentLevel;
            pkm.StatNature   = pkm.Nature;
            pkm.RefreshAbility(new Random().Next(0, 3));

            pkm.SetIVs();
            pkm.EVs = new int[6];

            pkm.Ball         = (int)Ball.Poke;
            pkm.Met_Location = 0;
            pkm.Met_Level    = metLevel;
            pkm.Egg_Location = dayCare;

            ReflectUtils.methods.TryGetValue("GetEggMoves", out MethodInfo method);
            int[] result = (int[])method.Invoke(null, new object[] { pkm, pkm.Species, pkm.AltForm, gameVersion });
            pkm.SetMoves(new List <int>());
            if (result.Length == 0)
            {
                pkm.SetRelearnMoves(pkm.GetSuggestedRelearnMoves());
            }
            else
            {
                pkm.SetRelearnMoves(GetEggMovesRandom(pkm, result));
            }
            pkm.SetMoves(pkm.RelearnMoves);
            pkm.SetMovesPPUpsToZero();
            pkm.SetMaximumPPCurrent();
            pkm.FixMoves();

            // 8代独有数据
            if (pkm.Format == 8)
            {
                PK8 pk8 = (PK8)pkm;
                pk8.DynamaxLevel  = 0;
                pk8.CanGigantamax = false;
            }

            pkm.ClearAllRibbon();
            pkm.ClearCurrentHandler();
            pkm.ClearMemories();
            pkm.ClearRecordFlags();
            pkm.CurrentFriendship = 4;

            return(pkm);
        }
示例#27
0
        /// <summary>
        /// Gets a legal <see cref="PKM"/> from a random in-game encounter's data.
        /// </summary>
        /// <param name="blank">Template data that will have its properties modified</param>
        /// <param name="tr">Trainer Data to use in generating the encounter</param>
        /// <param name="species">Species ID to generate</param>
        /// <returns>Result legal pkm, null if data should be ignored.</returns>
        private static PKM?GetRandomEncounter(PKM blank, ITrainerInfo tr, int species)
        {
            blank.Species = species;
            blank.Gender  = blank.GetSaneGender();
            if (species is ((int)Species.Meowstic)or((int)Species.Indeedee))
            {
                blank.Form = blank.Gender;
            }

            var legalencs = EncounterMovesetGenerator.GeneratePKMs(blank, tr).Where(z => new LegalityAnalysis(z).Valid);
            var firstenc  = legalencs.FirstOrDefault();

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

            var f = PKMConverter.ConvertToType(firstenc, blank.GetType(), out _);

            if (f == null)
            {
                var template = PKMConverter.GetBlank(tr.Generation, (GameVersion)tr.Game);
                var set      = new ShowdownSet(new ShowdownSet(blank).Text.Split('\r')[0]);
                template.ApplySetDetails(set);
                var success = tr.TryAPIConvert(set, template, out PKM pk);
                return(success == LegalizationResult.Regenerated ? pk : null);
            }
            var an = f.AbilityNumber;

            f.Species = species;
            f.Gender  = f.GetSaneGender();
            if (species is ((int)Species.Meowstic)or((int)Species.Indeedee))
            {
                f.Form = f.Gender;
            }
            f.CurrentLevel = 100;
            f.Nickname     = SpeciesName.GetSpeciesNameGeneration(f.Species, f.Language, f.Format);
            f.IsNicknamed  = false;
            f.SetSuggestedMoves();
            f.SetSuggestedMovePP(0);
            f.SetSuggestedMovePP(1);
            f.SetSuggestedMovePP(2);
            f.SetSuggestedMovePP(3);
            f.RefreshAbility(an >> 1);
            var info = new LegalityAnalysis(f).Info;

            if (info.Generation > 0 && info.EvoChainsAllGens[info.Generation].All(z => z.Species != info.EncounterMatch.Species))
            {
                f.CurrentHandler = 1;
                f.HT_Name        = f.OT_Name;
                if (f is IHandlerLanguage h)
                {
                    h.HT_Language = 1;
                }
            }
            if (f is IFormArgument fa)
            {
                fa.FormArgument = ShowdownEdits.GetSuggestedFormArgument(f, info.EncounterMatch.Species);
            }
            int wIndex = WurmpleUtil.GetWurmpleEvoGroup(f.Species);

            if (wIndex != -1)
            {
                f.EncryptionConstant = WurmpleUtil.GetWurmpleEncryptionConstant(wIndex);
            }
            if (f is IHomeTrack {
                Tracker : 0
            } ht&& APILegality.SetRandomTracker)
            {
                ht.Tracker = APILegality.GetRandomULong();
            }
            if (new LegalityAnalysis(f).Valid)
            {
                return(f);
            }

            // local name clashes!
            {
                var template = PKMConverter.GetBlank(tr.Generation, (GameVersion)tr.Game);
                var set      = new ShowdownSet(new ShowdownSet(blank).Text.Split('\r')[0]);
                template.ApplySetDetails(set);
                var success = tr.TryAPIConvert(set, template, out PKM pk);
                return(success == LegalizationResult.Regenerated ? pk : null);
            }
        }
示例#28
0
        public void AddToBoxesButtonClick(Object sender, EventArgs events)
        {
            var        sav          = SaveFileEditor.SAV;                                        // current save
            int        generation   = sav.Generation;                                            // the generation of the current save -- used to determine the PK save format
            List <PKM> pokemonList  = new List <PKM>();                                          // list of all Pokemon that will be added to the sav
            string     showdownData = this.input.Text;                                           // user's input

            var pokemonArray = JsonConvert.DeserializeObject <List <RawPokemon> >(showdownData); //jsonify the data

            foreach (RawPokemon rawPokemon in pokemonArray)
            {
                PKM pokemon = new PK2();

                //Determine save format
                switch (generation)
                {
                case 1:
                    pokemon = new PK1();
                    break;

                case 2:
                    pokemon = new PK2();
                    break;

                case 3:
                    pokemon = new PK3();
                    break;

                case 4:
                    pokemon = new PK4();
                    break;

                case 5:
                    pokemon = new PK5();
                    break;

                case 6:
                    pokemon = new PK6();
                    break;

                case 7:
                    pokemon = new PK7();
                    break;

                case 8:
                    pokemon = new PK8();
                    break;
                }

                // Set the species according to the Species enum
                int speciesAsNumber = 0;

                //Check if the Pokemon is Alolan or not; if it is, do some extra logic to set the proper form
                if (rawPokemon.Species.Contains("Alolan"))
                {
                    string[] pokemon_name = rawPokemon.Species.Split('_');
                    speciesAsNumber = (int)(Species)Enum.Parse(typeof(Species), pokemon_name[1]);
                    pokemon.SetForm(810);
                    pokemon.Species = speciesAsNumber;
                }
                else
                {
                    speciesAsNumber = (int)(Species)Enum.Parse(typeof(Species), rawPokemon.Species);
                    pokemon.Species = speciesAsNumber;
                }

                // Check to see if the Pokemon has forms (i.e. Flabebe, Shellos, etc.), and if it does, randomly generate one
                if (rawPokemon.Species.Contains("Burmy"))
                {
                    int form = random.Next(0, burmyForms.Length - 1);
                    pokemon.SetForm(form);
                }
                else if (rawPokemon.Species.Contains("Shellos"))
                {
                    int form = random.Next(0, shellosForms.Length - 1);
                    pokemon.SetForm(form);
                }
                else if (rawPokemon.Species.Contains("Scatterbug"))
                {
                    int form = random.Next(0, scatterbugForms.Length - 1);
                    pokemon.SetForm(form);
                }
                else if (rawPokemon.Species.Contains("Flabébé"))
                {
                    int form = random.Next(0, flabebeForms.Length - 1);
                    pokemon.SetForm(form);
                }
                else if (rawPokemon.Species.Contains("Oricorio"))
                {
                    int form = random.Next(0, oricorioForms.Length - 1);
                    pokemon.SetForm(form);
                }
                else if (rawPokemon.Species.Contains("Minior"))
                {
                    int form = random.Next(0, miniorForms.Length - 1);
                    pokemon.SetForm(form);
                }

                GameVersion  game         = (GameVersion)sav.Game;
                EncounterEgg encounterEgg = new EncounterEgg(speciesAsNumber, pokemon.Form, 1, sav.Generation, game);
                PKM          pokemonAsEgg = encounterEgg.ConvertToPKM(sav);
                pokemonAsEgg.IsEgg  = true;
                pokemon.IsNicknamed = true;
                pokemon.Nickname    = "Egg";

                // Set the ability
                string ability         = rawPokemon.Ability.Replace(" ", "");
                int    abilityAsNumber = (int)(Ability)Enum.Parse(typeof(Ability), ability);
                pokemonAsEgg.SetAbility(abilityAsNumber);

                //Set gender
                switch (rawPokemon.Gender)
                {
                case "M":
                    pokemonAsEgg.SetGender(0);
                    break;

                case "F":
                    pokemonAsEgg.SetGender(1);
                    break;

                case "N":
                    pokemonAsEgg.SetGender(2);
                    break;
                }

                // Set Nature via the Nature enum
                int natureAsNumber = (int)(Nature)Enum.Parse(typeof(Nature), rawPokemon.Nature);
                pokemonAsEgg.Nature = natureAsNumber;

                // Set the IVs
                pokemonAsEgg.IV_HP  = rawPokemon.HP;
                pokemonAsEgg.IV_ATK = rawPokemon.Atk;
                pokemonAsEgg.IV_DEF = rawPokemon.Def;
                pokemonAsEgg.IV_SPA = rawPokemon.SpA;
                pokemonAsEgg.IV_SPD = rawPokemon.SpD;
                pokemonAsEgg.IV_SPE = rawPokemon.Spe;

                // Set moves and make sure they have the proper PP
                string move = "";
                if (string.IsNullOrEmpty(rawPokemon.MoveOne) == false)
                {
                    move = rawPokemon.MoveOne.Replace("-", "");
                    move = move.Replace(" ", "");
                    pokemonAsEgg.Move1        = (int)(Move)Enum.Parse(typeof(Move), move);
                    pokemonAsEgg.RelearnMove1 = pokemonAsEgg.Move1;
                }
                if (string.IsNullOrEmpty(rawPokemon.MoveTwo) == false)
                {
                    move = rawPokemon.MoveTwo.Replace("-", "");
                    move = move.Replace(" ", "");
                    pokemonAsEgg.Move2        = (int)(Move)Enum.Parse(typeof(Move), move);
                    pokemonAsEgg.RelearnMove2 = pokemonAsEgg.Move2;
                }
                if (string.IsNullOrEmpty(rawPokemon.MoveThree) == false)
                {
                    move = rawPokemon.MoveThree.Replace("-", "");
                    move = move.Replace(" ", "");
                    pokemonAsEgg.Move3        = (int)(Move)Enum.Parse(typeof(Move), move);
                    pokemonAsEgg.RelearnMove3 = pokemonAsEgg.Move3;
                }
                if (string.IsNullOrEmpty(rawPokemon.MoveFour) == false)
                {
                    move = rawPokemon.MoveFour.Replace("-", "");
                    move = move.Replace(" ", "");
                    pokemonAsEgg.Move4        = (int)(Move)Enum.Parse(typeof(Move), move);
                    pokemonAsEgg.RelearnMove4 = pokemonAsEgg.Move4;
                }

                pokemonAsEgg.SetMaximumPPCurrent();

                //Finally, if the Pokemon is supposed to be shiny, make it so
                if (rawPokemon.IsShiny == "true")
                {
                    CommonEdits.SetShiny(pokemonAsEgg);
                }
                else
                {
                    CommonEdits.SetUnshiny(pokemonAsEgg);
                }

                pokemonAsEgg.Met_Location = 0;

                if (generation == 7 || generation == 6 || generation == 5)
                {
                    pokemonAsEgg.Egg_Location = Locations.Daycare5;
                }
                else
                {
                    pokemonAsEgg.Egg_Location = Locations.Daycare4;
                }

                pokemonAsEgg.IsNicknamed = true;
                pokemonAsEgg.Nickname    = SpeciesName.GetSpeciesNameGeneration(0, sav.Language, generation);

                //Hatch counter is for some reason called "CurrentFriendship".  Don't ask me why, I don't know.
                pokemonAsEgg.CurrentFriendship = 1;

                pokemonList.Add(pokemonAsEgg);
            }

            // Import Pokemon, reload the boxes so they can be seen, show a message and close the window
            sav.ImportPKMs(pokemonList);
            SaveFileEditor.ReloadSlots();
            MessageBox.Show("Done!");
            this.input.Clear();
            this.form.Close();
        }