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

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

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

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

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

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

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

                var la = new LegalityAnalysis(pk);
                if (la.Valid)
                {
                    satisfied = true;
                    return(pk);
                }
                Debug.WriteLine(la.Report());
            }
            satisfied = false;
            return(template);
        }
Пример #2
0
        /// <summary>
        /// Main function that auto legalizes based on the legality
        /// </summary>
        /// <remarks>Leverages <see cref="Core"/>'s <see cref="EncounterMovesetGenerator"/> to create a <see cref="PKM"/> from a <see cref="ShowdownSet"/>.</remarks>
        /// <param name="dest">Destination for the generated pkm</param>
        /// <param name="template">rough pkm that has all the <see cref="set"/> values entered</param>
        /// <param name="set">Showdown set object</param>
        /// <param name="satisfied">If the final result is satisfactory, otherwise use current auto legality functionality</param>
        public static PKM GetLegalFromTemplate(this ITrainerInfo dest, PKM template, ShowdownSet set, out bool satisfied)
        {
            var Form = SanityCheckForm(template, ref set);

            template.ApplySetDetails(set);
            var destType = template.GetType();
            var destVer  = (GameVersion)dest.Game;

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

            var encounters = EncounterMovesetGenerator.GenerateEncounters(pk: template, moves: set.Moves);

            foreach (var enc in encounters)
            {
                var ver = enc is IVersion v ? v.Version : destVer;
                var gen = enc is IGeneration g ? g.Generation : dest.Generation;
                var tr  = TrainerSettings.GetSavedTrainerData(ver, gen);
                var raw = enc.ConvertToPKM(tr);
                var pk  = PKMConverter.ConvertToType(raw, destType, out _);
                ApplySetDetails(pk, set, Form, raw, dest);

                var la = new LegalityAnalysis(pk);
                if (la.Valid)
                {
                    satisfied = true;
                    return(pk);
                }
                Debug.WriteLine(la.Report());
            }
            satisfied = false;
            return(template);
        }
        /// <summary>
        /// Load PKM from byte array. The output is a boolean, which is true if a byte array is loaded into WinForms, else false
        /// </summary>
        /// <param name="input">Byte array input correlating to the PKM</param>
        /// <param name="path">Path to the file itself</param>
        /// <param name="ext">Extension of the file</param>
        /// <param name="SAV">Type of save file</param>
        /// <returns></returns>
        private bool TryLoadPKM(byte[] input, string path, string ext, SaveFile SAV)
        {
            var temp = PKMConverter.GetPKMfromBytes(input, prefer: ext.Length > 0 ? (ext.Last() - 0x30) & 7 : SAV.Generation);

            if (temp == null)
            {
                return(false);
            }

            var type = CurrentPKM.GetType();
            PKM pk   = PKMConverter.ConvertToType(temp, type, out string c);

            if (pk == null)
            {
                return(false);
            }
            if (SAV.Generation < 3 && ((pk as PK1)?.Japanese ?? ((PK2)pk).Japanese) != SAV.Japanese)
            {
                var strs = new[] { "International", "Japanese" };
                var val  = SAV.Japanese ? 0 : 1;
                WinFormsUtil.Alert($"Cannot load {strs[val]} {pk.GetType().Name}s to {strs[val ^ 1]} saves.");
                return(false);
            }

            PopulateFields(pk);
            Console.WriteLine(c);
            return(true);
        }
