public static async Task ReplyWithLegalizedSetAsync(this ISocketMessageChannel channel, ITrainerInfo sav, ShowdownSet set)
        {
            if (set.Species <= 0)
            {
                await channel.SendMessageAsync("Oops! I wasn't able to interpret your message! If you intended to convert something, please double check what you're pasting!").ConfigureAwait(false);

                return;
            }

            try
            {
                var template = AutoLegalityWrapper.GetTemplate(set);
                var pkm      = sav.GetLegal(template, out var result);
                if (pkm is PK8 && pkm.Nickname.ToLower() == "egg" && Breeding.CanHatchAsEgg(pkm.Species))
                {
                    TradeExtensions <PK8> .EggTrade(pkm);
                }
                else if (pkm is PB8 && pkm.Nickname.ToLower() == "egg" && Breeding.CanHatchAsEgg(pkm.Species))
                {
                    TradeExtensions <PB8> .EggTrade(pkm);
                }

                var la   = new LegalityAnalysis(pkm);
                var spec = GameInfo.Strings.Species[template.Species];
                if (!la.Valid)
                {
                    var reason = result == "Timeout" ? $"That {spec} set took too long to generate." : $"I wasn't able to create a {spec} from that set.";
                    var imsg   = $"Oops! {reason}";
                    if (result == "Failed")
                    {
                        imsg += $"\n{AutoLegalityWrapper.GetLegalizationHint(template, sav, pkm)}";
                    }
                    await channel.SendMessageAsync(imsg).ConfigureAwait(false);

                    return;
                }

                var msg = $"Here's your ({result}) legalized PKM for {spec} ({la.EncounterOriginal.Name})!";
                await channel.SendPKMAsync(pkm, msg + $"\n{ReusableActions.GetFormattedShowdownText(pkm)}").ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                LogUtil.LogSafe(ex, nameof(AutoLegalityExtensionsDiscord));
                var msg = $"Oops! An unexpected problem happened with this Showdown Set:\n```{string.Join("\n", set.GetSetLines())}```";
                await channel.SendMessageAsync(msg).ConfigureAwait(false);
            }
        }
    public static IEnumerable <EncounterEgg> GenerateEggs(PKM pk, EvoCriteria[] chain, bool all = false)
    {
        int species = pk.Species;

        if (!Breeding.CanHatchAsEgg(species))
        {
            yield break;
        }

        var canBeEgg = all || GetCanBeEgg(pk);

        if (!canBeEgg)
        {
            yield break;
        }

        // Gen2 was before split-breed species existed; try to ensure that the egg we try and match to can actually originate in the game.
        // Species must be < 251
        // Form must be 0 (Unown cannot breed).
        var baseID = chain[^ 1];
    public static IEnumerable <EncounterEgg> GenerateEggs(PKM pk, EvoCriteria[] chain, int generation, bool all = false)
    {
        System.Diagnostics.Debug.Assert(generation >= 3); // if generating Gen2 eggs, use the other generator.
        int currentSpecies = pk.Species;

        if (!Breeding.CanHatchAsEgg(currentSpecies))
        {
            yield break;
        }

        var currentForm = pk.Form;

        if (!Breeding.CanHatchAsEgg(currentSpecies, currentForm, generation))
        {
            yield break; // can't originate from eggs
        }
        // version is a true indicator for all generation 3-5 origins
        var ver = (GameVersion)pk.Version;

        if (!Breeding.CanGameGenerateEggs(ver))
        {
            yield break;
        }

        var lvl = EggStateLegality.GetEggLevel(generation);
        int max = GetMaxSpeciesOrigin(generation);

        var(species, form) = GetBaseSpecies(chain, 0);
        if ((uint)species <= max)
        {
            // NOTE: THE SPLIT-BREED SECTION OF CODE SHOULD BE EXACTLY THE SAME AS THE BELOW SECTION
            if (FormInfo.IsBattleOnlyForm(species, form, generation))
            {
                form = FormInfo.GetOutOfBattleForm(species, form, generation);
            }
            if (Breeding.CanHatchAsEgg(species, form, ver))
            {
                yield return(new EncounterEgg(species, form, lvl, generation, ver));

                if (generation > 5 && (pk.WasTradedEgg || all) && HasOtherGamePair(ver))
                {
                    yield return(new EncounterEgg(species, form, lvl, generation, GetOtherTradePair(ver)));
                }
            }
        }

        if (!Breeding.GetSplitBreedGeneration(generation).Contains(currentSpecies))
        {
            yield break; // no other possible species
        }
        var otherSplit = species;

        (species, form) = GetBaseSpecies(chain, 1);
        if ((uint)species == otherSplit)
        {
            yield break;
        }

        if (species <= max)
        {
            // NOTE: THIS SECTION OF CODE SHOULD BE EXACTLY THE SAME AS THE ABOVE SECTION
            if (FormInfo.IsBattleOnlyForm(species, form, generation))
            {
                form = FormInfo.GetOutOfBattleForm(species, form, generation);
            }
            if (Breeding.CanHatchAsEgg(species, form, ver))
            {
                yield return(new EncounterEgg(species, form, lvl, generation, ver));

                if (generation > 5 && (pk.WasTradedEgg || all) && HasOtherGamePair(ver))
                {
                    yield return(new EncounterEgg(species, form, lvl, generation, GetOtherTradePair(ver)));
                }
            }
        }
    }
        // Helper functions for commands
        public static bool AddToWaitingList(string setstring, string display, string username, ulong mUserId, bool sub, out string msg)
        {
            if (!TwitchBot <T> .Info.GetCanQueue())
            {
                msg = "Sorry, I am not currently accepting queue requests!";
                return(false);
            }

            var set = ShowdownUtil.ConvertToShowdown(setstring);

            if (set == null)
            {
                msg = $"Skipping trade, @{username}: Empty nickname provided for the species.";
                return(false);
            }
            var template = AutoLegalityWrapper.GetTemplate(set);

            if (template.Species < 1)
            {
                msg = $"Skipping trade, @{username}: Please read what you are supposed to type as the command argument.";
                return(false);
            }

            if (set.InvalidLines.Count != 0)
            {
                msg = $"Skipping trade, @{username}: Unable to parse Showdown Set:\n{string.Join("\n", set.InvalidLines)}";
                return(false);
            }

            try
            {
                var sav = AutoLegalityWrapper.GetTrainerInfo <T>();
                PKM pkm = sav.GetLegal(template, out var result);

                var nickname = pkm.Nickname.ToLower();
                if (nickname == "egg" && Breeding.CanHatchAsEgg(pkm.Species))
                {
                    TradeExtensions <T> .EggTrade(pkm);
                }

                if (pkm.Species == 132 && (nickname.Contains("atk") || nickname.Contains("spa") || nickname.Contains("spe") || nickname.Contains("6iv")))
                {
                    TradeExtensions <T> .DittoTrade(pkm);
                }

                if (!pkm.CanBeTraded())
                {
                    msg = $"Skipping trade, @{username}: Provided Pokémon content is blocked from trading!";
                    return(false);
                }

                if (pkm is T pk)
                {
                    var valid = new LegalityAnalysis(pkm).Valid;
                    if (valid)
                    {
                        var tq = new TwitchQueue <T>(pk, new PokeTradeTrainerInfo(display, mUserId), username, sub);
                        TwitchBot <T> .QueuePool.RemoveAll(z => z.UserName == username); // remove old requests if any

                        TwitchBot <T> .QueuePool.Add(tq);

                        msg = $"@{username} - added to the waiting list. Please whisper your trade code to me! Your request from the waiting list will be removed if you are too slow!";
                        return(true);
                    }
                }

                var reason = result == "Timeout" ? "Set took too long to generate." : "Unable to legalize the Pokémon.";
                msg = $"Skipping trade, @{username}: {reason}";
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                LogUtil.LogSafe(ex, nameof(TwitchCommandsHelper <T>));
                msg = $"Skipping trade, @{username}: An unexpected problem occurred.";
            }
            return(false);
        }
Example #5
0
        /// <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);
                }
            }
        }