Пример #4
0
        /// <summary>
        /// Main function that auto legalizes based on the legality
        /// </summary>
        /// <remarks>Leverages <see cref="Core"/>'s <see cref="EncounterMovesetGenerator"/> to create a <see cref="PKM"/> from a <see cref="IBattleTemplate"/>.</remarks>
        /// <param name="dest">Destination for the generated pkm</param>
        /// <param name="template">rough pkm that has all the <see cref="set"/> values entered</param>
        /// <param name="set">Showdown set object</param>
        /// <param name="satisfied">If the final result is satisfactory, otherwise use deprecated bruteforce auto legality functionality</param>
        public static PKM GetLegalFromTemplate(this ITrainerInfo dest, PKM template, IBattleTemplate set, out bool satisfied)
        {
            if (set is RegenTemplate t)
            {
                t.FixGender(template.PersonalInfo);
            }
            template.ApplySetDetails(set);
            template.SetRecordFlags(); // Validate TR moves for the encounter
            var isHidden = template.AbilityNumber == 4;
            var destType = template.GetType();
            var destVer  = (GameVersion)dest.Game;

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

            var gamelist   = GameUtil.GetVersionsWithinRange(template, template.Format).OrderByDescending(c => c.GetGeneration()).ToArray();
            var encounters = EncounterMovesetGenerator.GenerateEncounters(pk: template, moves: set.Moves, gamelist);

            encounters = encounters.Concat(GetFriendSafariEncounters(template));
            foreach (var enc in encounters)
            {
                if (!IsEncounterValid(set, enc, isHidden, destVer, out var ver))
                {
                    continue;
                }
                var tr  = UseTrainerData ? TrainerSettings.GetSavedTrainerData(ver, enc.Generation) : TrainerSettings.DefaultFallback(enc.Generation);
                var raw = SanityCheckEncounters(enc).ConvertToPKM(tr);
                if (raw.IsEgg) // PGF events are sometimes eggs. Force hatch them before proceeding
                {
                    raw.HandleEggEncounters(enc, tr);
                }
                var pk = PKMConverter.ConvertToType(raw, destType, out _);
                if (pk == null)
                {
                    continue;
                }

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

                var la = new LegalityAnalysis(pk);
                if (la.Valid)
                {
                    satisfied = true;
                    return(pk);
                }
                Debug.WriteLine($"{la.Report()}\n");
            }
            satisfied = false;
            return(template);
        }
Пример #5
0
 private bool LoadPKM(PKM pk)
 {
     pk = PKMConverter.ConvertToType(pk, SaveFileEditor.SAV.PKMType, out _);
     if (pk == null)
     {
         return(false);
     }
     PKMEditor.PopulateFields(pk);
     return(true);
 }
Пример #6
0
 private static PK8?GetRequest(Download <PKM> dl)
 {
     if (!dl.Success)
     {
         return(null);
     }
     return(dl.Data switch
     {
         null => null,
         PK8 pk8 => pk8,
         _ => PKMConverter.ConvertToType(dl.Data, typeof(PK8), out _) as PK8
     });
Пример #7
0
        /// <summary>
        /// Main function that auto legalizes based on the legality
        /// </summary>
        /// <remarks>Leverages <see cref="Core"/>'s <see cref="EncounterMovesetGenerator"/> to create a <see cref="PKM"/> from a <see cref="ShowdownSet"/>.</remarks>
        /// <param name="dest">Destination for the generated pkm</param>
        /// <param name="template">rough pkm that has all the <see cref="set"/> values entered</param>
        /// <param name="set">Showdown set object</param>
        /// <param name="satisfied">If the final result is satisfactory, otherwise use deprecated bruteforce auto legality functionality</param>
        public static PKM GetLegalFromTemplate(this ITrainerInfo dest, PKM template, ShowdownSet set, out bool satisfied)
        {
            var Form = SanityCheckForm(template, ref set);

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

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

            var gamelist   = GameUtil.GetVersionsWithinRange(template, template.Format).OrderByDescending(c => c.GetGeneration()).ToArray();
            var encounters = EncounterMovesetGenerator.GenerateEncounters(pk: template, moves: set.Moves, gamelist);

            foreach (var enc in encounters)
            {
                var          ver = enc is IVersion v ? v.Version : destVer;
                var          gen = enc is IGeneration g ? g.Generation : dest.Generation;
                ITrainerInfo tr  = new SimpleTrainerInfo(ver);
                if (UseTrainerData)
                {
                    tr = TrainerSettings.GetSavedTrainerData(ver, gen, new SimpleTrainerInfo(ver));
                }
                var raw = SanityCheckEncounters(enc).ConvertToPKM(tr);
                var pk  = PKMConverter.ConvertToType(raw, destType, out _);
                if (pk == null)
                {
                    continue;
                }

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

                var la = new LegalityAnalysis(pk);
                if (la.Valid)
                {
                    satisfied = true;
                    return(pk);
                }
                Debug.WriteLine(la.Report());
            }
            satisfied = false;
            return(template);
        }
Пример #8
0
        /// <summary>
        /// Gets a legal <see cref="PKM"/> from a random in-game encounter's data.
        /// </summary>
        /// <param name="sav">Save File to receive the generated <see cref="PKM"/>.</param>
        /// <param name="tr">Trainer Data to use in generating the encounter</param>
        /// <param name="species">Species ID to generate</param>
        /// <param name="pk">Result legal pkm</param>
        /// <returns>True if a valid result was generated, false if the result should be ignored.</returns>
        public static bool GetRandomEncounter(this SaveFile sav, ITrainerInfo tr, int species, out PKM?pk)
        {
            var blank = sav.BlankPKM;

            pk = GetRandomEncounter(blank, tr, species);
            if (pk == null)
            {
                return(false);
            }

            pk = PKMConverter.ConvertToType(pk, sav.PKMType, out _);
            return(pk != null);
        }
Пример #9
0
        /// <summary>
        /// Gets a legal <see cref="PKM"/> from a random in-game encounter's data.
        /// </summary>
        /// <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>
        /// <param name="shiny"></param>
        /// <param name="alpha"></param>
        /// <param name="attempt"></param>
        /// <param name="pk">Result legal pkm</param>
        /// <returns>True if a valid result was generated, false if the result should be ignored.</returns>
        public static bool GetRandomEncounter(this ITrainerInfo tr, int species, int?form, bool shiny, bool alpha, ref int attempt, out PKM?pk)
        {
            var blank = PKMConverter.GetBlank(tr.Generation, tr.Game);

            pk = GetRandomEncounter(blank, tr, species, form, shiny, alpha, ref attempt);
            if (pk == null)
            {
                return(false);
            }

            pk = PKMConverter.ConvertToType(pk, blank.GetType(), out _);
            return(pk != null);
        }
Пример #10
0
        /// <summary>
        /// Gets a legal <see cref="PKM"/> from a random in-game encounter's data.
        /// </summary>
        /// <param name="tr">Trainer Data to use in generating the encounter</param>
        /// <param name="species">Species ID to generate</param>
        /// <param name="pk">Result legal pkm</param>
        /// <returns>True if a valid result was generated, false if the result should be ignored.</returns>
        public static bool GetRandomEncounter(this ITrainerInfo tr, int species, out PKM?pk)
        {
            var blank = PKMConverter.GetBlank(tr.Generation, tr.Game);

            pk = GetRandomEncounter(blank, tr, species);
            if (pk == null)
            {
                return(false);
            }

            pk = PKMConverter.ConvertToType(pk, blank.GetType(), out _);
            return(pk != null);
        }
Пример #11
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);
                var la   = new LegalityAnalysis(pkm);
                var spec = GameInfo.Strings.Species[template.Species];
                pkm = PKMConverter.ConvertToType(pkm, typeof(T), out _) ?? pkm;
                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);
            }
#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(TradeModule <T>));
                var msg = $"Oops! An unexpected problem happened with this Showdown Set:\n```{string.Join("\n", set.GetSetLines())}```";
                await ReplyAsync(msg).ConfigureAwait(false);
            }
        }