Example #6
0
        public async Task TradeAsync([Summary("Trade Code")] int code, [Summary("Showdown Set")][Remainder] string content)
        {
            content = ReusableActions.StripCodeBlock(content);
            var set      = new ShowdownSet(content);
            var template = AutoLegalityWrapper.GetTemplate(set);

            if (set.InvalidLines.Count != 0)
            {
                var msg = $"Unable to parse Showdown Set:\n{string.Join("\n", set.InvalidLines)}";
                await ReplyAsync(msg).ConfigureAwait(false);

                return;
            }

            try
            {
                var sav = AutoLegalityWrapper.GetTrainerInfo <T>();
                var pkm = sav.GetLegal(template, out var result);
                if (pkm.Species == 132)
                {
                    TradeExtensions <T> .DittoTrade(pkm);
                }

                if (pkm.Nickname.ToLower() == "egg" && Breeding.CanHatchAsEgg(pkm.Species))
                {
                    TradeExtensions <T> .EggTrade(pkm);
                }

                var la   = new LegalityAnalysis(pkm);
                var spec = GameInfo.Strings.Species[template.Species];
                pkm = EntityConverter.ConvertToType(pkm, typeof(T), out _) ?? pkm;
                bool memes = Info.Hub.Config.Trade.Memes && await TradeAdditionsModule <T> .TrollAsync(Context, pkm is not T || !la.Valid, pkm).ConfigureAwait(false);

                if (memes)
                {
                    return;
                }

                if (pkm is not T pk || !la.Valid)
                {
                    var reason = result == "Timeout" ? $"That {spec} set took too long to generate." : $"I wasn't able to create a {spec} from that set.";
                    var imsg   = $"Oops! {reason}";
                    if (result == "Failed")
                    {
                        imsg += $"\n{AutoLegalityWrapper.GetLegalizationHint(template, sav, pkm)}";
                    }
                    await ReplyAsync(imsg).ConfigureAwait(false);

                    return;
                }
                pk.ResetPartyStats();

                var sig = Context.User.GetFavor();
                await AddTradeToQueueAsync(code, Context.User.Username, pk, sig, Context.User).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                LogUtil.LogSafe(ex, nameof(TradeModule <T>));
                var msg = $"Oops! An unexpected problem happened with this Showdown Set:\n```{string.Join("\n", set.GetSetLines())}```";
                await ReplyAsync(msg).ConfigureAwait(false);
            }
        }