Пример #12
0
        private async Task <PKM> ImportFromClipboard()
        {
            var txt = await DataUtil.GetClipboardText().ConfigureAwait(false);

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

            try
            {
                var data = Convert.FromBase64String(txt);
                var pkm  = PKMConverter.GetPKMfromBytes(data, VM.SAV.Generation);
                if (pkm == null)
                {
                    await UserDialogs.Instance
                    .AlertAsync("Invalid data in device Clipboard!")
                    .ConfigureAwait(false);

                    return(null);
                }

                var converted = PKMConverter.ConvertToType(pkm, VM.SAV.PKMType, out var c);
                if (converted == null)
                {
                    await UserDialogs.Instance
                    .AlertAsync(c)
                    .ConfigureAwait(false);

                    return(null);
                }

                return(converted);
            }
            catch
            {
                await UserDialogs.Instance
                .AlertAsync("Invalid data in device Clipboard!")
                .ConfigureAwait(false);

                return(null);
            }
        }
Пример #13
0
        private static IEnumerable <PKM> GetPKMForSaveFile(this SaveFile SAV, IEnumerable <PKM> pks)
        {
            var savtype = SAV.PKMType;

            foreach (var temp in pks)
            {
                PKM pk = PKMConverter.ConvertToType(temp, savtype, out string c);

                if (pk == null)
                {
                    Debug.WriteLine(c); continue;
                }

                var compat = SAV.IsPKMCompatible(pk);
                if (compat.Length > 0)
                {
                    continue;
                }

                yield return(pk);
            }
        }
Пример #14
0
        // Important Events
        private void ClickView(object sender, EventArgs e)
        {
            int index = GetSenderIndex(sender);

            if (index < 0)
            {
                return;
            }
            var pk = Results[index].ConvertToPKM(SAV);

            pk = PKMConverter.ConvertToType(pk, SAV.PKMType, out var c);
            if (pk == null)
            {
                throw new FormatException(c); // shouldn't happen
            }
            SAV.AdaptPKM(pk);
            PKME_Tabs.PopulateFields(pk, false);
            slotSelected = index;
            slotColor    = SpriteUtil.Spriter.View;
            UpdateSlotColor(SCR_Box.Value);
            L_Viewed.Text = string.Format(Viewed, Results[index].FileName);
        }
Пример #15
0
        public async Task TradeAsync([Summary("Trade Code")] int code, [Summary("Showdown Set")][Remainder] string content)
        {
            const int gen = 8;

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

            var sav = AutoLegalityWrapper.GetTrainerInfo(gen);
            var pkm = sav.GetLegal(template, out var result);

            if (Info.Hub.Config.Trade.DittoTrade && pkm.Species == 132)
            {
                TradeExtensions.DittoTrade(pkm);
            }

            if (Info.Hub.Config.Trade.EggTrade && pkm.Nickname == "Egg")
            {
                TradeExtensions.EggTrade((PK8)pkm);
            }

            var la   = new LegalityAnalysis(pkm);
            var spec = GameInfo.Strings.Species[template.Species];

            pkm = PKMConverter.ConvertToType(pkm, typeof(PK8), out _) ?? pkm;
            if (Info.Hub.Config.Trade.Memes && await TrollAsync(pkm is not PK8 || !la.Valid, template).ConfigureAwait(false))
            {
                return;
            }
Пример #16
0
        public async Task TradeAsync([Summary("Trade Code")] int code, [Summary("Showdown Set")][Remainder] string content)
        {
            const int gen = 8;

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

            var sav = AutoLegalityWrapper.GetTrainerInfo(gen);

            var pkm  = sav.GetLegal(template, out var result);
            var la   = new LegalityAnalysis(pkm);
            var spec = GameInfo.Strings.Species[template.Species];

            pkm = PKMConverter.ConvertToType(pkm, typeof(PK8), out _) ?? pkm;
            if (pkm is not PK8 || !la.Valid)
            {
                var reason = result == "Timeout" ? "That set took too long to generate." : "I wasn't able to create something from that.";
                var imsg   = $"Oops! {reason} Here's my best attempt for that {spec}!";
                await Context.Channel.SendPKMAsync(pkm, imsg).ConfigureAwait(false);

                return;
            }

            pkm.ResetPartyStats();
            var sig = Context.User.GetFavor();

            await AddTradeToQueueAsync(code, Context.User.Username, (PK8)pkm, sig, Context.User).ConfigureAwait(false);
        }
Пример #17
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);
            }
        }
Пример #18
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);
        }
Пример #19
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);
                }
            }
        }
Пример #20
0
        /// <summary>
        /// Main function that auto legalizes based on the legality
        /// </summary>
        /// <remarks>Leverages <see cref="Core"/>'s <see cref="EncounterMovesetGenerator"/> to create a <see cref="PKM"/> from a <see cref="IBattleTemplate"/>.</remarks>
        /// <param name="dest">Destination for the generated pkm</param>
        /// <param name="template">rough pkm that has all the <see cref="set"/> values entered</param>
        /// <param name="set">Showdown set object</param>
        /// <param name="satisfied">If the final result is legal or not</param>
        public static PKM GetLegalFromTemplate(this ITrainerInfo dest, PKM template, IBattleTemplate set, out LegalizationResult satisfied)
        {
            RegenSet regen;

            if (set is RegenTemplate t)
            {
                t.FixGender(template.PersonalInfo);
                regen = t.Regen;
            }
            else
            {
                regen = RegenSet.Default;
            }

            template.ApplySetDetails(set);
            template.SetRecordFlags(); // Validate TR moves for the encounter
            var isHidden = template.AbilityNumber == 4;

            if (template.PersonalInfo.Abilities.Count > 2) // Hidden ability exists for the template
            {
                isHidden = isHidden || template.PersonalInfo.Abilities[2] == template.Ability;
            }
            var destType = template.GetType();
            var destVer  = (GameVersion)dest.Game;

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

            var timer    = Stopwatch.StartNew();
            var gamelist = FilteredGameList(template, destVer);

            var encounters = EncounterMovesetGenerator.GenerateEncounters(pk: template, moves: set.Moves, gamelist);
            var criteria   = EncounterCriteria.GetCriteria(set);

            foreach (var enc in encounters)
            {
                // Return out if set times out
                if (timer.Elapsed.TotalSeconds >= Timeout)
                {
                    timer.Stop();
                    satisfied = LegalizationResult.Timeout;
                    return(template);
                }

                // Look before we leap -- don't waste time generating invalid / incompatible junk.
                if (!IsEncounterValid(set, enc, isHidden, destVer))
                {
                    continue;
                }

                // Create the PKM from the template.
                var tr  = GetTrainer(regen, enc.Version, enc.Generation);
                var raw = enc.ConvertToPKM(tr, criteria);
                raw = raw.SanityCheckLocation(enc);
                if (raw.IsEgg) // PGF events are sometimes eggs. Force hatch them before proceeding
                {
                    raw.HandleEggEncounters(enc, tr);
                }

                raw.PreSetPIDIV(enc, set);

                // Transfer any VC1 via VC2, as there may be GSC exclusive moves requested.
                if (dest.Generation >= 7 && raw is PK1 basepk1)
                {
                    raw = basepk1.ConvertToPK2();
                }

                // Bring to the target generation, then apply final details.
                var pk = PKMConverter.ConvertToType(raw, destType, out _);
                if (pk == null)
                {
                    continue;
                }
                ApplySetDetails(pk, set, raw, dest, enc, regen);

                // Apply final tweaks to the data.
                if (pk is IGigantamax gmax && gmax.CanGigantamax != set.CanGigantamax)
                {
                    if (!gmax.CanToggleGigantamax(pk.Species, pk.Form, enc.Species, enc.Form))
                    {
                        continue;
                    }
                    gmax.CanGigantamax = set.CanGigantamax; // soup hax
                }

                // Try applying batch editor values.
                if (AllowBatchCommands && regen.HasBatchSettings)
                {
                    pk.RefreshChecksum();
                    var b = regen.Batch;
                    if (!BatchEditing.TryModify(pk, b.Filters, b.Instructions))
                    {
                        continue;
                    }
                }

                if (pk is PK1 pk1 && ParseSettings.AllowGen1Tradeback)
                {
                    pk1.Catch_Rate = pk1.Gen2Item; // Simulate a gen 2 trade/tradeback to allow tradeback moves
                }
                // Verify the Legality of what we generated, and exit if it is valid.
                var la = new LegalityAnalysis(pk);
                if (la.Valid)
                {
                    satisfied = LegalizationResult.Regenerated;
                    return(pk);
                }
                Debug.WriteLine($"{la.Report()}\n");
            }
            satisfied = LegalizationResult.Failed;
            return(template);
        }
Пример #21
0
        public static async Task <PKM> ScanQRPKM(SaveFile sav, INavigation nav)
        {
            var scanPage = new ZXingScannerPage
            {
                DefaultOverlayTopText    = "Hold camera up to QR code",
                DefaultOverlayBottomText = "Camera will automatically scan QR code/Barcode \r\n\rPress the 'Back' button to cancel"
            };

            scanPage.AutoFocus();

            PKM  pkm      = null;
            bool finished = false;

            scanPage.OnScanResult += async result =>
            {
                // disable scanning until message is acknowledged; if we get a good result, we're done scanning anyway
                scanPage.IsScanning = false;
                if (result.BarcodeFormat != BarcodeFormat.QR_CODE)
                {
                    await UserDialogs.Instance.AlertAsync("That's not a QR code.").ConfigureAwait(false);

                    scanPage.IsScanning = true;
                    return;
                }

                var pk = QRUtil.GetPKMFromQRMessage(result.Text, sav.Generation);
                if (pk == null)
                {
                    await UserDialogs.Instance.AlertAsync("Please scan a PKM QR code.").ConfigureAwait(false);

                    scanPage.IsScanning = true;
                    return;
                }

                pkm = PKMConverter.ConvertToType(pk, sav.PKMType, out var c);
                if (pkm == null)
                {
                    Console.WriteLine(c);
                    await UserDialogs.Instance.AlertAsync("Please scan a compatible PKM format QR code." + Environment.NewLine + $"Received {pk.GetType().Name}").ConfigureAwait(false);

                    scanPage.IsScanning = true;
                    return;
                }

                finished = true;
            };
            scanPage.Disappearing += (s, e) => finished = true;

            await nav.PushAsync(scanPage).ConfigureAwait(false);

            while (!finished)
            {
                await Task.Delay(100).ConfigureAwait(false);
            }
            if (pkm == null) // canceled
            {
                return(null);
            }
            Device.BeginInvokeOnMainThread(async() => await nav.PopAsync().ConfigureAwait(false));
            return(pkm);
        }
Пример #22
0
        /// <summary>
        /// Main function that auto legalizes based on the legality
        /// </summary>
        /// <remarks>Leverages <see cref="Core"/>'s <see cref="EncounterMovesetGenerator"/> to create a <see cref="PKM"/> from a <see cref="IBattleTemplate"/>.</remarks>
        /// <param name="dest">Destination for the generated pkm</param>
        /// <param name="template">rough pkm that has all the <see cref="set"/> values entered</param>
        /// <param name="set">Showdown set object</param>
        /// <param name="satisfied">If the final result is legal or not</param>
        public static PKM GetLegalFromTemplate(this ITrainerInfo dest, PKM template, IBattleTemplate set, out bool satisfied)
        {
            RegenSet regen;

            if (set is RegenTemplate t)
            {
                t.FixGender(template.PersonalInfo);
                regen = t.Regen;
            }
            else
            {
                regen = RegenSet.Default;
            }

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

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

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

            if (PrioritizeGame)
            {
                gamelist = PrioritizeGameVersion == GameVersion.Any ? PrioritizeVersion(gamelist, destVer) : PrioritizeVersion(gamelist, PrioritizeGameVersion);
            }

            var encounters = EncounterMovesetGenerator.GenerateEncounters(pk: template, moves: set.Moves, gamelist);

            foreach (var enc in encounters)
            {
                // Look before we leap -- don't waste time generating invalid / incompatible junk.
                if (!IsEncounterValid(set, enc, isHidden, destVer, out var ver))
                {
                    continue;
                }

                // Create the PKM from the template.
                var tr  = GetTrainer(regen, ver, enc.Generation);
                var raw = SanityCheckEncounters(enc).ConvertToPKM(tr);
                if (raw.IsEgg) // PGF events are sometimes eggs. Force hatch them before proceeding
                {
                    raw.HandleEggEncounters(enc, tr);
                }

                // Bring to the target generation, then apply final details.
                var pk = PKMConverter.ConvertToType(raw, destType, out _);
                if (pk == null)
                {
                    continue;
                }
                ApplySetDetails(pk, set, raw, dest, enc, regen);

                // Apply final tweaks to the data.
                if (pk is IGigantamax gmax && gmax.CanGigantamax != set.CanGigantamax)
                {
                    if (!gmax.CanToggleGigantamax(pk.Species, enc.Species))
                    {
                        continue;
                    }
                    gmax.CanGigantamax = set.CanGigantamax; // soup hax
                }

                // Try applying batch editor values.
                if (AllowBatchCommands && regen.HasBatchSettings)
                {
                    pk.RefreshChecksum();
                    var b = regen.Batch;
                    if (!BatchEditing.TryModify(pk, b.Filters, b.Instructions))
                    {
                        continue;
                    }
                }

                if (pk is PK1 pk1 && ParseSettings.AllowGen1Tradeback)
                {
                    pk1.Catch_Rate = pk1.Gen2Item; // Simulate a gen 2 trade/tradeback to allow tradeback moves
                }
                // Verify the Legality of what we generated, and exit if it is valid.
                var la = new LegalityAnalysis(pk);
                if (la.Valid)
                {
                    satisfied = true;
                    return(pk);
                }
                Debug.WriteLine($"{la.Report()}\n");
            }
            satisfied = false;
            return(template);
        }
Пример #23
0
        /// <summary>
        /// Main function that auto legalizes based on the legality
        /// </summary>
        /// <param name="roughPK">rough pkm that has all the SSet values entered</param>
        /// <param name="SSet">Showdown set object</param>
        /// <param name="satisfied">If the final result is satisfactory, otherwise use current auto legality functionality</param>
        /// <returns></returns>
        public static PKM APILegality(PKM roughPK, ShowdownSet SSet, out bool satisfied)
        {
            bool changedForm = false;

            if (SSet.Form != null)
            {
                changedForm = FixFormes(SSet, out SSet);
            }
            satisfied = false; // true when all features of the PKM are satisfied
            int Form = roughPK.AltForm;

            if (changedForm)
            {
                Form = SSet.FormIndex;
                roughPK.ApplySetDetails(SSet);
            }
            int HPType = roughPK.HPType;

            // List of candidate PKM files

            int[] moves = SSet.Moves;
            var   f     = GeneratePKMs(roughPK, SAV, moves);

            foreach (PKM pkmn in f)
            {
                if (pkmn != null)
                {
                    PKM       pk     = PKMConverter.ConvertToType(pkmn, SAV.PKMType, out _); // All Possible PKM files
                    LegalInfo info   = new LegalInfo(pk);
                    var       pidiv  = info.PIDIV ?? MethodFinder.Analyze(pk);
                    PIDType   Method = PIDType.None;
                    if (pidiv != null)
                    {
                        Method = pidiv.Type;
                    }
                    SetVersion(pk, pkmn); // PreEmptive Version setting
                    SetSpeciesLevel(pk, SSet, Form);
                    SetMovesEVsItems(pk, SSet);
                    SetTrainerDataAndMemories(pk);
                    SetNatureAbility(pk, SSet);
                    SetIVsPID(pk, SSet, Method, HPType, pkmn);
                    PrintLegality(pk);
                    ColosseumFixes(pk);
                    pk.SetSuggestedHyperTrainingData(pk.IVs); // Hypertrain
                    SetEncryptionConstant(pk);
                    SetShinyBoolean(pk, SSet.Shiny);
                    CheckAndSetFateful(pk);
                    FixGender(pk, SSet);
                    FixRibbons(pk);
                    FixMemoriesPKM(pk);
                    SetSpeciesBall(pk);
                    SetHappiness(pk);
                    LegalityAnalysis la = new LegalityAnalysis(pk);
                    if (la.Valid)
                    {
                        satisfied = true;
                    }
                    if (satisfied)
                    {
                        return(pk);
                    }
                    else
                    {
                        Console.WriteLine(la.Report());
                    }
                }
            }
            return(roughPK);
        }
Пример #24
0
        /// <summary>
        /// Loads a folder of files to the <see cref="SaveFile"/>.
        /// </summary>
        /// <param name="SAV"><see cref="SaveFile"/> to load folder to.</param>
        /// <param name="path">Folder to load <see cref="PKM"/> files from. Files are only loaded from the top directory.</param>
        /// <param name="result">Result message from the method.</param>
        /// <param name="boxStart">First box to start loading to. All prior boxes are not modified.</param>
        /// <param name="boxClear">Instruction to clear boxes after the starting box.</param>
        /// <param name="noSetb">Bypass option to not modify <see cref="PKM"/> properties when setting to Save File.</param>
        /// <returns></returns>
        public static bool LoadBoxes(this SaveFile SAV, string path, out string result, int boxStart = 0, bool boxClear = false, bool?noSetb = null)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                result = "Invalid path specified."; return(false);
            }
            if (!SAV.HasBox)
            {
                result = "Save file does not have boxes."; return(false);
            }

            if (boxClear)
            {
                SAV.ClearBoxes(boxStart);
            }

            int startCount = boxStart * SAV.BoxSlotCount;
            int maxCount   = SAV.BoxCount * SAV.BoxSlotCount;
            int ctr        = startCount;
            int pastctr    = 0;
            var filepaths  = Directory.EnumerateFiles(path, "*.*", SearchOption.TopDirectoryOnly);

            foreach (var file in filepaths)
            {
                if (!PKX.IsPKM(new FileInfo(file).Length))
                {
                    continue;
                }

                // Check for format compatibility with save; if transfer is necessary => convert.
                // format conversion comment
                byte[] data = File.ReadAllBytes(file);
                PKM    temp = PKMConverter.GetPKMfromBytes(data, prefer: SAV.Generation);
                PKM    pk   = PKMConverter.ConvertToType(temp, SAV.PKMType, out string c);

                if (pk == null)
                {
                    Debug.WriteLine(c); continue;
                }

                if (SAV.IsPKMCompatible(pk).Length > 0)
                {
                    continue;
                }

                while (SAV.IsSlotLocked(ctr / SAV.BoxSlotCount, ctr % SAV.BoxSlotCount))
                {
                    ctr++;
                }

                int offset = SAV.GetBoxOffset(ctr / SAV.BoxSlotCount) + ctr % SAV.BoxSlotCount * SAV.SIZE_STORED;
                SAV.SetStoredSlot(pk, offset, noSetb);
                if (pk.Format != temp.Format) // Transferred
                {
                    pastctr++;
                }
                if (++ctr == maxCount) // Boxes full!
                {
                    break;
                }
            }

            ctr -= startCount; // actual imported count
            if (ctr <= 0)
            {
                result = "No files loaded"; return(false);
            }

            result = $"Loaded {ctr} files to boxes.";
            if (pastctr > 0)
            {
                result += Environment.NewLine + $"Conversion successful for {pastctr} past generation files.";
            }

            return(true);
        }