Ejemplo n.º 1
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
            var pokemons = await session.Inventory.GetPokemons().ConfigureAwait(false);

            if (session.LogicSettings.TransferDuplicatePokemon && session.LogicSettings.RenamePokemonRespectTransferRule)
            {
                var duplicatePokemons = await
                                        session.Inventory.GetDuplicatePokemonToTransfer(
                    session.LogicSettings.PokemonsNotToTransfer,
                    session.LogicSettings.PokemonEvolveFilters,
                    session.LogicSettings.KeepPokemonsThatCanEvolve,
                    session.LogicSettings.PrioritizeIvOverCp).ConfigureAwait(false);

                pokemons = pokemons.Where(x => !duplicatePokemons.Any(p => p.Id == x.Id));
            }

            if (session.LogicSettings.TransferWeakPokemon && session.LogicSettings.RenamePokemonRespectTransferRule)
            {
                var weakPokemons = await
                                   session.Inventory.GetWeakPokemonToTransfer(
                    session.LogicSettings.PokemonsNotToTransfer,
                    session.LogicSettings.PokemonEvolveFilters,
                    session.LogicSettings.KeepPokemonsThatCanEvolve).ConfigureAwait(false);

                pokemons = pokemons.Where(x => !weakPokemons.Any(p => p.Id == x.Id));
            }
            foreach (var pokemon in pokemons)
            {
                cancellationToken.ThrowIfCancellationRequested();
                TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
                var perfection  = Math.Round(PokemonInfo.CalculatePokemonPerfection(pokemon));
                var level       = PokemonInfo.GetLevel(pokemon);
                var pokemonName = session.Translation.GetPokemonTranslation(pokemon.PokemonId);
                var cp          = PokemonInfo.CalculateCp(pokemon);
                // iv number + templating part + pokemonName <= 12

                var newNickname = session.LogicSettings.RenameTemplate.ToUpper();
                newNickname = newNickname.Replace("{IV}", Math.Round(perfection, 0).ToString());
                newNickname = newNickname.Replace("{LEVEL}", Math.Round(level, 0).ToString());
                newNickname = newNickname.Replace("{CP}", cp.ToString());

                var nameLength = 18 - newNickname.Length;
                if (pokemonName.Length > nameLength && nameLength > 0)
                {
                    pokemonName = pokemonName.Substring(0, nameLength);
                }

                newNickname = newNickname.Replace("{NAME}", pokemonName);

                //verify
                if (nameLength <= 0)
                {
                    Logger.Write($"Your rename template : {session.LogicSettings.RenameTemplate} incorrect. : {pokemonName} / {newNickname}");
                    continue;
                }
                var oldNickname = pokemon.Nickname.Length != 0 ? pokemon.Nickname : pokemon.PokemonId.ToString();

                // If "RenameOnlyAboveIv" = true only rename pokemon with IV over "KeepMinIvPercentage"
                if ((!session.LogicSettings.RenameOnlyAboveIv ||
                     perfection >= session.LogicSettings.KeepMinIvPercentage) &&
                    newNickname != oldNickname)
                {
                    var result = await session.Client.Inventory.NicknamePokemon(pokemon.Id, newNickname).ConfigureAwait(false);

                    if (result.Result == NicknamePokemonResponse.Types.Result.Success)
                    {
                        pokemon.Nickname = newNickname;

                        session.EventDispatcher.Send(new RenamePokemonEvent
                        {
                            Id          = pokemon.Id,
                            PokemonId   = pokemon.PokemonId,
                            OldNickname = oldNickname,
                            NewNickname = newNickname
                        });
                    }
                    //Delay only if the pokemon was really renamed!
                    await DelayingUtils.DelayAsync(session.LogicSettings.RenamePokemonActionDelay, 500, session.CancellationTokenSource.Token).ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 2
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken, dynamic encounter, MapPokemon pokemon,
                                         FortData currentFortData = null, ulong encounterId = 0)
        {
            AmountOfBerries = 0;
            cancellationToken.ThrowIfCancellationRequested();

            // If the encounter is null nothing will work below, so exit now
            if (encounter == null)
            {
                return;
            }

            if (CatchThresholdExceeds(session))
            {
                return;
            }

            float probability = encounter.CaptureProbability?.CaptureProbability_[0];

            // Check for pokeballs before proceeding
            var pokeball = await GetBestBall(session, encounter, probability);

            if (pokeball == ItemId.ItemUnknown)
            {
                return;
            }

            //Calculate CP and IV
            var pokemonCp = (encounter is EncounterResponse
                               ? encounter.WildPokemon?.PokemonData?.Cp
                               : encounter.PokemonData?.Cp);
            var pokemonIv = PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse
                    ? encounter.WildPokemon?.PokemonData
                    : encounter?.PokemonData);

            // Calculate distance away
            var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                   session.Client.CurrentLongitude,
                                                                   encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.Latitude
                    : currentFortData.Latitude,
                                                                   encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.Longitude
                    : currentFortData.Longitude);

            CatchPokemonResponse caughtPokemonResponse;
            var attemptCounter = 1;


            var myPokemon = await session.Inventory.GetPokemons();

            var  myPokemonList   = myPokemon.ToList();
            bool bolExistPokemon = false;
            var  pokemonId       = encounter is EncounterResponse
            ? encounter.WildPokemon?.PokemonData?.PokemonId
            : encounter?.PokemonData?.PokemonId;

            foreach (var itemPokemon in myPokemonList)
            {
                if (itemPokemon.PokemonId == pokemonId)
                {
                    bolExistPokemon = true;
                }
            }
            if (bolExistPokemon == true)
            {
                if (pokemonCp < 1000 || pokemonIv < 80)
                {
                    DelayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 0);
                    Logger.Write("CP : " + pokemonCp + " IV : " + pokemonIv + " 太低不抓,寶貝名稱 : " + pokemonId);
                    return;
                }
            }

            do
            {
                if ((session.LogicSettings.MaxPokeballsPerPokemon > 0 &&
                     attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon))
                {
                    break;
                }

                pokeball = await GetBestBall(session, encounter, probability);

                if (pokeball == ItemId.ItemUnknown)
                {
                    session.EventDispatcher.Send(new NoPokeballEvent
                    {
                        Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId,
                        Cp =
                            (encounter is EncounterResponse
                                ? encounter.WildPokemon?.PokemonData?.Cp
                                : encounter?.PokemonData?.Cp) ?? 0
                    });
                    return;
                }

                // Determine whether to use berries or not
                if ((session.LogicSettings.UseBerriesOperator.ToLower().Equals("and") &&
                     pokemonIv >= session.LogicSettings.UseBerriesMinIv &&
                     pokemonCp >= session.LogicSettings.UseBerriesMinCp &&
                     probability < session.LogicSettings.UseBerriesBelowCatchProbability) ||
                    (session.LogicSettings.UseBerriesOperator.ToLower().Equals("or") && (
                         pokemonIv >= session.LogicSettings.UseBerriesMinIv ||
                         pokemonCp >= session.LogicSettings.UseBerriesMinCp ||
                         probability < session.LogicSettings.UseBerriesBelowCatchProbability)))
                {
                    AmountOfBerries++;
                    if (AmountOfBerries <= session.LogicSettings.MaxBerriesToUsePerPokemon)
                    {
                        await
                        UseBerry(session,
                                 encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                 ?pokemon.EncounterId
                                 : encounterId,
                                 encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                 ?pokemon.SpawnPointId
                                 : currentFortData?.Id);
                    }
                }

                //default to excellent throw
                var normalizedRecticleSize = 1.95;
                //default spin
                var spinModifier = 1.0;

                //Humanized throws
                if (session.LogicSettings.EnableHumanizedThrows)
                {
                    //thresholds: https://gist.github.com/anonymous/077d6dea82d58b8febde54ae9729b1bf
                    var spinTxt = "Curve";
                    var hitTxt  = "Excellent";
                    if (pokemonCp > session.LogicSettings.ForceExcellentThrowOverCp ||
                        pokemonIv > session.LogicSettings.ForceExcellentThrowOverIv)
                    {
                        normalizedRecticleSize = Random.NextDouble() * (1.95 - 1.7) + 1.7;
                    }
                    else if (pokemonCp >= session.LogicSettings.ForceGreatThrowOverCp ||
                             pokemonIv >= session.LogicSettings.ForceGreatThrowOverIv)
                    {
                        normalizedRecticleSize = Random.NextDouble() * (1.95 - 1.3) + 1.3;
                        hitTxt = "Great";
                    }
                    else
                    {
                        var regularThrow = 100 - (session.LogicSettings.ExcellentThrowChance +
                                                  session.LogicSettings.GreatThrowChance +
                                                  session.LogicSettings.NiceThrowChance);
                        var rnd = Random.Next(1, 101);

                        if (rnd <= regularThrow)
                        {
                            normalizedRecticleSize = Random.NextDouble() * (1 - 0.1) + 0.1;
                            hitTxt = "Ordinary";
                        }
                        else if (rnd <= regularThrow + session.LogicSettings.NiceThrowChance)
                        {
                            normalizedRecticleSize = Random.NextDouble() * (1.3 - 1) + 1;
                            hitTxt = "Nice";
                        }
                        else if (rnd <=
                                 regularThrow + session.LogicSettings.NiceThrowChance +
                                 session.LogicSettings.GreatThrowChance)
                        {
                            normalizedRecticleSize = Random.NextDouble() * (1.7 - 1.3) + 1.3;
                            hitTxt = "Great";
                        }

                        if (Random.NextDouble() * 100 > session.LogicSettings.CurveThrowChance)
                        {
                            spinModifier = 0.0;
                            spinTxt      = "Straight";
                        }
                    }

                    //round to 2 decimals
                    normalizedRecticleSize = Math.Round(normalizedRecticleSize, 2);

                    Logger.Write($"(Threw ball) {hitTxt} hit. {spinTxt}-ball...", LogLevel.Debug);
                }

                int  missChance = Random.Next(0, 101);
                bool hitPokemon = true;
                if (missChance <= session.LogicSettings.ThrowMissPercentage && session.LogicSettings.EnableMissedThrows && session.LogicSettings.EnableHumanizedThrows)
                {
                    hitPokemon = false;
                }
                caughtPokemonResponse =
                    await session.Client.Encounter.CatchPokemon(
                        encounter is EncounterResponse || encounter is IncenseEncounterResponse
                        ?pokemon.EncounterId
                        : encounterId,
                        encounter is EncounterResponse || encounter is IncenseEncounterResponse
                        ?pokemon.SpawnPointId
                        : currentFortData.Id, pokeball, normalizedRecticleSize, spinModifier, hitPokemon);

                var lat = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                             ? pokemon.Latitude : currentFortData.Latitude;
                var lng = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                            ? pokemon.Longitude : currentFortData.Longitude;
                var evt = new PokemonCaptureEvent()
                {
                    Status    = caughtPokemonResponse.Status,
                    Latitude  = lat,
                    Longitude = lng
                };

                if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                {
                    var totalExp = 0;

                    foreach (var xp in caughtPokemonResponse.CaptureAward.Xp)
                    {
                        totalExp += xp;
                    }
                    var profile = await session.Client.Player.GetPlayer();

                    evt.Exp      = totalExp;
                    evt.Stardust = profile.PlayerData.Currencies.ToArray()[1].Amount;
                    evt.UniqueId = caughtPokemonResponse.CapturedPokemonId;

                    var pokemonSettings = await session.Inventory.GetPokemonSettings();

                    var pokemonFamilies = await session.Inventory.GetPokemonFamilies();

                    var setting =
                        pokemonSettings.FirstOrDefault(q => pokemon != null && q.PokemonId == pokemon.PokemonId);
                    var family = pokemonFamilies.FirstOrDefault(q => setting != null && q.FamilyId == setting.FamilyId);

                    if (family != null)
                    {
                        family.Candy_ += caughtPokemonResponse.CaptureAward.Candy.Sum();

                        evt.FamilyCandies = family.Candy_;
                    }
                    else
                    {
                        evt.FamilyCandies = caughtPokemonResponse.CaptureAward.Candy.Sum();
                    }
                    session.Stats.PokemonTimestamps.Add(DateTime.Now.Ticks);
                }

                evt.CatchType = encounter is EncounterResponse
                    ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal)
                    : encounter is DiskEncounterResponse
                        ? session.Translation.GetTranslation(TranslationString.CatchTypeLure)
                        : session.Translation.GetTranslation(TranslationString.CatchTypeIncense);

                evt.CatchTypeText = encounter is EncounterResponse
                    ? "normal"
                    : encounter is DiskEncounterResponse
                        ? "lure"
                        : "incense";
                evt.Id = encounter is EncounterResponse
                    ? pokemon.PokemonId : encounter?.PokemonData.PokemonId;
                evt.EncounterId = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.EncounterId
                    : encounterId;
                evt.Move1 = PokemonInfo.GetPokemonMove1(encounter is EncounterResponse
                    ? encounter.WildPokemon?.PokemonData
                    : encounter?.PokemonData);
                evt.Move2 = PokemonInfo.GetPokemonMove2(encounter is EncounterResponse
                    ? encounter.WildPokemon?.PokemonData
                    : encounter?.PokemonData);
                evt.Expires      = pokemon?.ExpirationTimestampMs ?? 0;
                evt.SpawnPointId = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.SpawnPointId
                    : currentFortData?.Id;
                evt.Level =
                    PokemonInfo.GetLevel(encounter is EncounterResponse
                        ? encounter.WildPokemon?.PokemonData
                        : encounter?.PokemonData);
                evt.Cp = encounter is EncounterResponse
                    ? encounter.WildPokemon?.PokemonData?.Cp
                    : encounter?.PokemonData?.Cp ?? 0;
                evt.MaxCp =
                    PokemonInfo.CalculateMaxCp(encounter is EncounterResponse
                        ? encounter.WildPokemon?.PokemonData
                        : encounter?.PokemonData);
                evt.Perfection =
                    Math.Round(
                        PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse
                            ? encounter.WildPokemon?.PokemonData
                            : encounter?.PokemonData));
                evt.Probability =
                    Math.Round(probability * 100, 2);
                evt.Distance = distance;
                evt.Pokeball = pokeball;
                evt.Attempt  = attemptCounter;
                await session.Inventory.RefreshCachedInventory();

                evt.BallAmount = await session.Inventory.GetItemAmountByType(pokeball);

                session.EventDispatcher.Send(evt);

                attemptCounter++;

                if (session.LogicSettings.TransferDuplicatePokemonOnCapture && session.LogicSettings.TransferDuplicatePokemon)
                {
                    if (session.LogicSettings.UseNearActionRandom)
                    {
                        await HumanRandomActionTask.TransferRandom(session, cancellationToken);
                    }
                    else
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                    }
                }

                DelayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 0);
            } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed ||
                     caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape);
        }
Ejemplo n.º 3
0
        public async Task <IEnumerable <PokemonData> > GetDuplicatePokemonToTransfer(
            IEnumerable <PokemonId> pokemonsNotToTransfer, Dictionary <PokemonId, EvolveFilter> pokemonEvolveFilters,
            bool keepPokemonsThatCanEvolve = false, bool prioritizeIVoverCp = false
            )
        {
            var session   = TinyIoCContainer.Current.Resolve <ISession>();
            var myPokemon = await GetPokemons().ConfigureAwait(false);

            var pokemonToTransfer = myPokemon.Where(p => !pokemonsNotToTransfer.Contains(p.PokemonId) && CanTransferPokemon(p));

            try
            {
                pokemonToTransfer =
                    pokemonToTransfer.Where(
                        p =>
                {
                    var pokemonTransferFilter = session.LogicSettings.PokemonsTransferFilter.GetFilter <TransferFilter>(p.PokemonId);

                    return(!pokemonTransferFilter.MovesOperator.BoolFunc(
                               pokemonTransferFilter.MovesOperator.ReverseBoolFunc(
                                   pokemonTransferFilter.MovesOperator.InverseBool(
                                       pokemonTransferFilter.Moves.Count > 0),
                                   pokemonTransferFilter.Moves.Any(moveset =>
                                                                   pokemonTransferFilter.MovesOperator.ReverseBoolFunc(
                                                                       pokemonTransferFilter.MovesOperator.InverseBool(moveset.Count > 0),
                                                                       moveset.Intersect(new[] { p.Move1, p.Move2 }).Count() ==
                                                                       Math.Max(Math.Min(moveset.Count, 2), 0)))),
                               pokemonTransferFilter.KeepMinOperator.BoolFunc(
                                   p.Cp >= pokemonTransferFilter.KeepMinCp,
                                   PokemonInfo.CalculatePokemonPerfection(p) >=
                                   pokemonTransferFilter.KeepMinIvPercentage,
                                   pokemonTransferFilter.KeepMinOperator.ReverseBoolFunc(
                                       pokemonTransferFilter.KeepMinOperator.InverseBool(pokemonTransferFilter
                                                                                         .UseKeepMinLvl),
                                       PokemonInfo.GetLevel(p) >= pokemonTransferFilter.KeepMinLvl))));
                })
                    .ToList();
            }
            catch (ActiveSwitchByRuleException e)
            {
                throw e;
            }

            var results         = new List <PokemonData>();
            var pokemonToEvolve = await GetPokemonToEvolve(pokemonEvolveFilters).ConfigureAwait(false);

            foreach (var pokemonGroupToTransfer in pokemonToTransfer.GroupBy(p => p.PokemonId).ToList())
            {
                var amountToKeepInStorage = Math.Max(GetApplyFilter <TransferFilter>(session.LogicSettings.PokemonsTransferFilter, pokemonGroupToTransfer.Key).KeepMinDuplicatePokemon, 0);
                var inStorage             = myPokemon.Count(data => data.PokemonId == pokemonGroupToTransfer.Key);
                var needToRemove          = inStorage - amountToKeepInStorage;

                if (needToRemove <= 0)
                {
                    continue;
                }

                var weakPokemonCount = pokemonGroupToTransfer.Count();
                var canBeRemoved     = Math.Min(needToRemove, weakPokemonCount);

                // Adjust canBeRemoved by subtracting the number of evolve pokemon we are saving.
                var pokemonToEvolveForThisGroup = pokemonToEvolve.Where(p => p.PokemonId == pokemonGroupToTransfer.Key);
                var numToSaveForEvolve          = pokemonGroupToTransfer.Count(p => pokemonToEvolveForThisGroup.Any(p2 => p2.Id == p.Id));
                canBeRemoved -= numToSaveForEvolve;
                var PokemonId = session.Translation.GetPokemonTranslation(pokemonGroupToTransfer.Key);

                Logger.Write($"Saving {numToSaveForEvolve,2:#0} {PokemonId,-12} for evolve. Number of {PokemonId,-12} to be transferred: {canBeRemoved,2:#0}", Logic.Logging.LogLevel.Info);

                if (prioritizeIVoverCp)
                {
                    results.AddRange(pokemonGroupToTransfer
                                     .Where(p => !pokemonToEvolveForThisGroup.Any(p2 => p2.Id == p.Id)) // Remove pokemon to evolve from the transfer list.
                                     .OrderBy(PokemonInfo.CalculatePokemonPerfection)
                                     .ThenBy(n => n.Cp)
                                     .Take(canBeRemoved));
                }
                else
                {
                    results.AddRange(pokemonGroupToTransfer
                                     .Where(p => !pokemonToEvolveForThisGroup.Any(p2 => p2.Id == p.Id)) // Remove pokemon to evolve from the transfer list.
                                     .OrderBy(x => x.Cp)
                                     .ThenBy(PokemonInfo.CalculatePokemonPerfection)
                                     .Take(canBeRemoved));
                }
            }
            return(results);
        }
Ejemplo n.º 4
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();

            try
            {
                var playerStats = (await session.Inventory.GetPlayerStats().ConfigureAwait(false)).FirstOrDefault();
                if (playerStats == null)
                {
                    return;
                }

                var incubators = (await session.Inventory.GetEggIncubators().ConfigureAwait(false))
                                 .Where(x => x.UsesRemaining > 0 || x.ItemId == ItemId.ItemIncubatorBasicUnlimited)
                                 .OrderByDescending(x => x.ItemId == ItemId.ItemIncubatorBasicUnlimited)
                                 .ToList();

                var unusedEggs = (await session.Inventory.GetEggs().ConfigureAwait(false))
                                 .Where(x => string.IsNullOrEmpty(x.EggIncubatorId))
                                 .OrderBy(x => x.EggKmWalkedTarget - x.EggKmWalkedStart)
                                 .ToList();

                var rememberedIncubatorsFilePath = Path.Combine(session.LogicSettings.ProfilePath, "temp", "incubators.json");
                var rememberedIncubators         = GetRememberedIncubators(rememberedIncubatorsFilePath);
                var pokemons = (await session.Inventory.GetPokemons().ConfigureAwait(false)).ToList();
                var eggIncubatorStatusEvent = new EggIncubatorStatusEvent();

                // Check if eggs in remembered incubator usages have since hatched
                // (instead of calling session.Client.Inventory.GetHatchedEgg(), which doesn't seem to work properly)
                foreach (var incubator in rememberedIncubators)
                {
                    var hatched = pokemons.FirstOrDefault(x => !x.IsEgg && x.Id == incubator.PokemonId);
                    if (hatched == null)
                    {
                        continue;
                    }

                    //Still Needs some work - TheWizard1328

                    var KMs         = playerStats.KmWalked - kmWalked;                  // playerStats.KmWalked - hatched.EggKmWalkedStart; // Total Km Walked(hatched.EggKmWalkedStart=0)
                    var stardust1   = session.Inventory.GetStarDust();                  // Total trainer Stardust
                    var stardust2   = session.RuntimeStatistics.TotalStardust;          // Total trainer Stardust
                    var ExpAwarded1 = playerStats.Experience;                           // Total Player Exp - TheWizard1328
                    var ExpAwarded2 = session.RuntimeStatistics.TotalExperience;        // Session Exp - TheWizard1328
                    var TotCandy    = session.Inventory.GetCandyCount(hatched.PokemonId);
                    //Temp logger line personal testing info - TheWizard1328
#if DEBUG
                    Logger.Write($"Hatch: eISE.KmWalked: {eggIncubatorStatusEvent.KmWalked:0.00} | eISE.KmToWalk: {eggIncubatorStatusEvent.KmToWalk:0.00} | " +
                                 $"XP1: {ExpAwarded1} | XP2: {ExpAwarded2} | SD1: {stardust1} | SD2: {stardust2}", LogLevel.Egg, ConsoleColor.DarkYellow);
#endif
                    if (session.LogicSettings.NotificationConfig.EnablePushBulletNotification)
                    {
                        await PushNotificationClient.SendNotification(session, $"Egg has hatched.", $"Pokemon: {hatched.PokemonId}\n" +
                                                                      $"Lvl: {PokemonInfo.GetLevel(hatched)}\n" +
                                                                      $"CP:  {hatched.Cp}\n" +
                                                                      $"IV:  {Math.Round(PokemonInfo.CalculatePokemonPerfection(hatched), 2)}\n", true).ConfigureAwait(false);
                    }

                    session.EventDispatcher.Send(new EggHatchedEvent
                    {
                        Dist       = KMs, //Still working on this - TheWizard1328
                        Id         = hatched.Id,
                        PokemonId  = hatched.PokemonId,
                        Level      = PokemonInfo.GetLevel(hatched),
                        Cp         = hatched.Cp,
                        MaxCp      = PokemonInfo.CalculateMaxCp(hatched.PokemonId),
                        Perfection = Math.Round(PokemonInfo.CalculatePokemonPerfection(hatched), 2),
                        HXP        = ExpAwarded1,
                        HSD        = stardust2, // This still needs work too to display the total SD after hatching - TheWizard1328
                        HCandy     = await TotCandy,
                    });
                }

                var newRememberedIncubators = new List <IncubatorUsage>();
                var eggs = 0;

                foreach (var incubator in incubators)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
                    eggs += 1;

                    if (incubator.PokemonId == 0)
                    {
                        // Unlimited incubators prefer short eggs, limited incubators prefer long eggs
                        // Special case: If only one incubator is available at all, it will prefer long eggs
                        var egg = (incubator.ItemId == ItemId.ItemIncubatorBasicUnlimited && incubators.Count > 1)
                            ? unusedEggs.FirstOrDefault()
                            : unusedEggs.LastOrDefault();

                        if (egg == null)
                        {
                            continue;
                        }

                        // Skip (save) limited incubators depending on user choice in config
                        if (!session.LogicSettings.UseLimitedEggIncubators &&
                            incubator.ItemId != ItemId.ItemIncubatorBasicUnlimited)
                        {
                            continue;
                        }

                        var response = await session.Client.Inventory.UseItemEggIncubator(incubator.Id, egg.Id).ConfigureAwait(false);

                        unusedEggs.Remove(egg);

                        newRememberedIncubators.Add(new IncubatorUsage {
                            IncubatorId = incubator.Id, PokemonId = egg.Id
                        });

                        session.EventDispatcher.Send(new EggIncubatorStatusEvent
                        {
                            Eggs        = eggs,
                            IncubatorId = incubator.Id,
                            WasAddedNow = true,
                            PokemonId   = egg.Id,
                            KmToWalk    = egg.EggKmWalkedTarget,
                            KmRemaining = response.EggIncubator.TargetKmWalked - kmWalked
                        });
                    }
                    else
                    {
                        newRememberedIncubators.Add(new IncubatorUsage
                        {
                            IncubatorId = incubator.Id,
                            PokemonId   = incubator.PokemonId
                        });

                        session.EventDispatcher.Send(new EggIncubatorStatusEvent
                        {
                            Eggs        = eggs,
                            IncubatorId = incubator.Id,
                            PokemonId   = incubator.PokemonId,
                            KmToWalk    = incubator.TargetKmWalked - incubator.StartKmWalked,
                            KmRemaining = incubator.TargetKmWalked - kmWalked
                        });
                    }
                }

                if (!newRememberedIncubators.SequenceEqual(rememberedIncubators))
                {
                    SaveRememberedIncubators(newRememberedIncubators, rememberedIncubatorsFilePath);
                }
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 5
0
        private static void StartIncubation()
        {
            try
            {
                if (GlobalVars.RelocateDefaultLocation)
                {
                    return;
                }
                var inventory  = Logic.objClient.Inventory.GetInventory();
                var incubators = Logic.objClient.Inventory.GetEggIncubators().ToList();
                var unusedEggs = (Logic.objClient.Inventory.GetEggs()).Where(x => string.IsNullOrEmpty(x.EggIncubatorId)).OrderBy(x => x.EggKmWalkedTarget - x.EggKmWalkedStart).ToList();
                var pokemons   = (Logic.objClient.Inventory.GetPokemons()).ToList();

                var playerStats = Logic.objClient.Inventory.GetPlayerStats();
                var stats       = playerStats.First();

                var kmWalked = stats.KmWalked;

                var logs = Path.Combine(logPath, "EggLog.txt");
                var date = DateTime.Now.ToString();

                var unusedEggsBasicInc   = eggsHatchingAllowedBasicInc(unusedEggs);
                var unusedEggsUnlimitInc = eggsHatchingAllowed(unusedEggs);

                foreach (var incubator in rememberedIncubators)
                {
                    var hatched = pokemons.FirstOrDefault(x => !x.IsEgg && x.Id == incubator.PokemonId);
                    if (hatched == null)
                    {
                        continue;
                    }

                    if (GlobalVars.LogEggs)
                    {
                        var MaxCP     = PokemonInfo.CalculateMaxCP(hatched);
                        var Level     = PokemonInfo.GetLevel(hatched);
                        var IVPercent = PokemonInfo.CalculatePokemonPerfection(hatched).ToString("0.00");
                        File.AppendAllText(logs, $"[{date}] - Egg hatched and we got a {hatched.PokemonId} (CP: {hatched.Cp} | MaxCP: {MaxCP} | Level: {Level} | IV: {IVPercent}% )" + Environment.NewLine);
                    }
                    Logger.ColoredConsoleWrite(ConsoleColor.DarkYellow, "Egg hatched and we got a " + hatched.PokemonId + " CP: " + hatched.Cp + " MaxCP: " + PokemonInfo.CalculateMaxCP(hatched) + " Level: " + PokemonInfo.GetLevel(hatched) + " IV: " + PokemonInfo.CalculatePokemonPerfection(hatched).ToString("0.00") + "%");
                }

                if ((unusedEggsUnlimitInc.Count < 1) && (unusedEggsUnlimitInc.Count < 1))
                {
                    Logger.ColoredConsoleWrite(ConsoleColor.DarkYellow, "There are not Allowed Eggs to hatch");
                    return;
                }

                var newRememberedIncubators = new List <IncubatorUsage>();

                foreach (EggIncubator incubator in incubators)
                {
                    if (incubator.PokemonId == 0)
                    {
                        // If is basic incubator and user don't want use it, we go to the next incubator
                        if ((incubator.ItemId == ItemId.ItemIncubatorBasic) &&
                            (!GlobalVars.UseBasicIncubators))
                        {
                            continue;
                        }

                        POGOProtos.Data.PokemonData egg;
                        if (incubator.ItemId == ItemId.ItemIncubatorBasic)
                        {
                            egg = GlobalVars.EggsAscendingSelectionBasicInc ? unusedEggsBasicInc.FirstOrDefault() : unusedEggsBasicInc.LastOrDefault();
                        }
                        else
                        {
                            egg = GlobalVars.EggsAscendingSelection ? unusedEggsUnlimitInc.FirstOrDefault() : unusedEggsUnlimitInc.LastOrDefault();
                        }

                        // If there is not eggs then we finish this function
                        if (egg == null)
                        {
                            return;
                        }

                        var response = Logic.objClient.Inventory.UseItemEggIncubator(incubator.Id, egg.Id);
                        try
                        {
                            unusedEggsUnlimitInc.Remove(egg);
                            unusedEggsBasicInc.Remove(egg);
                        }
                        catch (Exception ex) {
                            Logger.ColoredConsoleWrite(ConsoleColor.Red, "Error: Logic.cs - StartIncubation()");
                            Logger.ColoredConsoleWrite(ConsoleColor.Red, ex.Message);
                        }
                        newRememberedIncubators.Add(new IncubatorUsage {
                            IncubatorId = incubator.Id, PokemonId = egg.Id
                        });
                        Logger.ColoredConsoleWrite(ConsoleColor.DarkYellow, "Added Egg which needs " + egg.EggKmWalkedTarget + "km");
                        // We need some sleep here or this shit explodes
                        RandomHelper.RandomSleep(100, 200);
                    }
                    else
                    {
                        newRememberedIncubators.Add(new IncubatorUsage
                        {
                            IncubatorId = incubator.Id,
                            PokemonId   = incubator.PokemonId
                        });

                        Logger.ColoredConsoleWrite(ConsoleColor.DarkYellow, "Egg (" + (incubator.TargetKmWalked - incubator.StartKmWalked) + "km) need to walk " + Math.Round(incubator.TargetKmWalked - kmWalked, 2) + " km.");
                    }
                }
                if (!newRememberedIncubators.SequenceEqual(rememberedIncubators))
                {
                    rememberedIncubators = newRememberedIncubators;
                }
            }
            catch (Exception ex)
            {
                // Leave this here: Logger.Error(e.StackTrace);
                Logger.ColoredConsoleWrite(ConsoleColor.DarkYellow, "Egg: We dont have any eggs we could incubate.");
                Logger.ColoredConsoleWrite(ConsoleColor.Red, ex.Message);
            }
        }
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (!session.LogicSettings.TransferWeakPokemon)
            {
                return;
            }

            if (session.LogicSettings.AutoFavoritePokemon)
            {
                await FavoritePokemonTask.Execute(session, cancellationToken);
            }

            await session.Inventory.RefreshCachedInventory();

            var pokemons = await session.Inventory.GetPokemons();

            var pokemonDatas     = pokemons as IList <PokemonData> ?? pokemons.ToList();
            var pokemonsFiltered =
                pokemonDatas.Where(pokemon => !session.LogicSettings.PokemonsNotToTransfer.Contains(pokemon.PokemonId))
                .ToList().OrderBy(poke => poke.Cp);

            if (session.LogicSettings.KeepPokemonsThatCanEvolve)
            {
                pokemonsFiltered =
                    pokemonDatas.Where(pokemon => !session.LogicSettings.PokemonsToEvolve.Contains(pokemon.PokemonId))
                    .ToList().OrderBy(poke => poke.Cp);
            }

            var orderedPokemon = pokemonsFiltered.OrderBy(poke => poke.Cp);

            foreach (var pokemon in orderedPokemon)
            {
                cancellationToken.ThrowIfCancellationRequested();
                if ((pokemon.Cp >= session.LogicSettings.KeepMinCp) ||
                    (PokemonInfo.CalculatePokemonPerfection(pokemon) >= session.LogicSettings.KeepMinIvPercentage &&
                     session.LogicSettings.PrioritizeIvOverCp) ||
                    (PokemonInfo.GetLevel(pokemon) >= session.LogicSettings.KeepMinLvl && session.LogicSettings.UseKeepMinLvl) ||
                    pokemon.Favorite == 1)
                {
                    continue;
                }

                await session.Client.Inventory.TransferPokemon(pokemon.Id);

                await session.Inventory.DeletePokemonFromInvById(pokemon.Id);

                var bestPokemonOfType = (session.LogicSettings.PrioritizeIvOverCp
                    ? await session.Inventory.GetHighestPokemonOfTypeByIv(pokemon)
                    : await session.Inventory.GetHighestPokemonOfTypeByCp(pokemon)) ?? pokemon;

                var setting = session.Inventory.GetPokemonSettings()
                              .Result.Single(q => q.PokemonId == pokemon.PokemonId);
                var family = session.Inventory.GetPokemonFamilies().Result.First(q => q.FamilyId == setting.FamilyId);

                family.Candy_++;

                session.EventDispatcher.Send(new TransferPokemonEvent
                {
                    Id             = pokemon.PokemonId,
                    Perfection     = PokemonInfo.CalculatePokemonPerfection(pokemon),
                    Cp             = pokemon.Cp,
                    BestCp         = bestPokemonOfType.Cp,
                    BestPerfection = PokemonInfo.CalculatePokemonPerfection(bestPokemonOfType),
                    FamilyCandies  = family.Candy_
                });

                await DelayingUtils.DelayAsync(session.LogicSettings.TransferActionDelay, 0, cancellationToken);
            }
        }
Ejemplo n.º 7
0
        public async Task <IEnumerable <PokemonData> > GetDuplicatePokemonToTransfer(
            IEnumerable <PokemonId> pokemonsNotToTransfer, IEnumerable <PokemonId> pokemonsToEvolve,
            bool keepPokemonsThatCanEvolve = false, bool prioritizeIVoverCp = false
            )
        {
            var myPokemon = await GetPokemons();

            var myPokemonList = myPokemon.ToList();

            var pokemonToTransfer = myPokemonList.Where(p => !pokemonsNotToTransfer.Contains(p.PokemonId) && p.DeployedFortId == string.Empty && p.Favorite == 0).ToList();

            try
            {
                pokemonToTransfer =
                    pokemonToTransfer.Where(
                        p =>
                {
                    var pokemonTransferFilter = GetPokemonTransferFilter(p.PokemonId);

                    return(!pokemonTransferFilter.MovesOperator.BoolFunc(
                               pokemonTransferFilter.MovesOperator.ReverseBoolFunc(
                                   pokemonTransferFilter.MovesOperator.InverseBool(pokemonTransferFilter.Moves.Count > 0),
                                   pokemonTransferFilter.Moves.Any(moveset =>
                                                                   pokemonTransferFilter.MovesOperator.ReverseBoolFunc(
                                                                       pokemonTransferFilter.MovesOperator.InverseBool(moveset.Count > 0),
                                                                       moveset.Intersect(new[] { p.Move1, p.Move2 }).Count() == Math.Max(Math.Min(moveset.Count, 2), 0)))),
                               pokemonTransferFilter.KeepMinOperator.BoolFunc(
                                   p.Cp >= pokemonTransferFilter.KeepMinCp,
                                   PokemonInfo.CalculatePokemonPerfection(p) >= pokemonTransferFilter.KeepMinIvPercentage,
                                   pokemonTransferFilter.KeepMinOperator.ReverseBoolFunc(
                                       pokemonTransferFilter.KeepMinOperator.InverseBool(pokemonTransferFilter.UseKeepMinLvl),
                                       PokemonInfo.GetLevel(p) >= pokemonTransferFilter.KeepMinLvl))));
                }).ToList();
            }
            catch (Exceptions.ActiveSwitchByRuleException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                //throw e;
            }

            var myPokemonSettings = await GetPokemonSettings();

            var pokemonSettings = myPokemonSettings.ToList();

            var myPokemonFamilies = await GetPokemonFamilies();

            var pokemonFamilies = myPokemonFamilies.ToArray();

            var results = new List <PokemonData>();

            foreach (var pokemonGroupToTransfer in pokemonToTransfer.GroupBy(p => p.PokemonId).ToList())
            {
                var amountToKeepInStorage = Math.Max(GetPokemonTransferFilter(pokemonGroupToTransfer.Key).KeepMinDuplicatePokemon, 0);

                var inStorage    = myPokemonList.Count(data => data.PokemonId == pokemonGroupToTransfer.Key);
                var needToRemove = inStorage - amountToKeepInStorage;

                if (needToRemove <= 0)
                {
                    continue;
                }

                var weakPokemonCount = pokemonGroupToTransfer.Count();
                var canBeRemoved     = Math.Min(needToRemove, weakPokemonCount);


                var settings = pokemonSettings.Single(x => x.PokemonId == pokemonGroupToTransfer.Key);
                //Lets calc new canBeRemoved pokemons according to transferring some of them for +1 candy or to evolving for +1 candy
                if (keepPokemonsThatCanEvolve &&
                    pokemonsToEvolve.Contains(pokemonGroupToTransfer.Key) &&
                    settings.CandyToEvolve > 0 &&
                    settings.EvolutionIds.Count != 0)
                {
                    var familyCandy = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId);

                    // its an solution in fixed numbers of equations with two variables
                    // (N = X + Y, X + C + Y >= Y * E) -> X >= (N * (E - 1) - C) / E
                    // where N - current canBeRemoved,  X - new canBeRemoved, Y - possible to keep more, E - CandyToEvolve, C - candy amount
                    canBeRemoved = (int)Math.Ceiling((double)((settings.CandyToEvolve - 1) * canBeRemoved - familyCandy.Candy_) / settings.CandyToEvolve);
                }

                if (canBeRemoved <= 0)
                {
                    continue;
                }

                if (prioritizeIVoverCp)
                {
                    results.AddRange(pokemonGroupToTransfer
                                     .OrderBy(PokemonInfo.CalculatePokemonPerfection)
                                     .ThenBy(n => n.Cp)
                                     .Take(canBeRemoved));
                }
                else
                {
                    results.AddRange(pokemonGroupToTransfer
                                     .OrderBy(x => x.Cp)
                                     .ThenBy(PokemonInfo.CalculatePokemonPerfection)
                                     .Take(canBeRemoved));
                }
            }

            #region For testing

            /*
             *          results.ForEach(data =>
             *          {
             *              var allpokemonoftype = myPokemonList.Where(x => x.PokemonId == data.PokemonId);
             *              var bestPokemonOfType =
             *                  (_logicSettings.PrioritizeIvOverCp
             *                       ? allpokemonoftype
             *                      .OrderByDescending(PokemonInfo.CalculatePokemonPerfection)
             *                      .FirstOrDefault()
             *                       : allpokemonoftype
             *                      .OrderByDescending(x => x.Cp)
             *                      .FirstOrDefault())
             *                  ?? data;
             *
             *              var perfection = PokemonInfo.CalculatePokemonPerfection(data);
             *              var cp = data.Cp;
             *
             *              var bestPerfection = PokemonInfo.CalculatePokemonPerfection(bestPokemonOfType);
             *              var bestCp = bestPokemonOfType.Cp;
             *          });
             */
            #endregion

            return(results);
        }
Ejemplo n.º 8
0
        public async Task <IEnumerable <PokemonData> > GetDuplicatePokemonToTransfer(
            IEnumerable <PokemonId> pokemonsNotToTransfer, IEnumerable <PokemonId> pokemonsToEvolve,
            bool keepPokemonsThatCanEvolve = false, bool prioritizeIVoverCp = false
            )
        {
            var myPokemon = GetPokemons();

            var pokemonToTransfer = myPokemon
                                    .Where(p => !pokemonsNotToTransfer.Contains(p.PokemonId) && p.DeployedFortId == string.Empty &&
                                           p.Favorite == 0 && p.BuddyTotalKmWalked == 0)
                                    .ToList();

            try
            {
                pokemonToTransfer =
                    pokemonToTransfer.Where(
                        p =>
                {
                    var pokemonTransferFilter = GetPokemonTransferFilter(p.PokemonId);

                    return(!pokemonTransferFilter.MovesOperator.BoolFunc(
                               pokemonTransferFilter.MovesOperator.ReverseBoolFunc(
                                   pokemonTransferFilter.MovesOperator.InverseBool(
                                       pokemonTransferFilter.Moves.Count > 0),
                                   pokemonTransferFilter.Moves.Any(moveset =>
                                                                   pokemonTransferFilter.MovesOperator.ReverseBoolFunc(
                                                                       pokemonTransferFilter.MovesOperator.InverseBool(moveset.Count > 0),
                                                                       moveset.Intersect(new[] { p.Move1, p.Move2 }).Count() ==
                                                                       Math.Max(Math.Min(moveset.Count, 2), 0)))),
                               pokemonTransferFilter.KeepMinOperator.BoolFunc(
                                   p.Cp >= pokemonTransferFilter.KeepMinCp,
                                   PokemonInfo.CalculatePokemonPerfection(p) >=
                                   pokemonTransferFilter.KeepMinIvPercentage,
                                   pokemonTransferFilter.KeepMinOperator.ReverseBoolFunc(
                                       pokemonTransferFilter.KeepMinOperator.InverseBool(pokemonTransferFilter
                                                                                         .UseKeepMinLvl),
                                       PokemonInfo.GetLevel(p) >= pokemonTransferFilter.KeepMinLvl))));
                })
                    .ToList();
            }
            catch (ActiveSwitchByRuleException e)
            {
                throw e;
            }
            catch (Exception)
            {
                //throw e;
            }

            var myPokemonSettings = await GetPokemonSettings();

            var pokemonSettings = myPokemonSettings.ToList();

            var myPokemonFamilies = await GetPokemonFamilies();

            var pokemonFamilies = myPokemonFamilies.ToArray();

            var results = new List <PokemonData>();

            foreach (var pokemonGroupToTransfer in pokemonToTransfer.GroupBy(p => p.PokemonId).ToList())
            {
                var amountToKeepInStorage = Math.Max(GetPokemonTransferFilter(pokemonGroupToTransfer.Key).KeepMinDuplicatePokemon, 0);

                var inStorage    = myPokemon.Count(data => data.PokemonId == pokemonGroupToTransfer.Key);
                var needToRemove = inStorage - amountToKeepInStorage;

                if (needToRemove <= 0)
                {
                    continue;
                }

                var weakPokemonCount = pokemonGroupToTransfer.Count();
                var canBeRemoved     = Math.Min(needToRemove, weakPokemonCount);

                var settings = pokemonSettings.FirstOrDefault(x => x.PokemonId == pokemonGroupToTransfer.Key);

                if (settings != null &&
                    pokemonsToEvolve.Contains(pokemonGroupToTransfer.Key) &&
                    settings.CandyToEvolve > 0 &&
                    settings.EvolutionIds.Count != 0)
                {
                    var familyCandy = pokemonFamilies.FirstOrDefault(x => settings.FamilyId == x.FamilyId);
                    if (familyCandy != null)
                    {
                        // Calculate the number of evolutions possible (taking into account +1 candy for evolve and +1 candy for transfer)
                        var evolutionCalcs = CalculatePokemonEvolution(canBeRemoved, familyCandy.Candy_, settings.CandyToEvolve, 1); // 1 for candy gain after evolution

                        // Subtract the number of evolutions possible from the number that can be transferred.
                        canBeRemoved -= evolutionCalcs.Evolves;
                    }
                }

                if (canBeRemoved <= 0)
                {
                    continue;
                }

                if (prioritizeIVoverCp)
                {
                    results.AddRange(pokemonGroupToTransfer
                                     .OrderBy(PokemonInfo.CalculatePokemonPerfection)
                                     .ThenBy(n => n.Cp)
                                     .Take(canBeRemoved));
                }
                else
                {
                    results.AddRange(pokemonGroupToTransfer
                                     .OrderBy(x => x.Cp)
                                     .ThenBy(PokemonInfo.CalculatePokemonPerfection)
                                     .Take(canBeRemoved));
                }
            }

            #region For testing

            /*
             *          results.ForEach(data =>
             *          {
             *              var allpokemonoftype = myPokemonList.Where(x => x.PokemonId == data.PokemonId);
             *              var bestPokemonOfType =
             *                  (_logicSettings.PrioritizeIvOverCp
             *                       ? allpokemonoftype
             *                      .OrderByDescending(PokemonInfo.CalculatePokemonPerfection)
             *                      .FirstOrDefault()
             *                       : allpokemonoftype
             *                      .OrderByDescending(x => x.Cp)
             *                      .FirstOrDefault())
             *                  ?? data;
             *
             *              var perfection = PokemonInfo.CalculatePokemonPerfection(data);
             *              var cp = data.Cp;
             *
             *              var bestPerfection = PokemonInfo.CalculatePokemonPerfection(bestPokemonOfType);
             *              var bestCp = bestPokemonOfType.Cp;
             *          });
             */

            #endregion

            return(results);
        }
Ejemplo n.º 9
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            await session.Inventory.RefreshCachedInventory();

            if (session.Inventory.GetStarDust() <= session.LogicSettings.GetMinStarDustForLevelUp)
            {
                return;
            }
            upgradablePokemon = await session.Inventory.GetPokemonToUpgrade();

            if (session.LogicSettings.OnlyUpgradeFavorites)
            {
                var fave = upgradablePokemon.Where(i => i.Favorite == 1);
                upgradablePokemon = fave;
            }

            if (upgradablePokemon.Count() == 0)
            {
                return;
            }

            var myPokemonSettings = await session.Inventory.GetPokemonSettings();

            var pokemonSettings = myPokemonSettings.ToList();

            var myPokemonFamilies = await session.Inventory.GetPokemonFamilies();

            var pokemonFamilies = myPokemonFamilies.ToArray();

            var upgradedNumber = 0;
            var PokemonToLevel = session.LogicSettings.PokemonsToLevelUp;

            foreach (var pokemon in upgradablePokemon)
            {
                if (session.LogicSettings.UseLevelUpList && PokemonToLevel != null)
                {
                    for (int i = 0; i < PokemonToLevel.Count; i++)
                    {
                        if (PokemonToLevel.Contains(pokemon.PokemonId))
                        {
                            PlayerStats playerStats = await session.Inventory.GetPlayerStats();

                            if (PokemonInfo.GetLevel(pokemon) >= playerStats.Level + 1)
                            {
                                continue;
                            }

                            var settings    = pokemonSettings.Single(x => x.PokemonId == pokemon.PokemonId);
                            var familyCandy = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId);

                            if (familyCandy.Candy_ <= 0)
                            {
                                continue;
                            }

                            var upgradeResult = await session.Inventory.UpgradePokemon(pokemon.Id);

                            if (upgradeResult.Result.ToString().ToLower().Contains("success"))
                            {
                                Logger.Write("Pokemon Upgraded:" +
                                             session.Translation.GetPokemonTranslation(
                                                 upgradeResult.UpgradedPokemon.PokemonId) + ":" +
                                             upgradeResult.UpgradedPokemon.Cp, LogLevel.LevelUp);
                                upgradedNumber++;
                            }

                            if (upgradedNumber >= session.LogicSettings.AmountOfTimesToUpgradeLoop)
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    PlayerStats playerStats = await session.Inventory.GetPlayerStats();

                    if (PokemonInfo.GetLevel(pokemon) >= playerStats.Level + 1)
                    {
                        continue;
                    }

                    var settings    = pokemonSettings.Single(x => x.PokemonId == pokemon.PokemonId);
                    var familyCandy = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId);

                    if (familyCandy.Candy_ <= 0)
                    {
                        continue;
                    }

                    var upgradeResult = await session.Inventory.UpgradePokemon(pokemon.Id);

                    if (upgradeResult.Result.ToString().ToLower().Contains("success"))
                    {
                        Logger.Write("Pokemon Upgraded:" + session.Translation.GetPokemonTranslation(upgradeResult.UpgradedPokemon.PokemonId) + ":" +
                                     upgradeResult.UpgradedPokemon.Cp, LogLevel.LevelUp);
                        upgradedNumber++;
                    }

                    if (upgradedNumber >= session.LogicSettings.AmountOfTimesToUpgradeLoop)
                    {
                        break;
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public static async Task Execute(ISession session, dynamic encounter, MapPokemon pokemon,
                                         FortData currentFortData = null, ulong encounterId = 0)
        {
            CatchPokemonResponse caughtPokemonResponse;
            var attemptCounter = 1;

            do
            {
                if (session.LogicSettings.MaxPokeballsPerPokemon > 0 &&
                    attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon)
                {
                    break;
                }

                float probability = encounter?.CaptureProbability?.CaptureProbability_[0];

                var pokeball = await GetBestBall(session, encounter, probability);

                if (pokeball == ItemId.ItemUnknown)
                {
                    session.EventDispatcher.Send(new NoPokeballEvent
                    {
                        Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId,
                        Cp =
                            (encounter is EncounterResponse
                                ? encounter.WildPokemon?.PokemonData?.Cp
                                : encounter?.PokemonData?.Cp) ?? 0
                    });
                    return;
                }

                var isLowProbability = probability < 0.35;
                var isHighCp         = encounter != null &&
                                       (encounter is EncounterResponse
                                   ? encounter.WildPokemon?.PokemonData?.Cp
                                   : encounter.PokemonData?.Cp) > 400;
                var isHighPerfection =
                    PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse
                        ? encounter.WildPokemon?.PokemonData
                        : encounter?.PokemonData) >= session.LogicSettings.KeepMinIvPercentage;

                if ((isLowProbability && isHighCp) || isHighPerfection)
                {
                    await
                    UseBerry(session,
                             encounter is EncounterResponse || encounter is IncenseEncounterResponse
                             ?pokemon.EncounterId
                             : encounterId,
                             encounter is EncounterResponse || encounter is IncenseEncounterResponse
                             ?pokemon.SpawnPointId
                             : currentFortData?.Id);
                }

                var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                       session.Client.CurrentLongitude,
                                                                       encounter is EncounterResponse || encounter is IncenseEncounterResponse
                        ? pokemon.Latitude
                        : currentFortData.Latitude,
                                                                       encounter is EncounterResponse || encounter is IncenseEncounterResponse
                        ? pokemon.Longitude
                        : currentFortData.Longitude);

                caughtPokemonResponse =
                    await session.Client.Encounter.CatchPokemon(
                        encounter is EncounterResponse || encounter is IncenseEncounterResponse
                        ?pokemon.EncounterId
                        : encounterId,
                        encounter is EncounterResponse || encounter is IncenseEncounterResponse
                        ?pokemon.SpawnPointId
                        : currentFortData.Id, pokeball);

                var evt = new PokemonCaptureEvent {
                    Status = caughtPokemonResponse.Status
                };

                if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                {
                    var totalExp = 0;

                    foreach (var xp in caughtPokemonResponse.CaptureAward.Xp)
                    {
                        totalExp += xp;
                    }
                    var profile = await session.Client.Player.GetPlayer();

                    evt.Exp      = totalExp;
                    evt.Stardust = profile.PlayerData.Currencies.ToArray()[1].Amount;

                    var pokemonSettings = await session.Inventory.GetPokemonSettings();

                    var pokemonFamilies = await session.Inventory.GetPokemonFamilies();

                    var setting =
                        pokemonSettings.FirstOrDefault(q => pokemon != null && q.PokemonId == pokemon.PokemonId);
                    var family = pokemonFamilies.FirstOrDefault(q => setting != null && q.FamilyId == setting.FamilyId);

                    if (family != null)
                    {
                        family.Candy_ += caughtPokemonResponse.CaptureAward.Candy.Sum();

                        evt.FamilyCandies = family.Candy_;
                    }
                    else
                    {
                        evt.FamilyCandies = caughtPokemonResponse.CaptureAward.Candy.Sum();
                    }
                }


                evt.CatchType = encounter is EncounterResponse
                    ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal)
                    : encounter is DiskEncounterResponse
                        ? session.Translation.GetTranslation(TranslationString.CatchTypeLure)
                        : session.Translation.GetTranslation(TranslationString.CatchTypeIncense);

                evt.Id    = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId;
                evt.Level =
                    PokemonInfo.GetLevel(encounter is EncounterResponse
                        ? encounter.WildPokemon?.PokemonData
                        : encounter?.PokemonData);
                evt.Cp = encounter is EncounterResponse
                    ? encounter.WildPokemon?.PokemonData?.Cp
                    : encounter?.PokemonData?.Cp ?? 0;
                evt.MaxCp =
                    PokemonInfo.CalculateMaxCp(encounter is EncounterResponse
                        ? encounter.WildPokemon?.PokemonData
                        : encounter?.PokemonData);
                evt.Perfection =
                    Math.Round(
                        PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse
                            ? encounter.WildPokemon?.PokemonData
                            : encounter?.PokemonData));
                evt.Probability =
                    Math.Round(probability * 100, 2);
                evt.Distance = distance;
                evt.Pokeball = pokeball;
                evt.Attempt  = attemptCounter;
                await session.Inventory.RefreshCachedInventory();

                evt.BallAmount = await session.Inventory.GetItemAmountByType(pokeball);

                session.EventDispatcher.Send(evt);

                attemptCounter++;

                DelayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 2000);
            } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed ||
                     caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape);
        }
Ejemplo n.º 11
0
        public async Task ExportPokemonToCsv(Profile player, string filename = "PokeList.csv")
        {
            if (player == null)
            {
                return;
            }
            var stats = await GetPlayerStats();

            var stat = stats.FirstOrDefault();

            if (stat == null)
            {
                return;
            }

            if (!Directory.Exists(_exportPath))
            {
                Directory.CreateDirectory(_exportPath);
            }
            if (Directory.Exists(_exportPath))
            {
                try
                {
                    var pokelistFile = Path.Combine(_exportPath, $"Profile_{player.Username}_{filename}");
                    if (File.Exists(pokelistFile))
                    {
                        File.Delete(pokelistFile);
                    }
                    var          ls     = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
                    const string header = "PokemonID,Name,NickName,Level,CP / MaxCP,IV Perfection in %,Attack 1,Attack 2,HP,Attk,Def,Stamina,Familie Candies,IsInGym,IsFavorite,previewLink";
                    File.WriteAllText(pokelistFile, $"{header.Replace(",", $"{ls}")}");

                    var allPokemon = await GetHighestsPerfect();

                    var myPokemonSettings = await GetPokemonSettings();

                    var pokemonSettings   = myPokemonSettings.ToList();
                    var myPokemonFamilies = await GetPokemonFamilies();

                    var pokemonFamilies = myPokemonFamilies.ToArray();
                    var trainerLevel    = stat.Level;
                    var expReq          = new[] { 0, 1000, 3000, 6000, 10000, 15000, 21000, 28000, 36000, 45000, 55000, 65000, 75000, 85000, 100000, 120000, 140000, 160000, 185000, 210000, 260000, 335000, 435000, 560000, 710000, 900000, 1100000, 1350000, 1650000, 2000000, 2500000, 3000000, 3750000, 4750000, 6000000, 7500000, 9500000, 12000000, 15000000, 20000000 };
                    var expReqAtLevel   = expReq[stat.Level - 1];

                    using (var w = File.AppendText(pokelistFile))
                    {
                        w.WriteLine("");
                        foreach (var pokemon in allPokemon)
                        {
                            var toEncode = $"{(int)pokemon.PokemonId}" + "," + trainerLevel + "," + PokemonInfo.GetLevel(pokemon) + "," + pokemon.Cp + "," + pokemon.Stamina;
                            //Generate base64 code to make it viewable here http://poke.isitin.org/#MTUwLDIzLDE3LDE5MDIsMTE4
                            var encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(toEncode));

                            var isInGym = string.Empty;
                            //var isInGym = pokemon.DeployedFortId == 0 ? "Yes" : "No";
                            var isFavorite = pokemon.Favorite != 0 ? "Yes" : "No";

                            var settings       = pokemonSettings.Single(x => x.PokemonId == pokemon.PokemonId);
                            var familiecandies = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId).Candy;
                            var perfection     = PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00");
                            perfection = perfection.Replace(",", ls == "," ? "." : ",");
                            string contentPart1 = $"\"{(int)pokemon.PokemonId}\",\"{pokemon.PokemonId}\",\"{pokemon.Nickname}\",";
                            string contentPart2 = $",\"{pokemon.Cp} / {PokemonInfo.CalculateMaxCp(pokemon)}\",";
                            string contentPart3 = $",\"{pokemon.Move1}\",\"{pokemon.Move2}\",\"{pokemon.Stamina}\",\"{pokemon.IndividualAttack}\",\"{pokemon.IndividualDefense}\",\"{pokemon.IndividualStamina}\",\"{familiecandies}\",\"{isInGym}\",\"{isFavorite}\",http://poke.isitin.org/#{encoded}";
                            string content      = $"{contentPart1.Replace(",", $"{ls}")}\"{PokemonInfo.GetLevel(pokemon)}\"{contentPart2.Replace(",", $"{ls}")}\"{perfection}\"{contentPart3.Replace(",", $"{ls}")}";
                            w.WriteLine($"{content}");
                        }
                        w.Close();
                    }
                    Logger.Write($"Export Player Infos and all Pokemon to \"\\Export\\Profile_{player.Username}_{filename}\"", LogLevel.Info);
                }
                catch
                {
                    Logger.Write("Export Player Infos and all Pokemons to CSV not possible. File seems be in use!", LogLevel.Warning);
                }
            }
        }
Ejemplo n.º 12
0
        private async void Execute()
        {
            EnabledButton(false, "Reloading Pokemon list.");


            await check();

            try
            {
                client = Logic.Logic._client;
                if (client.readyToUse != false)
                {
                    profile = await client.Player.GetPlayer();

                    inventory = await client.Inventory.GetInventory();

                    pokemons =
                        inventory.InventoryDelta.InventoryItems
                        .Select(i => i.InventoryItemData?.PokemonData)
                        .Where(p => p != null && p?.PokemonId > 0)
                        .OrderByDescending(key => key.Cp);
                    var families = inventory.InventoryDelta.InventoryItems
                                   .Select(i => i.InventoryItemData?.Candy)
                                   .Where(p => p != null && (int)p?.FamilyId > 0)
                                   .OrderByDescending(p => (int)p.FamilyId);

                    var imageSize = 50;

                    var imageList = new ImageList {
                        ImageSize = new Size(imageSize, imageSize)
                    };
                    PokemonListView.ShowItemToolTips = true;
                    PokemonListView.SmallImageList   = imageList;

                    var templates = await client.Download.GetItemTemplates();

                    var myPokemonSettings = templates.ItemTemplates.Select(i => i.PokemonSettings).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                    var pokemonSettings   = myPokemonSettings.ToList();

                    var myPokemonFamilies = inventory.InventoryDelta.InventoryItems.Select(i => i.InventoryItemData?.Candy).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                    var pokemonFamilies   = myPokemonFamilies.ToArray();

                    PokemonListView.DoubleBuffered(true);
                    PokemonListView.View = View.Details;

                    ColumnHeader columnheader;
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "Name";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "CP";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "IV A-D-S";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "LVL";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "Evolvable?";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "Height";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "Weight";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "HP";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "Attack";
                    PokemonListView.Columns.Add(columnheader);
                    columnheader      = new ColumnHeader();
                    columnheader.Text = "SpecialAttack (DPS)";
                    PokemonListView.Columns.Add(columnheader);

                    foreach (var pokemon in pokemons)
                    {
                        Bitmap pokemonImage = null;
                        await Task.Run(() =>
                        {
                            pokemonImage = GetPokemonImage((int)pokemon.PokemonId);
                        });

                        imageList.Images.Add(pokemon.PokemonId.ToString(), pokemonImage);

                        PokemonListView.LargeImageList = imageList;
                        var listViewItem = new ListViewItem();
                        listViewItem.Tag = pokemon;



                        var currentCandy = families
                                           .Where(i => (int)i.FamilyId <= (int)pokemon.PokemonId)
                                           .Select(f => f.Candy_)
                                           .First();
                        listViewItem.SubItems.Add(string.Format("{0}", pokemon.Cp));
                        listViewItem.SubItems.Add(string.Format("{0}% {1}-{2}-{3}", PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00"), pokemon.IndividualAttack, pokemon.IndividualDefense, pokemon.IndividualStamina));
                        listViewItem.SubItems.Add(string.Format("{0}", PokemonInfo.GetLevel(pokemon)));
                        listViewItem.ImageKey = pokemon.PokemonId.ToString();

                        listViewItem.Text = string.Format((pokemon.Favorite == 1) ? "{0} ★" : "{0}", StringUtils.getPokemonNameByLanguage(ClientSettings, (PokemonId)pokemon.PokemonId));

                        listViewItem.ToolTipText = new DateTime((long)pokemon.CreationTimeMs * 10000).AddYears(1769).ToString("dd/MM/yyyy HH:mm:ss");
                        if (pokemon.Nickname != "")
                        {
                            listViewItem.ToolTipText += "\nNickname: " + pokemon.Nickname;
                        }

                        var settings    = pokemonSettings.Single(x => x.PokemonId == pokemon.PokemonId);
                        var familyCandy = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId);

                        if (settings.EvolutionIds.Count > 0 && familyCandy.Candy_ >= settings.CandyToEvolve)
                        {
                            listViewItem.SubItems.Add("Y (" + familyCandy.Candy_ + "/" + settings.CandyToEvolve + ")");
                            listViewItem.Checked = true;
                        }
                        else
                        {
                            if (settings.EvolutionIds.Count > 0)
                            {
                                listViewItem.SubItems.Add("N (" + familyCandy.Candy_ + "/" + settings.CandyToEvolve + ")");
                            }
                            else
                            {
                                listViewItem.SubItems.Add("N (" + familyCandy.Candy_ + "/Max)");
                            }
                        }
                        listViewItem.SubItems.Add(string.Format("{0}", Math.Round(pokemon.HeightM, 2)));
                        listViewItem.SubItems.Add(string.Format("{0}", Math.Round(pokemon.WeightKg, 2)));
                        listViewItem.SubItems.Add(string.Format("{0}/{1}", pokemon.Stamina, pokemon.StaminaMax));
                        listViewItem.SubItems.Add(string.Format("{0}", pokemon.Move1));
                        listViewItem.SubItems.Add(string.Format("{0} ({1})", pokemon.Move2, PokemonInfo.GetAttack(pokemon.Move2)));

                        PokemonListView.Items.Add(listViewItem);
                    }
                    PokemonListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                    Text = "Pokemon List | User: "******" | Pokemons: " + pokemons.Count() + "/" + profile.PlayerData.MaxPokemonStorage;
                    EnabledButton(true);

                    statusTexbox.Text = string.Empty;
                }
            }
            catch (Exception e)
            {
                Logger.Error("[PokemonList-Error] " + e.StackTrace);
                await Task.Delay(1000); // Lets the API make a little pause, so we dont get blocked

                Execute();
            }
        }
Ejemplo n.º 13
0
        public void ExportPokemonToCSV(PlayerData player, string filename = "PokemonList.csv")
        {
            if (player == null)
            {
                return;
            }
            var stats = GetPlayerStats();
            var stat  = stats.FirstOrDefault();

            if (stat == null)
            {
                return;
            }

            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs");

            if (Directory.Exists(path))
            {
                try
                {
                    string pokelist_file = Path.Combine(path, $"Profile_{player.Username}_{filename}");
                    if (File.Exists(pokelist_file))
                    {
                        File.Delete(pokelist_file);
                    }
                    string ls     = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
                    string header = "PokemonID,Name,NickName,CP / MaxCP,IV Perfection in %,Attack 1,Attack 2,HP,Attk,Def,Stamina,Familie Candies,IsInGym,IsFavorite,previewLink";
                    File.WriteAllText(pokelist_file, header.Replace(",", ls));

                    var   AllPokemon        = GetHighestsPerfect();
                    var   myPokemonSettings = GetPokemonSettings();
                    var   pokemonSettings   = myPokemonSettings.ToList();
                    var   myPokemonFamilies = GetPokemonFamilies();
                    var   pokemonFamilies   = myPokemonFamilies.ToArray();
                    int   trainerLevel      = stat.Level;
                    int[] exp_req           = new[] { 0, 1000, 3000, 6000, 10000, 15000, 21000, 28000, 36000, 45000, 55000, 65000, 75000, 85000, 100000, 120000, 140000, 160000, 185000, 210000, 260000, 335000, 435000, 560000, 710000, 900000, 1100000, 1350000, 1650000, 2000000, 2500000, 3000000, 3750000, 4750000, 6000000, 7500000, 9500000, 12000000, 15000000, 20000000 };
                    int   exp_req_at_level  = exp_req[stat.Level - 1];

                    using (var w = File.AppendText(pokelist_file))
                    {
                        w.WriteLine("");
                        foreach (var pokemon in AllPokemon)
                        {
                            string toEncode = $"{(int)pokemon.PokemonId}" + "," + trainerLevel + "," + PokemonInfo.GetLevel(pokemon) + "," + pokemon.Cp + "," + pokemon.Stamina;
                            //Generate base64 code to make it viewable here http://poke.isitin.org/#MTUwLDIzLDE3LDE5MDIsMTE4
                            var encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(toEncode));

                            string IsInGym    = string.Empty;
                            string IsFavorite = string.Empty;

                            if (pokemon.Favorite != 0)
                            {
                                IsFavorite = "Yes";
                            }
                            else
                            {
                                IsFavorite = "No";
                            }

                            var    settings       = pokemonSettings.SingleOrDefault(x => x.PokemonId == pokemon.PokemonId);
                            var    familiecandies = pokemonFamilies.SingleOrDefault(x => settings.FamilyId == x.FamilyId).Candy_;
                            string perfection     = PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00");
                            perfection = perfection.Replace(",", ls == "," ? "." : ",");
                            string content_part1 = $"{(int)pokemon.PokemonId},{pokemon.PokemonId},{pokemon.Nickname},{pokemon.Cp}/{PokemonInfo.CalculateMaxCP(pokemon)},";
                            string content_part2 = $",{pokemon.Move1},{pokemon.Move2},{pokemon.Stamina},{pokemon.IndividualAttack},{pokemon.IndividualDefense},{pokemon.IndividualStamina},{familiecandies},{IsInGym},{IsFavorite},http://poke.isitin.org/#{encoded}";
                            var    str1          = content_part1.Replace(",", ls);
                            var    str2          = content_part2.Replace(",", ls);
                            string content       = $"{str1}\"{perfection}\"{str2}";
                            w.WriteLine($"{content}");
                        }
                        w.Close();
                    }
                    Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Export Player Infos and all Pokemon to \"\\Config\\{filename}\"");
                }
                catch
                {
                    Logger.Error("Export Player Infos and all Pokemons to CSV not possible. File seems be in use!" /*, LogLevel.Warning*/);
                }
            }
        }
        private bool CanPowerUp()
        {
            if (SelectedPokemon == null || ServerRequestRunning)
            {
                return(false);
            }
            var pokemonLevel      = PokemonInfo.GetLevel(SelectedPokemon.WrappedData);
            var currentCandy      = GameClient.CandyInventory.FirstOrDefault(item => item.FamilyId == GameClient.GetExtraDataForPokemon(SelectedPokemon.PokemonId).FamilyId);
            var candiesToPowerUp  = Convert.ToInt32(GameClient.PokemonUpgradeSettings.CandyCost[Convert.ToInt32(Math.Floor(PokemonInfo.GetLevel(SelectedPokemon.WrappedData)) - 1)]);
            var stardustToPowerUp = Convert.ToInt32(GameClient.PokemonUpgradeSettings.StardustCost[Convert.ToInt32(Math.Floor(PokemonInfo.GetLevel(SelectedPokemon.WrappedData)) - 1)]);

            return(currentCandy != null && StardustAmount >= stardustToPowerUp && currentCandy.Candy_ >= candiesToPowerUp && pokemonLevel < GameClient.PlayerStats.Level + 1.5);
        }
Ejemplo n.º 15
0
        public static async Task <bool> Execute(ISession session, dynamic encounter, PokemonCacheItem pokemon,
                                                FortData currentFortData = null, ulong encounterId = 0)
        {
            if (encounter is EncounterResponse && pokemon == null)
            {
                throw new ArgumentException("Parameter pokemon must be set, if encounter is of type EncounterResponse",
                                            nameof(pokemon));
            }


            CatchPokemonResponse caughtPokemonResponse;
            var attemptCounter = 1;

            do
            {
                if (session.LogicSettings.MaxPokeballsPerPokemon > 0 &&
                    attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon)
                {
                    break;
                }

                float probability = encounter?.CaptureProbability?.CaptureProbability_[0];

                ItemId pokeball = await GetBestBall(session, encounter, probability);

                if (pokeball == ItemId.ItemUnknown)
                {
                    session.EventDispatcher.Send(new NoPokeballEvent
                    {
                        Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId,
                        Cp =
                            (encounter is EncounterResponse
                                ? encounter.WildPokemon?.PokemonData?.Cp
                                : encounter?.PokemonData?.Cp) ?? 0
                    });
                    return(false);
                }

                var useBerryBelowCatchProbability = session.LogicSettings.UseBerryBelowCatchProbability > 1
                    ? session.LogicSettings.UseBerryBelowCatchProbability / 100
                    : session.LogicSettings.UseBerryBelowCatchProbability;
                var isLowProbability = probability < useBerryBelowCatchProbability;
                var isHighCp         = encounter != null &&
                                       (encounter is EncounterResponse
                                   ? encounter.WildPokemon?.PokemonData?.Cp
                                   : encounter.PokemonData?.Cp) > session.LogicSettings.UseBerryMinCp;
                var isHighPerfection =
                    PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse
                        ? encounter.WildPokemon?.PokemonData
                        : encounter?.PokemonData) >= session.LogicSettings.UseBerryMinIv;

                if (isLowProbability && ((session.LogicSettings.PrioritizeIvOverCp && isHighPerfection) || isHighCp))
                {
                    await
                    UseBerry(session,
                             encounter is EncounterResponse || encounter is IncenseEncounterResponse
                             ?pokemon.EncounterId
                             : encounterId,
                             encounter is EncounterResponse || encounter is IncenseEncounterResponse
                             ?pokemon.SpawnPointId
                             : currentFortData?.Id);

                    await DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 1000);
                }

                var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                       session.Client.CurrentLongitude,
                                                                       encounter is EncounterResponse || encounter is IncenseEncounterResponse
                        ? pokemon.Latitude
                        : currentFortData.Latitude,
                                                                       encounter is EncounterResponse || encounter is IncenseEncounterResponse
                        ? pokemon.Longitude
                        : currentFortData.Longitude);

                double normalizedRecticleSize, spinModifier;
                if (session.LogicSettings.HumanizeThrows)
                {
                    normalizedRecticleSize =
                        Rng.NextInRange(session.LogicSettings.ThrowAccuracyMin, session.LogicSettings.ThrowAccuracyMax) *
                        1.85 + 0.1; // 0.1..1.95
                    spinModifier = Rng.NextDouble() > session.LogicSettings.ThrowSpinFrequency ? 0.0 : 1.0;
                }
                else
                {
                    normalizedRecticleSize = 1.95;
                    spinModifier           = 1.00;
                }
                Func <ItemId, string> returnRealBallName = a =>
                {
                    switch (a)
                    {
                    case ItemId.ItemPokeBall:
                        return(session.Translation.GetTranslation(TranslationString.Pokeball));

                    case ItemId.ItemGreatBall:
                        return(session.Translation.GetTranslation(TranslationString.GreatPokeball));

                    case ItemId.ItemUltraBall:
                        return(session.Translation.GetTranslation(TranslationString.UltraPokeball));

                    case ItemId.ItemMasterBall:
                        return(session.Translation.GetTranslation(TranslationString.MasterPokeball));

                    default:
                        return(session.Translation.GetTranslation(TranslationString.CommonWordUnknown));
                    }
                };
                Func <double, string> getThrowType = a =>
                {
                    if (a < 1.0)
                    {
                        return("Normal ");
                    }
                    if (a < 1.3)
                    {
                        return("Nice! ");
                    }
                    if (a < 1.7)
                    {
                        return("Great! ");
                    }
                    return(a > 1.6 ? "Excellent! " : "unknown ");
                };
                var hit = Rng.NextDouble() > session.LogicSettings.MissChance;
                Logging.Logger.Write($"Throwing {(Math.Abs(spinModifier - 1) < 0.00001 ?"Spinning " : "" )}{getThrowType(normalizedRecticleSize)}{returnRealBallName(pokeball)} - {(hit ? "WILL HIT" : "WILL MISS")}", Logging.LogLevel.Caught, session: session);
                caughtPokemonResponse =
                    await session.Client.Encounter.CatchPokemon(
                        encounter is EncounterResponse || encounter is IncenseEncounterResponse
                        ?pokemon.EncounterId
                        : encounterId,
                        encounter is EncounterResponse || encounter is IncenseEncounterResponse
                        ?pokemon.SpawnPointId
                        : currentFortData.Id, pokeball,
                        normalizedRecticleSize,
                        spinModifier, hitPokemon : hit);

                session.EventDispatcher.Send(new ItemLostEvent {
                    Id = pokeball, Count = 1
                });

                var lat = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.Latitude
                    : currentFortData.Latitude;
                var lng = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.Longitude
                    : currentFortData.Longitude;
                var evt = new PokemonCaptureEvent
                {
                    Status    = caughtPokemonResponse.Status,
                    Latitude  = lat,
                    Longitude = lng
                };

                if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                {
                    if (pokemon != null)
                    {
                        pokemon.Caught = true;
                    }
                    evt.Uid = caughtPokemonResponse.CapturedPokemonId;

                    var totalExp = caughtPokemonResponse.CaptureAward.Xp.Sum();
                    var profile  = await session.Client.Player.GetPlayer();

                    evt.Exp      = totalExp;
                    evt.Stardust = profile.PlayerData.Currencies.ToArray()[1].Amount;

                    var pokemonSettings = await session.Inventory.GetPokemonSettings();

                    var pokemonFamilies = await session.Inventory.GetPokemonFamilies();

                    var setting =
                        pokemonSettings.FirstOrDefault(q => q.PokemonId == pokemon?.PokemonId);
                    var family = pokemonFamilies.FirstOrDefault(q => setting != null && q.FamilyId == setting.FamilyId);

                    if (family != null)
                    {
                        family.Candy_    += caughtPokemonResponse.CaptureAward.Candy.Sum();
                        evt.Family        = family.FamilyId;
                        evt.FamilyCandies = family.Candy_;
                    }
                    else
                    {
                        evt.FamilyCandies = caughtPokemonResponse.CaptureAward.Candy.Sum();
                    }
                    session.MapCache.PokemonCaught(pokemon);
                }
                if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchFlee)
                {
                    pokemon.Caught = true;
                }


                evt.CatchType = encounter is EncounterResponse
                    ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal)
                    : encounter is DiskEncounterResponse
                        ? session.Translation.GetTranslation(TranslationString.CatchTypeLure)
                        : session.Translation.GetTranslation(TranslationString.CatchTypeIncense);

                evt.Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId;

                var pokeData = (encounter is EncounterResponse
                    ? encounter.WildPokemon?.PokemonData
                    : encounter?.PokemonData) as PokemonData;

                if (pokeData != null)
                {
                    evt.Level       = PokemonInfo.GetLevel(pokeData);
                    evt.Cp          = pokeData.Cp;
                    evt.MaxCp       = PokemonInfo.CalculateMaxCp(pokeData);
                    evt.Perfection  = Math.Round(pokeData.CalculatePokemonPerfection(), 2);
                    evt.Probability =
                        Math.Round(probability * 100, 2);

                    evt.Move1 = pokeData.Move1;
                    evt.Move2 = pokeData.Move2;
                }
                evt.Distance = distance;
                evt.Pokeball = pokeball;
                evt.Attempt  = attemptCounter;
                await session.Inventory.RefreshCachedInventory();

                evt.BallAmount = await session.Inventory.GetItemAmountByType(pokeball);

                session.EventDispatcher.Send(evt);

                attemptCounter++;
                await Task.Delay(session.LogicSettings.DelayCatchPokemon);
            } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed ||
                     caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape);

            return(true);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Because this function sometime being called inside loop, return true it mean we don't want break look, false it mean not need to call this , break a loop from caller function
        /// </summary>
        /// <param name="session"></param>
        /// <param name="cancellationToken"></param>
        /// <param name="encounter"></param>
        /// <param name="pokemon"></param>
        /// <param name="currentFortData"></param>
        /// <param name="sessionAllowTransfer"></param>
        /// <returns></returns>
        public static async Task <bool> Execute(ISession session,
                                                CancellationToken cancellationToken,
                                                dynamic encounter,
                                                MapPokemon pokemon,
                                                FortData currentFortData,
                                                bool sessionAllowTransfer)
        {
            // If the encounter is null nothing will work below, so exit now
            if (encounter == null)
            {
                return(true);
            }
            // Exit if user defined max limits reached
            if (CatchThresholdExceeds(session, cancellationToken))
            {
                return(false);
            }

            using (var block = new BlockableScope(session, Model.BotActions.Catch))
            {
                if (!await block.WaitToRun())
                {
                    return(true);
                }

                AmountOfBerries = 0;

                cancellationToken.ThrowIfCancellationRequested();

                float probability = encounter.CaptureProbability?.CaptureProbability_[0];

                PokemonData encounteredPokemon;
                long        unixTimeStamp;
                ulong       _encounterId;
                string      _spawnPointId;

                // Calling from CatchNearbyPokemonTask and SnipePokemonTask
                if (encounter is EncounterResponse &&
                    (encounter?.Status == EncounterResponse.Types.Status.EncounterSuccess))
                {
                    encounteredPokemon = encounter.WildPokemon?.PokemonData;
                    unixTimeStamp      = encounter.WildPokemon?.LastModifiedTimestampMs
                                         + encounter.WildPokemon?.TimeTillHiddenMs;
                    _spawnPointId = encounter.WildPokemon?.SpawnPointId;
                    _encounterId  = encounter.WildPokemon?.EncounterId;
                }
                // Calling from CatchIncensePokemonTask
                else if (encounter is IncenseEncounterResponse &&
                         (encounter?.Result == IncenseEncounterResponse.Types.Result.IncenseEncounterSuccess))
                {
                    encounteredPokemon = encounter?.PokemonData;
                    unixTimeStamp      = pokemon.ExpirationTimestampMs;
                    _spawnPointId      = pokemon.SpawnPointId;
                    _encounterId       = pokemon.EncounterId;
                }
                // Calling from CatchLurePokemon
                else if (encounter is DiskEncounterResponse &&
                         encounter?.Result == DiskEncounterResponse.Types.Result.Success &&
                         !(currentFortData == null))
                {
                    encounteredPokemon = encounter?.PokemonData;
                    unixTimeStamp      = currentFortData.LureInfo.LureExpiresTimestampMs;
                    _spawnPointId      = currentFortData.Id;
                    _encounterId       = currentFortData.LureInfo.EncounterId;
                }
                else
                {
                    return(true); // No success to work with, exit
                }
                // Check for pokeballs before proceeding
                var pokeball = await GetBestBall(session, encounteredPokemon, probability);

                if (pokeball == ItemId.ItemUnknown)
                {
                    Logger.Write(session.Translation.GetTranslation(TranslationString.ZeroPokeballInv));
                    return(false);
                }

                // Calculate CP and IV
                var pokemonCp = encounteredPokemon?.Cp;
                var pokemonIv = PokemonInfo.CalculatePokemonPerfection(encounteredPokemon);
                var lv        = PokemonInfo.GetLevel(encounteredPokemon);

                // Calculate distance away
                var latitude = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                            ? pokemon.Latitude
                            : currentFortData.Latitude;
                var longitude = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                        ? pokemon.Longitude
                        : currentFortData.Longitude;

                var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                       session.Client.CurrentLongitude, latitude, longitude);
                if (session.LogicSettings.ActivateMSniper)
                {
                    var newdata = new MSniperServiceTask.EncounterInfo();
                    newdata.EncounterId  = _encounterId.ToString();
                    newdata.Iv           = Math.Round(pokemonIv, 2);
                    newdata.Latitude     = latitude.ToString("G17", CultureInfo.InvariantCulture);
                    newdata.Longitude    = longitude.ToString("G17", CultureInfo.InvariantCulture);
                    newdata.PokemonId    = (int)(encounteredPokemon?.PokemonId ?? 0);
                    newdata.PokemonName  = encounteredPokemon?.PokemonId.ToString();
                    newdata.SpawnPointId = _spawnPointId;
                    newdata.Move1        = PokemonInfo.GetPokemonMove1(encounteredPokemon).ToString();
                    newdata.Move2        = PokemonInfo.GetPokemonMove2(encounteredPokemon).ToString();
                    newdata.Expiration   = unixTimeStamp;

                    session.EventDispatcher.Send(newdata);
                }

                DateTime expiredDate = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(unixTimeStamp));
                var      encounterEV = new EncounteredEvent()
                {
                    Latitude        = latitude,
                    Longitude       = longitude,
                    PokemonId       = encounteredPokemon.PokemonId,
                    IV              = pokemonIv,
                    Level           = (int)lv,
                    Expires         = expiredDate.ToUniversalTime(),
                    ExpireTimestamp = unixTimeStamp,
                    SpawnPointId    = _spawnPointId,
                    EncounterId     = _encounterId.ToString(),
                    Move1           = PokemonInfo.GetPokemonMove1(encounteredPokemon).ToString(),
                    Move2           = PokemonInfo.GetPokemonMove2(encounteredPokemon).ToString(),
                };

                session.EventDispatcher.Send(encounterEV);

                if (IsNotMetWithCatchCriteria(session, encounteredPokemon, pokemonIv, lv, pokemonCp))
                {
                    session.EventDispatcher.Send(new NoticeEvent
                    {
                        Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped, encounteredPokemon.PokemonId)
                    });
                    session.Cache.Add(_encounterId.ToString(), encounteredPokemon, expiredDate);
                    Logger.Write($"Filter catch not met. {encounteredPokemon.PokemonId.ToString()} IV {pokemonIv} lv {lv} {pokemonCp} move1 {PokemonInfo.GetPokemonMove1(encounteredPokemon)} move 2 {PokemonInfo.GetPokemonMove2(encounteredPokemon)}");
                    return(true);
                }
                ;

                CatchPokemonResponse caughtPokemonResponse = null;
                var lastThrow      = CatchPokemonResponse.Types.CatchStatus.CatchSuccess; // Initializing lastThrow
                var attemptCounter = 1;

                // Main CatchPokemon-loop
                do
                {
                    if ((session.LogicSettings.MaxPokeballsPerPokemon > 0 &&
                         attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon))
                    {
                        break;
                    }

                    pokeball = await GetBestBall(session, encounteredPokemon, probability);

                    if (pokeball == ItemId.ItemUnknown)
                    {
                        session.EventDispatcher.Send(new NoPokeballEvent
                        {
                            Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId,
                            Cp = encounteredPokemon.Cp
                        });
                        return(false);
                    }

                    // Determine whether to use berries or not
                    if (((session.LogicSettings.UseBerriesOperator.ToLower().Equals("and") &&
                          pokemonIv >= session.LogicSettings.UseBerriesMinIv &&
                          pokemonCp >= session.LogicSettings.UseBerriesMinCp &&
                          probability < session.LogicSettings.UseBerriesBelowCatchProbability) ||
                         (session.LogicSettings.UseBerriesOperator.ToLower().Equals("or") && (
                              pokemonIv >= session.LogicSettings.UseBerriesMinIv ||
                              pokemonCp >= session.LogicSettings.UseBerriesMinCp ||
                              probability < session.LogicSettings.UseBerriesBelowCatchProbability))) &&
                        lastThrow != CatchPokemonResponse.Types.CatchStatus.CatchMissed) // if last throw is a miss, no double berry
                    {
                        AmountOfBerries++;
                        if (AmountOfBerries <= session.LogicSettings.MaxBerriesToUsePerPokemon)
                        {
                            await UseBerry(session, _encounterId, _spawnPointId, cancellationToken);
                        }
                    }

                    bool hitPokemon = true;

                    //default to excellent throw
                    var normalizedRecticleSize = 1.95;

                    //default spin
                    var spinModifier = 1.0;

                    //Humanized throws
                    if (session.LogicSettings.EnableHumanizedThrows)
                    {
                        //thresholds: https://gist.github.com/anonymous/077d6dea82d58b8febde54ae9729b1bf
                        var spinTxt = "Curve";
                        var hitTxt  = "Excellent";
                        if (pokemonCp > session.LogicSettings.ForceExcellentThrowOverCp ||
                            pokemonIv > session.LogicSettings.ForceExcellentThrowOverIv)
                        {
                            normalizedRecticleSize = Random.NextDouble() * (1.95 - 1.7) + 1.7;
                        }
                        else if (pokemonCp >= session.LogicSettings.ForceGreatThrowOverCp ||
                                 pokemonIv >= session.LogicSettings.ForceGreatThrowOverIv)
                        {
                            normalizedRecticleSize = Random.NextDouble() * (1.95 - 1.3) + 1.3;
                            hitTxt = "Great";
                        }
                        else
                        {
                            var regularThrow = 100 - (session.LogicSettings.ExcellentThrowChance +
                                                      session.LogicSettings.GreatThrowChance +
                                                      session.LogicSettings.NiceThrowChance);
                            var rnd = Random.Next(1, 101);

                            if (rnd <= regularThrow)
                            {
                                normalizedRecticleSize = Random.NextDouble() * (1 - 0.1) + 0.1;
                                hitTxt = "Ordinary";
                            }
                            else if (rnd <= regularThrow + session.LogicSettings.NiceThrowChance)
                            {
                                normalizedRecticleSize = Random.NextDouble() * (1.3 - 1) + 1;
                                hitTxt = "Nice";
                            }
                            else if (rnd <=
                                     regularThrow + session.LogicSettings.NiceThrowChance +
                                     session.LogicSettings.GreatThrowChance)
                            {
                                normalizedRecticleSize = Random.NextDouble() * (1.7 - 1.3) + 1.3;
                                hitTxt = "Great";
                            }

                            if (Random.NextDouble() * 100 > session.LogicSettings.CurveThrowChance)
                            {
                                spinModifier = 0.0;
                                spinTxt      = "Straight";
                            }
                        }

                        // Round to 2 decimals
                        normalizedRecticleSize = Math.Round(normalizedRecticleSize, 2);

                        // Missed throw check
                        int missChance = Random.Next(1, 101);
                        if (missChance <= session.LogicSettings.ThrowMissPercentage && session.LogicSettings.EnableMissedThrows)
                        {
                            hitPokemon = false;
                        }

                        Logger.Write($"(Threw ball) {hitTxt} throw, {spinTxt}-ball, HitPokemon = {hitPokemon}...", LogLevel.Debug);
                    }

                    caughtPokemonResponse =
                        await session.Client.Encounter.CatchPokemon(
                            encounter is EncounterResponse || encounter is IncenseEncounterResponse
                            ?pokemon.EncounterId
                            : _encounterId,
                            encounter is EncounterResponse || encounter is IncenseEncounterResponse
                            ?pokemon.SpawnPointId
                            : currentFortData.Id, pokeball, normalizedRecticleSize, spinModifier, hitPokemon);

                    var evt = new PokemonCaptureEvent()
                    {
                        Status    = caughtPokemonResponse.Status,
                        Latitude  = latitude,
                        Longitude = longitude
                    };

                    lastThrow = caughtPokemonResponse.Status;       // sets lastThrow status


                    if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                    {
                        var totalExp = 0;

                        foreach (var xp in caughtPokemonResponse.CaptureAward.Xp)
                        {
                            totalExp += xp;
                        }
                        var profile = await session.Client.Player.GetPlayer();

                        evt.Exp      = totalExp;
                        evt.Stardust = profile.PlayerData.Currencies.ToArray()[1].Amount;
                        evt.UniqueId = caughtPokemonResponse.CapturedPokemonId;

                        var pokemonSettings = await session.Inventory.GetPokemonSettings();

                        var pokemonFamilies = await session.Inventory.GetPokemonFamilies();

                        var setting =
                            pokemonSettings.FirstOrDefault(q => pokemon != null && q.PokemonId == pokemon.PokemonId);
                        var family = pokemonFamilies.FirstOrDefault(q => setting != null && q.FamilyId == setting.FamilyId);

                        if (family != null)
                        {
                            family.Candy_    += caughtPokemonResponse.CaptureAward.Candy.Sum();
                            evt.FamilyCandies = family.Candy_;
                        }
                        else
                        {
                            evt.FamilyCandies = caughtPokemonResponse.CaptureAward.Candy.Sum();
                        }

                        if (session.LogicSettings.UseCatchLimit)
                        {
                            session.Stats.AddPokemonTimestamp(DateTime.Now.Ticks);
                            Logger.Write($"(CATCH LIMIT) {session.Stats.GetNumPokemonsInLast24Hours()}/{session.LogicSettings.CatchPokemonLimit}",
                                         LogLevel.Info, ConsoleColor.Yellow);
                        }
                    }

                    evt.CatchType = encounter is EncounterResponse
                        ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal)
                        : encounter is DiskEncounterResponse
                            ? session.Translation.GetTranslation(TranslationString.CatchTypeLure)
                            : session.Translation.GetTranslation(TranslationString.CatchTypeIncense);

                    evt.CatchTypeText = encounter is EncounterResponse
                        ? "normal"
                        : encounter is DiskEncounterResponse
                            ? "lure"
                            : "incense";
                    evt.Id = encounter is EncounterResponse
                        ? pokemon.PokemonId : encounter?.PokemonData.PokemonId;
                    evt.EncounterId  = _encounterId;
                    evt.Move1        = PokemonInfo.GetPokemonMove1(encounteredPokemon);
                    evt.Move2        = PokemonInfo.GetPokemonMove2(encounteredPokemon);
                    evt.Expires      = pokemon?.ExpirationTimestampMs ?? 0;
                    evt.SpawnPointId = _spawnPointId;
                    evt.Level        = PokemonInfo.GetLevel(encounteredPokemon);
                    evt.Cp           = encounteredPokemon.Cp;
                    evt.MaxCp        = PokemonInfo.CalculateMaxCp(encounteredPokemon);
                    evt.Perfection   = Math.Round(PokemonInfo.CalculatePokemonPerfection(encounteredPokemon));
                    evt.Probability  = Math.Round(probability * 100, 2);
                    evt.Distance     = distance;
                    evt.Pokeball     = pokeball;
                    evt.Attempt      = attemptCounter;

                    await session.Inventory.RefreshCachedInventory();

                    evt.BallAmount = await session.Inventory.GetItemAmountByType(pokeball);

                    evt.Rarity = PokemonGradeHelper.GetPokemonGrade(evt.Id).ToString();

                    session.EventDispatcher.Send(evt);

                    attemptCounter++;

                    DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0);
                } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed ||
                         caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape);

                if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings))
                {
                    if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchFlee)
                    {
                        CatchFleeContinuouslyCount++;
                        if (CatchFleeContinuouslyCount > 10)
                        {
                            CatchFleeContinuouslyCount = 0;

                            throw new ActiveSwitchByRuleException()
                                  {
                                      MatchedRule  = SwitchRules.CatchFlee,
                                      ReachedValue = 10
                                  };
                        }
                    }
                    else
                    {
                        //reset if not catch flee.
                        CatchFleeContinuouslyCount = 0;
                    }
                }

                session.Actions.RemoveAll(x => x == Model.BotActions.Catch);

                if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings))
                {
                    ExecuteSwitcher(session, encounterEV);
                }

                if (session.LogicSettings.TransferDuplicatePokemonOnCapture &&
                    session.LogicSettings.TransferDuplicatePokemon &&
                    sessionAllowTransfer &&
                    caughtPokemonResponse != null &&
                    caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                {
                    if (session.LogicSettings.UseNearActionRandom)
                    {
                        await HumanRandomActionTask.TransferRandom(session, cancellationToken);
                    }
                    else
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 17
0
        public async void Execute()
        {
            EnabledButton(false, "Reloading Pokemon list.");
            await check();

            try
            {
                client = Logic.Logic._client;
                if (client.readyToUse != false)
                {
                    inventory = await client.Inventory.GetInventory();

                    pokemons =
                        inventory.InventoryDelta.InventoryItems
                        .Select(i => i.InventoryItemData?.PokemonData)
                        .Where(p => p != null && p?.PokemonId > 0)
                        .OrderByDescending(key => key.Cp);
                    var families = inventory.InventoryDelta.InventoryItems
                                   .Select(i => i.InventoryItemData?.Candy)
                                   .Where(p => p != null && (int)p?.FamilyId > 0)
                                   .OrderByDescending(p => (int)p.FamilyId);


                    var templates = await client.Download.GetItemTemplates();

                    var myPokemonSettings = templates.ItemTemplates.Select(i => i.PokemonSettings).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                    var pokemonSettings   = myPokemonSettings.ToList();

                    var myPokemonFamilies = inventory.InventoryDelta.InventoryItems.Select(i => i.InventoryItemData?.Candy).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                    var pokemonFamilies   = myPokemonFamilies.ToArray();
                    PokemonListView.BeginUpdate();

                    foreach (var pokemon in pokemons)
                    {
                        var listViewItem = new ListViewItem();
                        listViewItem.Tag = pokemon;
                        var currentCandy = families
                                           .Where(i => (int)i.FamilyId <= (int)pokemon.PokemonId)
                                           .Select(f => f.Candy_)
                                           .First();
                        listViewItem.SubItems.Add(string.Format("{0}", pokemon.Cp));
                        //<listViewItem.SubItems.Add(string.Format("{0}% {1}{2}{3} ({4})", PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0"), pokemon.IndividualAttack.ToString("X"), pokemon.IndividualDefense.ToString("X"), pokemon.IndividualStamina.ToString("X"), (45 - pokemon.IndividualAttack- pokemon.IndividualDefense- pokemon.IndividualStamina) ));
                        listViewItem.SubItems.Add(string.Format("{0}% {1}-{2}-{3}", PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0"), pokemon.IndividualAttack, pokemon.IndividualDefense, pokemon.IndividualStamina));
                        listViewItem.SubItems.Add(string.Format("{0}", PokemonInfo.GetLevel(pokemon)));
                        listViewItem.ImageKey = pokemon.PokemonId.ToString();
                        listViewItem.Text     = string.Format((pokemon.Favorite == 1) ? "{0} ★" : "{0}", StringUtils.getPokemonNameByLanguage(ClientSettings, (PokemonId)pokemon.PokemonId));

                        listViewItem.ToolTipText = StringUtils.ConvertTimeMSinString(pokemon.CreationTimeMs, "dd/MM/yyyy HH:mm:ss");
                        if (pokemon.Nickname != "")
                        {
                            listViewItem.ToolTipText += "\nNickname: " + pokemon.Nickname;
                        }

                        var settings    = pokemonSettings.Single(x => x.PokemonId == pokemon.PokemonId);
                        var familyCandy = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId);

                        if (settings.EvolutionIds.Count > 0 && familyCandy.Candy_ >= settings.CandyToEvolve)
                        {
                            listViewItem.SubItems.Add("Y (" + familyCandy.Candy_ + "/" + settings.CandyToEvolve + ")");
                            listViewItem.Checked = true;
                        }
                        else
                        {
                            if (settings.EvolutionIds.Count > 0)
                            {
                                listViewItem.SubItems.Add("N (" + familyCandy.Candy_ + "/" + settings.CandyToEvolve + ")");
                            }
                            else
                            {
                                listViewItem.SubItems.Add("N (" + familyCandy.Candy_ + "/Max)");
                            }
                        }
                        listViewItem.SubItems.Add(string.Format("{0}", Math.Round(pokemon.HeightM, 2)));
                        listViewItem.SubItems.Add(string.Format("{0}", Math.Round(pokemon.WeightKg, 2)));
                        listViewItem.SubItems.Add(string.Format("{0}/{1}", pokemon.Stamina, pokemon.StaminaMax));
                        listViewItem.SubItems.Add(string.Format("{0}", pokemon.Move1));
                        listViewItem.SubItems.Add(string.Format("{0} ({1})", pokemon.Move2, PokemonInfo.GetAttack(pokemon.Move2)));
                        listViewItem.SubItems.Add(string.Format("{0}", (int)pokemon.PokemonId));
                        listViewItem.SubItems.Add(string.Format("{0}", PokemonInfo.CalculatePokemonPerfectionCP(pokemon).ToString("0.00")));

                        AdditionalPokeData addData = additionalPokeData.FirstOrDefault(x => x.PokedexNumber == (int)pokemon.PokemonId);
                        if (addData != null)
                        {
                            listViewItem.SubItems.Add(addData.Type1);
                            listViewItem.SubItems.Add(addData.Type2);
                        }
                        else
                        {
                            listViewItem.SubItems.Add("");
                            listViewItem.SubItems.Add("");
                        }
                        // NOTE: yyyy/MM/dd is inverted order to can sort correctly as text.
                        listViewItem.SubItems.Add(StringUtils.ConvertTimeMSinString(pokemon.CreationTimeMs, "yyyy/MM/dd HH:mm:ss"));
                        listViewItem.SubItems.Add(pokemon.Pokeball.ToString().Replace("Item", ""));
                        listViewItem.SubItems.Add("" + pokemon.NumUpgrades);
                        listViewItem.SubItems.Add("" + pokemon.BattlesAttacked);
                        listViewItem.SubItems.Add("" + pokemon.BattlesDefended);

                        PokemonListView.Items.Add(listViewItem);
                    }
                    PokemonListView.EndUpdate();
                    PokemonListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                    EnabledButton(true);
                    btnUseLure.Enabled = false;
                    statusTexbox.Text  = string.Empty;
                    RefreshTitle();
                }
            }
            catch (Exception e)
            {
                Logger.Error("[PokemonList-Error] " + e.StackTrace);
                await Task.Delay(1000); // Lets the API make a little pause, so we dont get blocked

                Execute();
            }
        }
Ejemplo n.º 18
0
        private async Task CatchEncounter(EncounterResponse encounter, MapPokemon pokemon)
        {
            CatchPokemonResponse caughtPokemonResponse;
            var attemptCounter = 1;

            do
            {
                var probability  = encounter?.CaptureProbability?.CaptureProbability_?.FirstOrDefault();
                var bestPokeball = await GetBestBall(encounter);

                if (bestPokeball == MiscEnums.Item.ITEM_UNKNOWN)
                {
                    Logger.Write($"You don't own any Pokeballs :( - We missed a {pokemon.PokemonId} with CP {encounter?.WildPokemon?.PokemonData?.Cp}", LogLevel.Warning);
                    return;
                }
                var bestBerry = await GetBestBerry(encounter);

                var inventoryBerries = await _inventory.GetItems();

                var berries = inventoryBerries.FirstOrDefault(p => (ItemId)p.Item_ == bestBerry);
                if (bestBerry != ItemId.ItemUnknown && probability.HasValue && probability.Value < 0.35)
                {
                    await _client.UseCaptureItem(pokemon.EncounterId, bestBerry, pokemon.SpawnpointId);

                    berries.Count--;
                    Logger.Write($"{bestBerry} used, remaining: {berries.Count}", LogLevel.Berry);
                }

                var distance = LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, pokemon.Latitude, pokemon.Longitude);
                caughtPokemonResponse = await _client.CatchPokemon(pokemon.EncounterId, pokemon.SpawnpointId, pokemon.Latitude, pokemon.Longitude, bestPokeball);

                if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                {
                    foreach (var xp in caughtPokemonResponse.Scores.Xp)
                    {
                        _stats.AddExperience(xp);
                    }
                    _stats.IncreasePokemons();
                    var profile = await _client.GetProfile();

                    _stats.GetStardust(profile.Profile.Currency.ToArray()[1].Amount);
                }
                _stats.UpdateConsoleTitle(_client, _inventory);

                if (encounter?.CaptureProbability?.CaptureProbability_ != null)
                {
                    Func <MiscEnums.Item, string> returnRealBallName = a =>
                    {
                        switch (a)
                        {
                        case MiscEnums.Item.ITEM_POKE_BALL:
                            return("Poke");

                        case MiscEnums.Item.ITEM_GREAT_BALL:
                            return("Great");

                        case MiscEnums.Item.ITEM_ULTRA_BALL:
                            return("Ultra");

                        case MiscEnums.Item.ITEM_MASTER_BALL:
                            return("Master");

                        default:
                            return("Unknown");
                        }
                    };
                    var catchStatus = attemptCounter > 1
                        ? $"{caughtPokemonResponse.Status} Attempt #{attemptCounter}"
                        : $"{caughtPokemonResponse.Status}";

                    var receivedXp = caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess
                        ? $"and received XP {caughtPokemonResponse.Scores.Xp.Sum()}"
                        : $"";

                    Logger.Write($"({catchStatus}) | {pokemon.PokemonId} - Lvl {PokemonInfo.GetLevel(encounter?.WildPokemon?.PokemonData)} [CP {encounter?.WildPokemon?.PokemonData?.Cp}/{PokemonInfo.CalculateMaxCp(encounter?.WildPokemon?.PokemonData)} | IV: {PokemonInfo.CalculatePokemonPerfection(encounter?.WildPokemon?.PokemonData).ToString("0.00")}% perfect] | Chance: {(float)((int)(encounter?.CaptureProbability?.CaptureProbability_.First() * 100)) / 100} | {distance:0.##}m dist | with a {returnRealBallName(bestPokeball)}Ball {receivedXp}", LogLevel.Pokemon);
                }

                attemptCounter++;
            }while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed || caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape);
        }
Ejemplo n.º 19
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // Refresh inventory so that the player stats are fresh
            await session.Inventory.RefreshCachedInventory();

            var playerStats = (await session.Inventory.GetPlayerStats()).FirstOrDefault();

            if (playerStats == null)
            {
                return;
            }

            var kmWalked = playerStats.KmWalked;

            var incubators = (await session.Inventory.GetEggIncubators())
                             .Where(x => x.UsesRemaining > 0 || x.ItemId == ItemId.ItemIncubatorBasicUnlimited)
                             .OrderByDescending(x => x.ItemId == ItemId.ItemIncubatorBasicUnlimited)
                             .ToList();

            var unusedEggs = (await session.Inventory.GetEggs())
                             .Where(x => string.IsNullOrEmpty(x.EggIncubatorId))
                             .OrderBy(x => x.EggKmWalkedTarget - x.EggKmWalkedStart)
                             .ToList();

            var rememberedIncubatorsFilePath = Path.Combine(session.LogicSettings.ProfilePath, "temp", "incubators.json");
            var rememberedIncubators         = GetRememberedIncubators(rememberedIncubatorsFilePath);
            var pokemons = (await session.Inventory.GetPokemons()).ToList();

            // Check if eggs in remembered incubator usages have since hatched
            // (instead of calling session.Client.Inventory.GetHatchedEgg(), which doesn't seem to work properly)
            foreach (var incubator in rememberedIncubators)
            {
                var hatched = pokemons.FirstOrDefault(x => !x.IsEgg && x.Id == incubator.PokemonId);
                if (hatched == null)
                {
                    continue;
                }

                session.EventDispatcher.Send(new EggHatchedEvent
                {
                    Id         = hatched.Id,
                    PokemonId  = hatched.PokemonId,
                    Level      = PokemonInfo.GetLevel(hatched),
                    Cp         = hatched.Cp,
                    MaxCp      = PokemonInfo.CalculateMaxCp(hatched),
                    Perfection = Math.Round(PokemonInfo.CalculatePokemonPerfection(hatched), 2)
                });
            }

            var newRememberedIncubators = new List <IncubatorUsage>();

            foreach (var incubator in incubators)
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (incubator.PokemonId == 0)
                {
                    // Unlimited incubators prefer short eggs, limited incubators prefer long eggs
                    // Special case: If only one incubator is available at all, it will prefer long eggs
                    var egg = (incubator.ItemId == ItemId.ItemIncubatorBasicUnlimited && incubators.Count > 1)
                        ? unusedEggs.FirstOrDefault()
                        : unusedEggs.LastOrDefault();

                    if (egg == null)
                    {
                        continue;
                    }

                    var response = await session.Client.Inventory.UseItemEggIncubator(incubator.Id, egg.Id);

                    unusedEggs.Remove(egg);

                    newRememberedIncubators.Add(new IncubatorUsage {
                        IncubatorId = incubator.Id, PokemonId = egg.Id
                    });

                    session.EventDispatcher.Send(new EggIncubatorStatusEvent
                    {
                        IncubatorId = incubator.Id,
                        WasAddedNow = true,
                        PokemonId   = egg.Id,
                        KmToWalk    = egg.EggKmWalkedTarget,
                        KmRemaining = response.EggIncubator.TargetKmWalked - kmWalked
                    });
                }
                else
                {
                    newRememberedIncubators.Add(new IncubatorUsage
                    {
                        IncubatorId = incubator.Id,
                        PokemonId   = incubator.PokemonId
                    });

                    session.EventDispatcher.Send(new EggIncubatorStatusEvent
                    {
                        IncubatorId = incubator.Id,
                        PokemonId   = incubator.PokemonId,
                        KmToWalk    = incubator.TargetKmWalked - incubator.StartKmWalked,
                        KmRemaining = incubator.TargetKmWalked - kmWalked
                    });
                }
            }

            if (!newRememberedIncubators.SequenceEqual(rememberedIncubators))
            {
                SaveRememberedIncubators(newRememberedIncubators, rememberedIncubatorsFilePath);
            }
        }
Ejemplo n.º 20
0
        private async Task DisplayHighests()
        {
            Logger.Write("====== DisplayHighestsCP ======", LogLevel.Info, ConsoleColor.Yellow);
            var highestsPokemonCp = await _inventory.GetHighestsCp(10);

            foreach (var pokemon in highestsPokemonCp)
            {
                Logger.Write(
                    $"# CP {pokemon.Cp.ToString().PadLeft(4, ' ')}/{PokemonInfo.CalculateMaxCp(pokemon).ToString().PadLeft(4, ' ')} | ({PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}% perfect)\t| Lvl {PokemonInfo.GetLevel(pokemon).ToString("00")}\t NAME: '{pokemon.PokemonId}'",
                    LogLevel.Info, ConsoleColor.Yellow);
            }
            Logger.Write("====== DisplayHighestsPerfect ======", LogLevel.Info, ConsoleColor.Yellow);
            var highestsPokemonPerfect = await _inventory.GetHighestsPerfect(10);

            foreach (var pokemon in highestsPokemonPerfect)
            {
                Logger.Write(
                    $"# CP {pokemon.Cp.ToString().PadLeft(4, ' ')}/{PokemonInfo.CalculateMaxCp(pokemon).ToString().PadLeft(4, ' ')} | ({PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}% perfect)\t| Lvl {PokemonInfo.GetLevel(pokemon).ToString("00")}\t NAME: '{pokemon.PokemonId}'",
                    LogLevel.Info, ConsoleColor.Yellow);
            }
        }
Ejemplo n.º 21
0
        public static async Task Execute(ISession session)
        {
            var highestsPokemonCp = await session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var pokemonPairedWithStatsCp = highestsPokemonCp.Select(pokemon => Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon), PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon))).ToList();

            var highestsPokemonPerfect =
                await session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var pokemonPairedWithStatsIv = highestsPokemonPerfect.Select(pokemon => Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon), PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon))).ToList();

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "CP",
                PokemonList = pokemonPairedWithStatsCp
            });

            await Task.Delay(500);

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "IV",
                PokemonList = pokemonPairedWithStatsIv
            });

            var allPokemonInBag = session.LogicSettings.PrioritizeIvOverCp ? await session.Inventory.GetHighestsPerfect(1000) : await session.Inventory.GetHighestsCp(1000);

            if (session.LogicSettings.DumpPokemonStats)
            {
                const string dumpFileName = "PokeBagStats";
                Dumper.ClearDumpFile(session, dumpFileName);
                foreach (var pokemon in allPokemonInBag)
                {
                    Dumper.Dump(session, $"NAME: {pokemon.PokemonId.ToString().PadRight(16, ' ')}Lvl: { PokemonInfo.GetLevel(pokemon).ToString("00")}\t\tCP: { pokemon.Cp.ToString().PadRight(8, ' ')}\t\t IV: { PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}%", dumpFileName);
                }
            }
            await Task.Delay(500);
        }
Ejemplo n.º 22
0
        public static async Task Execute(ISession session)
        {
            var myPokemonFamilies = await session.Inventory.GetPokemonFamilies();

            var myPokeSettings = await session.Inventory.GetPokemonSettings();

            var highestsPokemonCp =
                await session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var pokemonPairedWithStatsCp =
                highestsPokemonCp.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),
                                 PokemonInfo.GetCandy(pokemon, myPokemonFamilies, myPokeSettings))).ToList();

            var highestsPokemonPerfect =
                await session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var pokemonPairedWithStatsIv =
                highestsPokemonPerfect.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),
                                 PokemonInfo.GetCandy(pokemon, myPokemonFamilies, myPokeSettings))).ToList();

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "CP",
                PokemonList = pokemonPairedWithStatsCp
            });

            await Task.Delay(500);

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "IV",
                PokemonList = pokemonPairedWithStatsIv
            });

            var allPokemonInBag = session.LogicSettings.PrioritizeIvOverCp
                ? await session.Inventory.GetHighestsPerfect(1000)
                : await session.Inventory.GetHighestsCp(1000);

            if (session.LogicSettings.DumpPokemonStats)
            {
                const string dumpFileName = "PokeBagStats";
                Dumper.ClearDumpFile(session, dumpFileName);
                Dumper.Dump(session, "pokemonid,pokemonlevel,cp,perfection,stamina,staminamax,move1,move2,candy,ownername,origin,heightm,weightkg,individualattack,individualdefense,individualstamina,cpmultiplier,battlesattacked,battlesdefended,creationtimems,numupgrades,additionalcpmultiplier,favorite,nickname", dumpFileName);
                foreach (var pokemon in allPokemonInBag)
                {
                    Dumper.Dump(session,
                                $"{pokemon.PokemonId},{PokemonInfo.GetLevel(pokemon)},{pokemon.Cp},{PokemonInfo.CalculatePokemonPerfection(pokemon)},{pokemon.Stamina},{pokemon.StaminaMax},{pokemon.Move1},{pokemon.Move2},{PokemonInfo.GetCandy(pokemon, myPokemonFamilies, myPokeSettings)},{pokemon.OwnerName},{pokemon.Origin},{pokemon.HeightM},{pokemon.WeightKg},{pokemon.IndividualAttack},{pokemon.IndividualDefense},{pokemon.IndividualStamina},{pokemon.CpMultiplier},{pokemon.BattlesAttacked},{pokemon.BattlesDefended},{pokemon.CreationTimeMs},{pokemon.NumUpgrades},{pokemon.AdditionalCpMultiplier},{pokemon.Favorite},{pokemon.Nickname}",
                                dumpFileName);
                }
            }
            await Task.Delay(500);
        }
Ejemplo n.º 23
0
        public async Task <IEnumerable <PokemonData> > GetDuplicatePokemonToTransfer(
            IEnumerable <PokemonId> pokemonsNotToTransfer, IEnumerable <PokemonId> pokemonsToEvolve,
            bool keepPokemonsThatCanEvolve = false, bool prioritizeIVoverCp = false
            )
        {
            var myPokemon = await GetPokemons();

            var myPokemonList = myPokemon.ToList();

            var pokemonToTransfer = myPokemonList.Where(p => !pokemonsNotToTransfer.Contains(p.PokemonId) && p.DeployedFortId == string.Empty && p.Favorite == 0).ToList();

            try
            {
                pokemonToTransfer =
                    pokemonToTransfer.Where(
                        p =>
                {
                    var pokemonTransferFilter = GetPokemonTransferFilter(p.PokemonId);

                    return
                    (!pokemonTransferFilter.MovesOperator.BoolFunc(
                         pokemonTransferFilter.Moves.Intersect(new[] { p.Move1, p.Move2 }).Any(),
                         pokemonTransferFilter.KeepMinOperator.BoolFunc(
                             p.Cp >= pokemonTransferFilter.KeepMinCp,
                             PokemonInfo.CalculatePokemonPerfection(p) >= pokemonTransferFilter.KeepMinIvPercentage,
                             pokemonTransferFilter.KeepMinOperator.ReverseBoolFunc(
                                 pokemonTransferFilter.KeepMinOperator.InverseBool(pokemonTransferFilter.UseKeepMinLvl),
                                 PokemonInfo.GetLevel(p) >= pokemonTransferFilter.KeepMinLvl))));
                }).ToList();
            }
            catch (Exception e)
            {
                throw e;
            }

            var myPokemonSettings = await GetPokemonSettings();

            var pokemonSettings = myPokemonSettings.ToList();

            var myPokemonFamilies = await GetPokemonFamilies();

            var pokemonFamilies = myPokemonFamilies.ToArray();

            var results = new List <PokemonData>();

            foreach (var pokemonGroupToTransfer in pokemonToTransfer.GroupBy(p => p.PokemonId).ToList())
            {
                var amountToKeepInStorage = Math.Max(GetPokemonTransferFilter(pokemonGroupToTransfer.Key).KeepMinDuplicatePokemon, 0);

                var settings    = pokemonSettings.Single(x => x.PokemonId == pokemonGroupToTransfer.Key);
                var familyCandy = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId);

                int?modFromEvolve = null;

                if (keepPokemonsThatCanEvolve &&
                    pokemonsToEvolve.Contains(pokemonGroupToTransfer.Key) &&
                    settings.CandyToEvolve > 0 &&
                    settings.EvolutionIds.Count != 0)
                {
                    var possibleCountToEvolve = familyCandy.Candy_ / settings.CandyToEvolve;
                    amountToKeepInStorage = Math.Max(amountToKeepInStorage, possibleCountToEvolve);

                    //remain candy
                    modFromEvolve = familyCandy.Candy_ % settings.CandyToEvolve;
                }

                var inStorage = myPokemonList.Count(data => data.PokemonId == pokemonGroupToTransfer.Key);

                var weakPokemonCount = pokemonGroupToTransfer.Count();

                var needToRemove = inStorage - amountToKeepInStorage;
                if (needToRemove <= 0)
                {
                    continue;
                }

                var canBeRemoved = Math.Min(needToRemove, weakPokemonCount);

                if (canBeRemoved <= 0)
                {
                    continue;
                }

                //Lets calc new canBeRemoved pokemons according to transferring some of them and use it as future candy to keepPokemonsThatCanEvolve
                if (modFromEvolve.HasValue)
                {
                    // its an solution in fixed numbers of equations with two variables
                    // (N = X + Y, X + C >= Y * E) -> (X >= (N * E - C / 1 + E)
                    // where N - current canBeRemoved,  X - new canBeRemoved, Y - possible to keep more, E - CandyToEvolve, C - modFromEvolve(remain candy) ) )
                    canBeRemoved = (settings.CandyToEvolve * canBeRemoved - modFromEvolve.Value) / (1 + settings.CandyToEvolve) +
                                   Math.Sign((settings.CandyToEvolve * canBeRemoved - modFromEvolve.Value) % (1 + settings.CandyToEvolve));
                }

                var skipCount = weakPokemonCount - canBeRemoved;

                if (prioritizeIVoverCp)
                {
                    results.AddRange(pokemonGroupToTransfer
                                     .OrderByDescending(PokemonInfo.CalculatePokemonPerfection)
                                     .ThenByDescending(n => n.Cp)
                                     .Skip(skipCount));
                }
                else
                {
                    results.AddRange(pokemonGroupToTransfer
                                     .OrderByDescending(x => x.Cp)
                                     .ThenByDescending(PokemonInfo.CalculatePokemonPerfection)
                                     .Skip(skipCount));
                }
            }

            #region For testing

            /*
             * results.ForEach(data =>
             * {
             *  var bestPokemonOfType = (_logicSettings.PrioritizeIvOverCp
             *   ? myPokemonList.Where(x => x.PokemonId == data.PokemonId)
             *  .OrderByDescending(x => x.Cp)
             *  .FirstOrDefault()
             *   : myPokemonList.Where(x => x.PokemonId == data.PokemonId)
             *  .OrderByDescending(PokemonInfo.CalculatePokemonPerfection)
             *  .FirstOrDefault()) ?? data;
             *
             *  var perfection = PokemonInfo.CalculatePokemonPerfection(data);
             *  var cp = data.Cp;
             *
             *  var bestPerfection = PokemonInfo.CalculatePokemonPerfection(bestPokemonOfType);
             *  var bestCp = bestPokemonOfType.Cp;
             * });
             */
            #endregion

            return(results);
        }
Ejemplo n.º 24
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var prevState = session.State;

            session.State = BotState.Evolve;
            // Refresh inventory so that the player stats are fresh
            await session.Inventory.RefreshCachedInventory();

            var pokemonToEvolveTask = await session.Inventory.GetPokemonToEvolve(session.LogicSettings.PokemonsToEvolve);

            var pokemonToEvolve = pokemonToEvolveTask.Where(x => string.IsNullOrEmpty(x.DeployedFortId)).ToList();

            if (pokemonToEvolve.Any())
            {
                var inventoryContent = await session.Inventory.GetItems();

                var luckyEggs = inventoryContent.Where(p => p.ItemId == ItemId.ItemLuckyEgg);
                var luckyEgg  = luckyEggs.FirstOrDefault();

                //maybe there can be a warning message as an else condition of luckyEgg checks, like;
                //"There is no Lucky Egg, so, your UseLuckyEggsMinPokemonAmount setting bypassed."
                if (session.LogicSettings.UseLuckyEggsWhileEvolving && luckyEgg != null && luckyEgg.Count > 0)
                {
                    if (pokemonToEvolve.Count >= session.LogicSettings.UseLuckyEggsMinPokemonAmount)
                    {
                        await UseLuckyEgg(session);
                    }
                    else
                    {
                        // Wait until we have enough pokemon
                        session.EventDispatcher.Send(new UseLuckyEggMinPokemonEvent
                        {
                            Diff       = session.LogicSettings.UseLuckyEggsMinPokemonAmount - pokemonToEvolve.Count,
                            CurrCount  = pokemonToEvolve.Count,
                            MinPokemon = session.LogicSettings.UseLuckyEggsMinPokemonAmount
                        });
                        return;
                    }
                }
                var pokemonFamilies = session.Inventory.GetPokemonFamilies().Result;
                foreach (var pokemon in pokemonToEvolve)
                {
                    // no cancellationToken.ThrowIfCancellationRequested here, otherwise the lucky egg would be wasted.
                    var evolveResponse = await session.Client.Inventory.EvolvePokemon(pokemon.Id);

                    session.EventDispatcher.Send(new PokemonEvolveEvent
                    {
                        Uid    = pokemon.Id,
                        Id     = pokemon.PokemonId,
                        Exp    = evolveResponse.ExperienceAwarded,
                        Result = evolveResponse.Result
                    });


                    if (evolveResponse.EvolvedPokemonData != null)
                    {
                        var pokemonSettings = session.Inventory.GetPokemonSettings().Result.ToList();
                        var setting         = pokemonSettings.Single(q => q.PokemonId == evolveResponse.EvolvedPokemonData.PokemonId);
                        var family          = pokemonFamilies.First(q => q.FamilyId == setting.FamilyId);
                        session.EventDispatcher.Send(new PokemonEvolveDoneEvent
                        {
                            Uid        = evolveResponse.EvolvedPokemonData.Id,
                            Id         = evolveResponse.EvolvedPokemonData.PokemonId,
                            Cp         = evolveResponse.EvolvedPokemonData.Cp,
                            Perfection = evolveResponse.EvolvedPokemonData.CalculatePokemonPerfection(),
                            Family     = family.FamilyId,
                            Candy      = family.Candy_,
                            Level      = PokemonInfo.GetLevel(pokemon),
                            Move1      = pokemon.Move1,
                            Move2      = pokemon.Move2,
                            Type1      = setting.Type,
                            Type2      = setting.Type2,
                            Stats      = setting.Stats,
                            MaxCp      = (int)PokemonInfo.GetMaxCpAtTrainerLevel(pokemon, session.Runtime.CurrentLevel),
                            Stamina    = pokemon.Stamina,
                            MaxStamina = pokemon.StaminaMax
                        });
                    }
                    await DelayingEvolveUtils.Delay(session.LogicSettings.DelayEvolvePokemon, 0, session.LogicSettings.DelayEvolveVariation);
                }
            }
            session.State = prevState;
        }
Ejemplo n.º 25
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
            if (!session.LogicSettings.TransferWeakPokemon)
            {
                return;
            }

            if (session.LogicSettings.AutoFavoritePokemon)
            {
                await FavoritePokemonTask.Execute(session, cancellationToken);
            }

            var pokemons = session.Inventory.GetPokemons();

            if (session.LogicSettings.UseBulkTransferPokemon)
            {
                int buff = session.LogicSettings.BulkTransferStogareBuffer;
                //check for bag, if bag is nearly full, then process bulk transfer.
                var maxStorage = session.Profile.PlayerData.MaxPokemonStorage;
                var totalEggs  = session.Inventory.GetEggs();
                if ((maxStorage - totalEggs.Count() - buff) > pokemons.Count())
                {
                    return;
                }
            }

            var pokemonDatas = pokemons as IList <PokemonData> ?? pokemons.ToList();

            var buddy = session.Profile.PlayerData.BuddyPokemon;

            var pokemonsFiltered =
                pokemonDatas.Where(pokemon => !session.LogicSettings.PokemonsNotToTransfer.Contains(pokemon.PokemonId) &&
                                   pokemon.Favorite == 0 &&
                                   pokemon.Id != buddy.Id &&
                                   pokemon.DeployedFortId == string.Empty)
                .ToList().OrderBy(poke => poke.Cp);

            if (session.LogicSettings.KeepPokemonsThatCanEvolve)
            {
                var pokemonToEvolve = session.Inventory.GetPokemonToEvolve(session.LogicSettings.PokemonEvolveFilters);

                pokemonsFiltered =
                    pokemonDatas.Where(pokemon => !pokemonToEvolve.Any(p => p.Id == pokemon.Id))
                    .ToList().OrderBy(poke => poke.Cp);
            }

            var orderedPokemon     = pokemonsFiltered.OrderBy(poke => poke.Cp);
            var pokemonToTransfers = new List <PokemonData>();

            foreach (var pokemon in orderedPokemon)
            {
                TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
                cancellationToken.ThrowIfCancellationRequested();
                if ((pokemon.Cp >= session.LogicSettings.KeepMinCp) ||
                    (PokemonInfo.CalculatePokemonPerfection(pokemon) >= session.LogicSettings.KeepMinIvPercentage &&
                     session.LogicSettings.PrioritizeIvOverCp) ||
                    (PokemonInfo.GetLevel(pokemon) >= session.LogicSettings.KeepMinLvl && session.LogicSettings.UseKeepMinLvl) ||
                    pokemon.Favorite == 1)
                {
                    continue;
                }

                if (session.LogicSettings.UseBulkTransferPokemon)
                {
                    pokemonToTransfers.Add(pokemon);
                }
                else
                {
                    await session.Client.Inventory.TransferPokemon(pokemon.Id);

                    PrintTransferedPokemonInfo(session, pokemon);

                    await DelayingUtils.DelayAsync(session.LogicSettings.TransferActionDelay, 0, cancellationToken);
                }
            }
            if (session.LogicSettings.UseBulkTransferPokemon && pokemonToTransfers.Count > 0)
            {
                int page = orderedPokemon.Count() / session.LogicSettings.BulkTransferSize + 1;
                for (int i = 0; i < page; i++)
                {
                    var batchTransfer = orderedPokemon.Skip(i * session.LogicSettings.BulkTransferSize).Take(session.LogicSettings.BulkTransferSize);
                    var t             = await session.Client.Inventory.TransferPokemons(batchTransfer.Select(x => x.Id).ToList());

                    if (t.Result == ReleasePokemonResponse.Types.Result.Success)
                    {
                        foreach (var duplicatePokemon in batchTransfer)
                        {
                            PrintTransferedPokemonInfo(session, duplicatePokemon);
                        }
                    }
                    else
                    {
                        session.EventDispatcher.Send(new WarnEvent()
                        {
                            Message = session.Translation.GetTranslation(TranslationString.BulkTransferFailed, orderedPokemon.Count())
                        });
                    }
                }
            }

            // Evolve after transfer.
            await EvolvePokemonTask.Execute(session, cancellationToken);
        }
        public static async Task Execute(ISession session, ulong pokemonId, CancellationToken cancellationToken)
        {
            if (!await CheckBotStateTask.Execute(session, cancellationToken))
            {
                return;
            }

            var prevState = session.State;

            session.State = BotState.Evolve;
            var all = await session.Inventory.GetPokemons();

            var pokemons = all.OrderByDescending(x => x.Cp).ThenBy(n => n.StaminaMax);
            var pokemon  = pokemons.FirstOrDefault(p => p.Id == pokemonId);


            if (pokemon == null)
            {
                return;
            }

            var pokemonFamilies = await session.Inventory.GetPokemonFamilies();

            var pokemonSettings = (await session.Inventory.GetPokemonSettings()).ToList();
            var setting         = pokemonSettings.Single(q => q.PokemonId == pokemon.PokemonId);
            var family          = pokemonFamilies.First(q => q.FamilyId == setting.FamilyId);

            if (!string.IsNullOrEmpty(pokemon.DeployedFortId))
            {
                session.EventDispatcher.Send(new WarnEvent()
                {
                    Message = $"Pokemon {(string.IsNullOrEmpty(pokemon.Nickname) ? pokemon.PokemonId.ToString() : pokemon.Nickname)} is signed to defend a GYM!"
                });
                return;
            }

            if (family.Candy_ < setting.CandyToEvolve)
            {
                session.EventDispatcher.Send(new WarnEvent()
                {
                    Message = $"Miss some candies to evolve ({family.Candy_}/{setting.CandyToEvolve}), cancelling..."
                });
                return;
            }

            var evolveResponse = await session.Client.Inventory.EvolvePokemon(pokemon.Id);

            session.EventDispatcher.Send(new PokemonEvolveEvent
            {
                Uid    = pokemon.Id,
                Id     = pokemon.PokemonId,
                Exp    = evolveResponse.ExperienceAwarded,
                Result = evolveResponse.Result
            });

            if (evolveResponse.EvolvedPokemonData != null)
            {
                family.Candy_ -= setting.CandyToEvolve;
                setting        = pokemonSettings.Single(q => q.PokemonId == evolveResponse.EvolvedPokemonData.PokemonId);
                family         = pokemonFamilies.First(q => q.FamilyId == setting.FamilyId);
                session.EventDispatcher.Send(new PokemonEvolveDoneEvent
                {
                    Uid           = evolveResponse.EvolvedPokemonData.Id,
                    Id            = evolveResponse.EvolvedPokemonData.PokemonId,
                    Cp            = evolveResponse.EvolvedPokemonData.Cp,
                    Perfection    = evolveResponse.EvolvedPokemonData.CalculatePokemonPerfection(),
                    Family        = family.FamilyId,
                    Level         = PokemonInfo.GetLevel(evolveResponse.EvolvedPokemonData),
                    Candy         = family.Candy_,
                    Type1         = setting.Type,
                    Type2         = setting.Type2,
                    Stats         = setting.Stats,
                    MaxCp         = (int)PokemonInfo.GetMaxCpAtTrainerLevel(pokemon, session.Runtime.CurrentLevel),
                    Stamina       = pokemon.Stamina,
                    MaxStamina    = pokemon.StaminaMax,
                    Move1         = evolveResponse.EvolvedPokemonData.Move1,
                    Move2         = evolveResponse.EvolvedPokemonData.Move2,
                    PossibleCp    = (int)PokemonInfo.GetMaxCpAtTrainerLevel(pokemon, session.Runtime.CurrentLevel),
                    CandyToEvolve = setting.CandyToEvolve
                });
            }
            await DelayingUtils.Delay(session.LogicSettings.DelayEvolvePokemon, 25000);

            session.State = prevState;
        }
Ejemplo n.º 27
0
        public async Task ExportPokemonToCSV(PlayerData player, string filename = "PokeList.csv")
        {
            if (player == null)
            {
                return;
            }
            var stats = await GetPlayerStats();

            var stat = stats.FirstOrDefault();

            if (stat == null)
            {
                return;
            }

            if (!Directory.Exists(export_path))
            {
                Directory.CreateDirectory(export_path);
            }
            if (Directory.Exists(export_path))
            {
                try
                {
                    string pokelist_file = Path.Combine(export_path, $"Profile_{player.Username}_{filename}");
                    if (File.Exists(pokelist_file))
                    {
                        File.Delete(pokelist_file);
                    }
                    string ls     = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
                    string header = "PokemonID,Name,NickName,CP / MaxCP,Perfection,Attack 1,Attack 2,HP,Attk,Def,Stamina,Familie Candies,previewLink";
                    File.WriteAllText(pokelist_file, $"{header.Replace(",", $"{ls}")}");

                    var AllPokemon = await GetHighestsPerfect();

                    var myPokemonSettings = await GetPokemonSettings();

                    var pokemonSettings   = myPokemonSettings.ToList();
                    var myPokemonFamilies = await GetPokemonFamilies();

                    var   pokemonFamilies  = myPokemonFamilies.ToArray();
                    int   trainerLevel     = stat.Level;
                    int[] exp_req          = new[] { 0, 1000, 3000, 6000, 10000, 15000, 21000, 28000, 36000, 45000, 55000, 65000, 75000, 85000, 100000, 120000, 140000, 160000, 185000, 210000, 260000, 335000, 435000, 560000, 710000, 900000, 1100000, 1350000, 1650000, 2000000, 2500000, 3000000, 3750000, 4750000, 6000000, 7500000, 9500000, 12000000, 15000000, 20000000 };
                    int   exp_req_at_level = exp_req[stat.Level - 1];

                    using (var w = File.AppendText(pokelist_file))
                    {
                        w.WriteLine("");
                        foreach (var pokemon in AllPokemon)
                        {
                            string toEncode = $"{(int)pokemon.PokemonId}" + "," + trainerLevel + "," + PokemonInfo.GetLevel(pokemon) + "," + pokemon.Cp + "," + pokemon.Stamina;
                            //Generate base64 code to make it viewable here https://jackhumbert.github.io/poke-rater/#MTUwLDIzLDE3LDE5MDIsMTE4
                            var    encoded        = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(toEncode));
                            var    settings       = pokemonSettings.Single(x => x.PokemonId == pokemon.PokemonId);
                            var    familiecandies = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId).Candy_;
                            string perfection     = pokemon.GetPerfection().ToString("0.00");
                            perfection = perfection.Replace(",", ls == "," ? "." : ",");
                            string content_part1 = $"{(int)pokemon.PokemonId},{pokemon.PokemonId},{pokemon.Nickname},{pokemon.Cp}/{PokemonInfo.CalculateMaxCP(pokemon)},";
                            string content_part2 = $",{pokemon.Move1},{pokemon.Move2},{pokemon.Stamina},{pokemon.IndividualAttack},{pokemon.IndividualDefense},{pokemon.IndividualStamina},{familiecandies},https://jackhumbert.github.io/poke-rater/#{encoded}";
                            string content       = $"{content_part1.Replace(",", $"{ls}")}{perfection}{content_part2.Replace(",", $"{ls}")}";
                            w.WriteLine($"{content}");
                        }
                        w.Close();
                    }
                    //Logger.Write($"Export Player Infos and all Pokemon to \"\\Export\\{filename}\"", LogLevel.Info);
                }
                catch
                {
                    Logger.Write("Export Player Infos and all Pokemons to CSV not possible. File seems be in use!", LogLevel.Warning);
                }
            }
        }
Ejemplo n.º 28
0
        public static async Task Execute(ISession session)
        {
            var highestsPokemonCp = await
                                    session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart).ConfigureAwait(false);

            var pokemonPairedWithStatsCp =
                highestsPokemonCp.Select(
                    pokemon =>
                    Tuple.Create(
                        pokemon,
                        PokemonInfo.CalculateMaxCp(pokemon.PokemonId),
                        PokemonInfo.CalculatePokemonPerfection(pokemon),
                        PokemonInfo.GetLevel(pokemon),
                        PokemonInfo.GetPokemonMove1(pokemon),
                        PokemonInfo.GetPokemonMove2(pokemon),
                        PokemonInfo.GetCandy(session, pokemon).Result
                        )
                    )
                .ToList();

            var highestsPokemonPerfect = await
                                         session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart).ConfigureAwait(false);

            var pokemonPairedWithStatsIv =
                highestsPokemonPerfect.Select(
                    pokemon =>
                    Tuple.Create(
                        pokemon,
                        PokemonInfo.CalculateMaxCp(pokemon.PokemonId),
                        PokemonInfo.CalculatePokemonPerfection(pokemon),
                        PokemonInfo.GetLevel(pokemon),
                        PokemonInfo.GetPokemonMove1(pokemon),
                        PokemonInfo.GetPokemonMove2(pokemon),
                        PokemonInfo.GetCandy(session, pokemon).Result
                        )
                    )
                .ToList();

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "CP",
                PokemonList = pokemonPairedWithStatsCp
            });

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "IV",
                PokemonList = pokemonPairedWithStatsIv
            });

            var allPokemonInBag = session.LogicSettings.PrioritizeIvOverCp
                ? await session.Inventory.GetHighestsPerfect(1000).ConfigureAwait(false)
                : await session.Inventory.GetHighestsCp(1000).ConfigureAwait(false);

            if (session.LogicSettings.DumpPokemonStats)
            {
                _MultiAccountManager = new MultiAccountManager();
                var    account      = _MultiAccountManager.GetCurrentAccount();
                string dumpFileName = account.Nickname; // "-PokeBagStats";
                try
                {
                    Dumper.ClearDumpFile(session, dumpFileName);

                    string[] data =
                    {
                        "Pokemon",
                        "Nickname",
                        "Slashed",
                        "Level",
                        "CP",
                        "IV",
                        "Candies",
                        "Power Ups",
                        "Favorite",
                        "Stamina",
                        "Stamina Max",
                        "Move1",
                        "Move2",
                        "Owner Name",
                        "Origin",
                        "Height(M)",
                        "Weight(KG)",
                        "Attack",
                        "Defense",
                        "Stamina",
                        "CP Multi",
                        "Gyms Attacked",
                        "Gyms Defended",
                        "Creationtimems",
                        "Add CP Multi"
                    };
                    Dumper.Dump(session, data, dumpFileName);

                    // set culture to OS default
                    CultureInfo prevCulture = Thread.CurrentThread.CurrentCulture;
                    CultureInfo culture     = CultureInfo.CurrentUICulture;
                    Thread.CurrentThread.CurrentCulture = culture;

                    foreach (var pokemon in allPokemonInBag)
                    {
                        string[] pokemonData =
                        {
                            session.Translation.GetPokemonTranslation(pokemon.PokemonId),
                            pokemon.Nickname,
                            pokemon.IsBad.ToString(),
                            PokemonInfo.GetLevel(pokemon).ToString(),
                            pokemon.Cp.ToString(),
                            PokemonInfo.CalculatePokemonPerfection(pokemon).ToString(),
                            PokemonInfo.GetCandy(session,                                pokemon).ToString(),
                            pokemon.NumUpgrades.ToString(),
                            pokemon.Favorite.ToString(),
                            pokemon.Stamina.ToString(),
                            pokemon.StaminaMax.ToString(),
                            pokemon.Move1.ToString(),
                            pokemon.Move2.ToString(),
                            pokemon.OwnerName,
                            pokemon.Origin.ToString(),
                            pokemon.HeightM.ToString(),
                            pokemon.WeightKg.ToString(),
                            pokemon.IndividualAttack.ToString(),
                            pokemon.IndividualDefense.ToString(),
                            pokemon.IndividualStamina.ToString(),
                            pokemon.CpMultiplier.ToString(),
                            pokemon.BattlesAttacked.ToString(),
                            pokemon.BattlesDefended.ToString(),
                            pokemon.CreationTimeMs.ToString(),
                            pokemon.AdditionalCpMultiplier.ToString()
                        };
                        Dumper.Dump(session, pokemonData, dumpFileName);
                    }

                    // restore culture
                    Thread.CurrentThread.CurrentCulture = prevCulture;
                }
                catch (IOException)
                {
                    session.EventDispatcher.Send(
                        new ErrorEvent {
                        Message = $"Could not write {dumpFileName} dump file."
                    }
                        );
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Because this function sometime being called inside loop, return true it mean we don't want break look, false it mean not need to call this , break a loop from caller function
        /// </summary>
        /// <param name="session"></param>
        /// <param name="cancellationToken"></param>
        /// <param name="encounter"></param>
        /// <param name="pokemon"></param>
        /// <param name="currentFortData"></param>
        /// <param name="sessionAllowTransfer"></param>
        /// <returns></returns>
        public static async Task <bool> Execute(ISession session,
                                                CancellationToken cancellationToken,
                                                dynamic encounter,
                                                MapPokemon pokemon,
                                                FortData currentFortData,
                                                bool sessionAllowTransfer)
        {
            var manager = TinyIoCContainer.Current.Resolve <MultiAccountManager>();

            manager.ThrowIfSwitchAccountRequested();
            // If the encounter is null nothing will work below, so exit now
            if (encounter == null)
            {
                return(true);
            }

            var totalBalls = (await session.Inventory.GetItems().ConfigureAwait(false)).Where(x => x.ItemId == ItemId.ItemPokeBall || x.ItemId == ItemId.ItemGreatBall || x.ItemId == ItemId.ItemUltraBall).Sum(x => x.Count);

            if (session.SaveBallForByPassCatchFlee && totalBalls < BALL_REQUIRED_TO_BYPASS_CATCHFLEE)
            {
                return(false);
            }

            // Exit if user defined max limits reached
            if (session.Stats.CatchThresholdExceeds(session))
            {
                if (manager.AllowMultipleBot() &&
                    session.LogicSettings.MultipleBotConfig.SwitchOnCatchLimit &&
                    TinyIoCContainer.Current.Resolve <MultiAccountManager>().AllowSwitch())
                {
                    throw new ActiveSwitchByRuleException()
                          {
                              MatchedRule  = SwitchRules.CatchLimitReached,
                              ReachedValue = session.LogicSettings.CatchPokemonLimit
                          };
                }

                return(false);
            }
            using (var block = new BlockableScope(session, BotActions.Catch))
            {
                if (!await block.WaitToRun().ConfigureAwait(false))
                {
                    return(true);
                }

                AmountOfBerries = new Dictionary <ItemId, int>();

                cancellationToken.ThrowIfCancellationRequested();

                float probability = encounter.CaptureProbability?.CaptureProbability_[0];

                PokemonData encounteredPokemon;
                long        unixTimeStamp;
                ulong       _encounterId;
                string      _spawnPointId;

                // Calling from CatchNearbyPokemonTask and SnipePokemonTask
                if (encounter is EncounterResponse &&
                    (encounter?.Status == EncounterResponse.Types.Status.EncounterSuccess))
                {
                    encounteredPokemon = encounter.WildPokemon?.PokemonData;
                    unixTimeStamp      = encounter.WildPokemon?.LastModifiedTimestampMs
                                         + encounter.WildPokemon?.TimeTillHiddenMs;
                    _spawnPointId = encounter.WildPokemon?.SpawnPointId;
                    _encounterId  = encounter.WildPokemon?.EncounterId;
                }
                // Calling from CatchIncensePokemonTask
                else if (encounter is IncenseEncounterResponse &&
                         (encounter?.Result == IncenseEncounterResponse.Types.Result.IncenseEncounterSuccess))
                {
                    encounteredPokemon = encounter?.PokemonData;
                    unixTimeStamp      = pokemon.ExpirationTimestampMs;
                    _spawnPointId      = pokemon.SpawnPointId;
                    _encounterId       = pokemon.EncounterId;
                }
                // Calling from CatchLurePokemon
                else if (encounter is DiskEncounterResponse &&
                         encounter?.Result == DiskEncounterResponse.Types.Result.Success &&
                         !(currentFortData == null))
                {
                    encounteredPokemon = encounter?.PokemonData;
                    unixTimeStamp      = currentFortData.LureInfo.LureExpiresTimestampMs;
                    _spawnPointId      = currentFortData.Id;
                    _encounterId       = currentFortData.LureInfo.EncounterId;
                }
                else
                {
                    return(true); // No success to work with, exit
                }
                // Check for pokeballs before proceeding
                var pokeball = await GetBestBall(session, encounteredPokemon, probability).ConfigureAwait(false);

                if (pokeball == ItemId.ItemUnknown)
                {
                    Logger.Write(session.Translation.GetTranslation(TranslationString.ZeroPokeballInv));
                    return(false);
                }

                // Calculate CP and IV
                var pokemonCp = encounteredPokemon?.Cp;
                var pokemonIv = PokemonInfo.CalculatePokemonPerfection(encounteredPokemon);
                var lv        = PokemonInfo.GetLevel(encounteredPokemon);

                // Calculate distance away
                var latitude = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.Latitude
                    : currentFortData.Latitude;
                var longitude = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.Longitude
                    : currentFortData.Longitude;

                var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                       session.Client.CurrentLongitude, latitude, longitude);
                if (session.LogicSettings.ActivateMSniper)
                {
                    var newdata = new MSniperServiceTask.EncounterInfo();
                    newdata.EncounterId  = _encounterId.ToString();
                    newdata.Iv           = Math.Round(pokemonIv, 2);
                    newdata.Latitude     = latitude.ToString("G17", CultureInfo.InvariantCulture);
                    newdata.Longitude    = longitude.ToString("G17", CultureInfo.InvariantCulture);
                    newdata.PokemonId    = (int)(encounteredPokemon?.PokemonId ?? 0);
                    newdata.PokemonName  = encounteredPokemon?.PokemonId.ToString();
                    newdata.SpawnPointId = _spawnPointId;
                    newdata.Move1        = PokemonInfo.GetPokemonMove1(encounteredPokemon).ToString();
                    newdata.Move2        = PokemonInfo.GetPokemonMove2(encounteredPokemon).ToString();
                    newdata.Expiration   = unixTimeStamp;

                    session.EventDispatcher.Send(newdata);
                }

                DateTime expiredDate =
                    new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(unixTimeStamp));
                var encounterEV = new EncounteredEvent()
                {
                    Latitude        = latitude,
                    Longitude       = longitude,
                    PokemonId       = encounteredPokemon.PokemonId,
                    IV              = pokemonIv,
                    Level           = (int)lv,
                    Expires         = expiredDate.ToUniversalTime(),
                    ExpireTimestamp = unixTimeStamp,
                    SpawnPointId    = _spawnPointId,
                    EncounterId     = _encounterId.ToString(),
                    Move1           = PokemonInfo.GetPokemonMove1(encounteredPokemon).ToString(),
                    Move2           = PokemonInfo.GetPokemonMove2(encounteredPokemon).ToString(),
                };

                //add catch to avoid snipe duplicate
                string uniqueCacheKey =
                    $"{session.Settings.Username}{Math.Round(encounterEV.Latitude, 6)}{(int)encounterEV.PokemonId}{Math.Round(encounterEV.Longitude, 6)}";
                session.Cache.Add(uniqueCacheKey, encounterEV, DateTime.Now.AddMinutes(30));

                session.EventDispatcher.Send(encounterEV);

                if (IsNotMetWithCatchCriteria(session, encounteredPokemon, pokemonIv, lv, pokemonCp))
                {
                    session.EventDispatcher.Send(new NoticeEvent
                    {
                        Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped,
                                                                     encounteredPokemon.PokemonId)
                    });
                    session.Cache.Add(_encounterId.ToString(), encounteredPokemon, expiredDate);
                    Logger.Write(
                        $"Filter catch not met. {encounteredPokemon.PokemonId.ToString()} IV {pokemonIv} lv {lv} {pokemonCp} move1 {PokemonInfo.GetPokemonMove1(encounteredPokemon)} move 2 {PokemonInfo.GetPokemonMove2(encounteredPokemon)}");
                    return(true);
                }

                CatchPokemonResponse caughtPokemonResponse = null;
                var lastThrow      = CatchPokemonResponse.Types.CatchStatus.CatchSuccess; // Initializing lastThrow
                var attemptCounter = 1;

                // Main CatchPokemon-loop
                do
                {
                    if (session.LogicSettings.UseHumanlikeDelays)
                    {
                        await DelayingUtils.DelayAsync(session.LogicSettings.BeforeCatchDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);
                    }

                    if ((session.LogicSettings.MaxPokeballsPerPokemon > 0 &&
                         attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon))
                    {
                        break;
                    }

                    pokeball = await GetBestBall(session, encounteredPokemon, probability).ConfigureAwait(false);

                    if (pokeball == ItemId.ItemUnknown)
                    {
                        session.EventDispatcher.Send(new NoPokeballEvent
                        {
                            Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId,
                            Cp = encounteredPokemon.Cp
                        });
                        return(false);
                    }

                    // Determine whether to use berries or not
                    if (lastThrow != CatchPokemonResponse.Types.CatchStatus.CatchMissed)
                    {
                        //AmountOfBerries++;
                        //if (AmountOfBerries <= session.LogicSettings.MaxBerriesToUsePerPokemon)
                        await UseBerry(session,
                                       encounterEV.PokemonId,
                                       _encounterId,
                                       _spawnPointId,
                                       pokemonIv,
                                       pokemonCp.HasValue?pokemonCp.Value : 10000, //unknow CP pokemon, want to use berry
                                       encounterEV.Level,
                                       probability,
                                       cancellationToken).ConfigureAwait(false);
                    }

                    bool hitPokemon = true;

                    //default to excellent throw
                    var normalizedRecticleSize = 1.95;

                    //default spin
                    var spinModifier = 1.0;

                    //Humanized throws
                    if (session.LogicSettings.EnableHumanizedThrows)
                    {
                        //thresholds: https://gist.github.com/anonymous/077d6dea82d58b8febde54ae9729b1bf
                        var spinTxt = "Curve";
                        var hitTxt  = "Excellent";
                        if (pokemonCp > session.LogicSettings.ForceExcellentThrowOverCp ||
                            pokemonIv > session.LogicSettings.ForceExcellentThrowOverIv)
                        {
                            normalizedRecticleSize = Random.NextDouble() * (1.95 - 1.7) + 1.7;
                        }
                        else if (pokemonCp >= session.LogicSettings.ForceGreatThrowOverCp ||
                                 pokemonIv >= session.LogicSettings.ForceGreatThrowOverIv)
                        {
                            normalizedRecticleSize = Random.NextDouble() * (1.95 - 1.3) + 1.3;
                            hitTxt = "Great";
                        }
                        else
                        {
                            var regularThrow = 100 - (session.LogicSettings.ExcellentThrowChance +
                                                      session.LogicSettings.GreatThrowChance +
                                                      session.LogicSettings.NiceThrowChance);
                            var rnd = Random.Next(1, 101);

                            if (rnd <= regularThrow)
                            {
                                normalizedRecticleSize = Random.NextDouble() * (1 - 0.1) + 0.1;
                                hitTxt = "Ordinary";
                            }
                            else if (rnd <= regularThrow + session.LogicSettings.NiceThrowChance)
                            {
                                normalizedRecticleSize = Random.NextDouble() * (1.3 - 1) + 1;
                                hitTxt = "Nice";
                            }
                            else if (rnd <=
                                     regularThrow + session.LogicSettings.NiceThrowChance +
                                     session.LogicSettings.GreatThrowChance)
                            {
                                normalizedRecticleSize = Random.NextDouble() * (1.7 - 1.3) + 1.3;
                                hitTxt = "Great";
                            }

                            if (Random.NextDouble() * 100 > session.LogicSettings.CurveThrowChance)
                            {
                                spinModifier = 0.0;
                                spinTxt      = "Straight";
                            }
                        }


                        // Round to 2 decimals
                        normalizedRecticleSize = Math.Round(normalizedRecticleSize, 2);

                        // Missed throw check
                        int missChance = Random.Next(1, 101);
                        if (missChance <= session.LogicSettings.ThrowMissPercentage &&
                            session.LogicSettings.EnableMissedThrows)
                        {
                            hitPokemon = false;
                        }

                        Logger.Write($"(Threw ball) {hitTxt} throw, {spinTxt}-ball, HitPokemon = {hitPokemon}...",
                                     LogLevel.Debug);
                    }

                    if (CatchFleeContinuouslyCount >= 3 && session.LogicSettings.ByPassCatchFlee)
                    {
                        MSniperServiceTask.BlockSnipe();

                        if (totalBalls <= BALL_REQUIRED_TO_BYPASS_CATCHFLEE)
                        {
                            Logger.Write("You don't enought ball to  by pass catchflee");
                            return(false);
                        }
                        List <ItemId> ballToByPass = new List <ItemId>();
                        var           numPokeBalls = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall).ConfigureAwait(false);

                        for (int i = 0; i < numPokeBalls - 1; i++)
                        {
                            ballToByPass.Add(ItemId.ItemPokeBall);
                        }
                        var numGreatBalls = await session.Inventory.GetItemAmountByType(ItemId.ItemGreatBall).ConfigureAwait(false);

                        for (int i = 0; i < numGreatBalls - 1; i++)
                        {
                            ballToByPass.Add(ItemId.ItemGreatBall);
                        }
                        var numUltraBalls = await session.Inventory.GetItemAmountByType(ItemId.ItemUltraBall).ConfigureAwait(false);

                        for (int i = 0; i < numUltraBalls - 1; i++)
                        {
                            ballToByPass.Add(ItemId.ItemUltraBall);
                        }
                        bool catchMissed = true;

                        Random r = new Random();
                        for (int i = 0; i < ballToByPass.Count - 1; i++)
                        {
                            if (i > 130 && r.Next(0, 100) <= 30)
                            {
                                catchMissed = false;
                            }
                            else
                            {
                                catchMissed = true;
                            }

                            caughtPokemonResponse =
                                await session.Client.Encounter.CatchPokemon(
                                    encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                    ?pokemon.EncounterId
                                    : _encounterId,
                                    encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                    ?pokemon.SpawnPointId
                                    : currentFortData.Id, ballToByPass[i], 1.0, 1.0, !catchMissed).ConfigureAwait(false);

                            await session.Inventory.UpdateInventoryItem(ballToByPass[i]).ConfigureAwait(false);

                            await Task.Delay(100).ConfigureAwait(false);

                            Logger.Write($"CatchFlee By pass : {ballToByPass[i].ToString()} , Attempt {i}, result {caughtPokemonResponse.Status}");

                            if (caughtPokemonResponse.Status != CatchPokemonResponse.Types.CatchStatus.CatchMissed)
                            {
                                session.SaveBallForByPassCatchFlee = false;
                                CatchFleeContinuouslyCount         = 0;
                                break;
                            }
                        }
                    }
                    else
                    {
                        caughtPokemonResponse =
                            await session.Client.Encounter.CatchPokemon(
                                encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                ?pokemon.EncounterId
                                : _encounterId,
                                encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                ?pokemon.SpawnPointId
                                : currentFortData.Id, pokeball, normalizedRecticleSize, spinModifier, hitPokemon).ConfigureAwait(false);

                        await session.Inventory.UpdateInventoryItem(pokeball).ConfigureAwait(false);
                    }


                    var evt = new PokemonCaptureEvent()
                    {
                        Status        = caughtPokemonResponse.Status,
                        CaptureReason = caughtPokemonResponse.CaptureReason,
                        Latitude      = latitude,
                        Longitude     = longitude
                    };

                    lastThrow = caughtPokemonResponse.Status; // sets lastThrow status


                    if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                    {
                        evt.Gender = (await session.Inventory.GetPokemons().ConfigureAwait(false)).First(x => x.Id == caughtPokemonResponse.CapturedPokemonId).PokemonDisplay.Gender.ToString();

                        var totalExp      = 0;
                        var totalStarDust = caughtPokemonResponse.CaptureAward.Stardust.Sum();
                        if (encounteredPokemon != null)
                        {
                            encounteredPokemon.Id = caughtPokemonResponse.CapturedPokemonId;
                        }
                        foreach (var xp in caughtPokemonResponse.CaptureAward.Xp)
                        {
                            totalExp += xp;
                        }
                        var stardust = session.Inventory.UpdateStarDust(totalStarDust);

                        evt.Exp      = totalExp;
                        evt.Stardust = stardust;
                        evt.UniqueId = caughtPokemonResponse.CapturedPokemonId;
                        evt.Candy    = await session.Inventory.GetCandyFamily(pokemon.PokemonId).ConfigureAwait(false);
                    }

                    if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess ||
                        caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchFlee)
                    {
                        // Also count catch flee against the catch limit
                        if (session.LogicSettings.UseCatchLimit)
                        {
                            session.Stats.AddPokemonTimestamp(DateTime.Now.Ticks);
                            session.EventDispatcher.Send(new CatchLimitUpdate(session.Stats.GetNumPokemonsInLast24Hours(), session.LogicSettings.CatchPokemonLimit));
                        }
                    }

                    evt.CatchType = encounter is EncounterResponse
                        ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal)
                        : encounter is DiskEncounterResponse
                            ? session.Translation.GetTranslation(TranslationString.CatchTypeLure)
                            : session.Translation.GetTranslation(TranslationString.CatchTypeIncense);

                    evt.CatchTypeText = encounter is EncounterResponse
                        ? "normal"
                        : encounter is DiskEncounterResponse
                            ? "lure"
                            : "incense";
                    evt.Id = encounter is EncounterResponse
                        ? pokemon.PokemonId
                        : encounter?.PokemonData.PokemonId;
                    evt.EncounterId  = _encounterId;
                    evt.Move1        = PokemonInfo.GetPokemonMove1(encounteredPokemon);
                    evt.Move2        = PokemonInfo.GetPokemonMove2(encounteredPokemon);
                    evt.Expires      = pokemon?.ExpirationTimestampMs ?? 0;
                    evt.SpawnPointId = _spawnPointId;
                    evt.Level        = PokemonInfo.GetLevel(encounteredPokemon);
                    evt.Cp           = encounteredPokemon.Cp;
                    evt.MaxCp        = PokemonInfo.CalculateMaxCp(encounteredPokemon.PokemonId);
                    evt.Perfection   = Math.Round(PokemonInfo.CalculatePokemonPerfection(encounteredPokemon));
                    evt.Probability  = Math.Round(probability * 100, 2);
                    evt.Distance     = distance;
                    evt.Pokeball     = pokeball;
                    evt.Attempt      = attemptCounter;

                    //await session.Inventory.RefreshCachedInventory().ConfigureAwait(false);

                    evt.BallAmount = await session.Inventory.GetItemAmountByType(pokeball).ConfigureAwait(false);

                    evt.Rarity = PokemonGradeHelper.GetPokemonGrade(evt.Id).ToString();

                    session.EventDispatcher.Send(evt);

                    attemptCounter++;

                    // If Humanlike delays are used
                    if (session.LogicSettings.UseHumanlikeDelays)
                    {
                        switch (caughtPokemonResponse.Status)
                        {
                        case CatchPokemonResponse.Types.CatchStatus.CatchError:
                            await DelayingUtils.DelayAsync(session.LogicSettings.CatchErrorDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);

                            break;

                        case CatchPokemonResponse.Types.CatchStatus.CatchSuccess:
                            await DelayingUtils.DelayAsync(session.LogicSettings.CatchSuccessDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);

                            break;

                        case CatchPokemonResponse.Types.CatchStatus.CatchEscape:
                            await DelayingUtils.DelayAsync(session.LogicSettings.CatchEscapeDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);

                            break;

                        case CatchPokemonResponse.Types.CatchStatus.CatchFlee:
                            await DelayingUtils.DelayAsync(session.LogicSettings.CatchFleeDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);

                            break;

                        case CatchPokemonResponse.Types.CatchStatus.CatchMissed:
                            await DelayingUtils.DelayAsync(session.LogicSettings.CatchMissedDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);

                            break;

                        default:
                            break;
                        }
                    }
                    else
                    {
                        await DelayingUtils.DelayAsync(session.LogicSettings.DelayBetweenPlayerActions, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);
                    }
                } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed ||
                         caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape);

                if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchFlee)
                {
                    CatchFleeContinuouslyCount++;
                    if (CatchFleeContinuouslyCount >= 3 && session.LogicSettings.ByPassCatchFlee)
                    {
                        session.SaveBallForByPassCatchFlee = true;
                        Logger.Write("Seem that bot has ben catch flee softban, Bot will start save 100 balls to by pass it.");
                    }
                    if (manager.AllowMultipleBot() && !session.LogicSettings.ByPassCatchFlee)
                    {
                        if (CatchFleeContinuouslyCount > session.LogicSettings.MultipleBotConfig.CatchFleeCount &&
                            TinyIoCContainer.Current.Resolve <MultiAccountManager>().AllowSwitch())
                        {
                            CatchFleeContinuouslyCount         = 0;
                            session.SaveBallForByPassCatchFlee = false;

                            throw new ActiveSwitchByRuleException()
                                  {
                                      MatchedRule  = SwitchRules.CatchFlee,
                                      ReachedValue = session.LogicSettings.MultipleBotConfig.CatchFleeCount
                                  };
                        }
                    }
                }
                else
                {
                    //reset if not catch flee.
                    if (caughtPokemonResponse.Status != CatchPokemonResponse.Types.CatchStatus.CatchMissed)
                    {
                        CatchFleeContinuouslyCount = 0;
                        MSniperServiceTask.UnblockSnipe();
                    }
                }

                session.Actions.RemoveAll(x => x == BotActions.Catch);

                if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings, manager))
                {
                    ExecuteSwitcher(session, encounterEV, uniqueCacheKey);
                }

                if (session.LogicSettings.TransferDuplicatePokemonOnCapture &&
                    session.LogicSettings.TransferDuplicatePokemon &&
                    sessionAllowTransfer &&
                    caughtPokemonResponse != null &&
                    caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                {
                    if (session.LogicSettings.UseNearActionRandom)
                    {
                        await HumanRandomActionTask.TransferRandom(session, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 30
0
        private static async Task <PokemonData> GetDeployablePokemon(ISession session)
        {
            PokemonData  pokemon  = null;
            List <ulong> excluded = new List <ulong>();

            while (pokemon == null)
            {
                var pokemonList = (await session.Inventory.GetPokemons()).ToList();
                pokemonList = pokemonList
                              .Where(w => !excluded.Contains(w.Id) && w.Id != session.Profile.PlayerData.BuddyPokemon?.Id && (session.LogicSettings.GymConfig.HealDefendersBeforeApplyToGym || w.Stamina == w.StaminaMax))
                              .OrderByDescending(p => p.Cp)
                              .Skip(Math.Min(pokemonList.Count - 1, session.LogicSettings.GymConfig.NumberOfTopPokemonToBeExcluded))
                              .ToList();

                if (pokemonList.Count == 0)
                {
                    return(null);
                }

                if (pokemonList.Count == 1)
                {
                    pokemon = pokemonList.FirstOrDefault();
                }
                if (session.LogicSettings.GymConfig.UseRandomPokemon && pokemon == null)
                {
                    pokemon = pokemonList.ElementAt(new Random().Next(0, pokemonList.Count - 1));
                }

                pokemon = pokemonList.FirstOrDefault(p => p.Cp <= session.LogicSettings.GymConfig.MaxCPToDeploy && PokemonInfo.GetLevel(p) <= session.LogicSettings.GymConfig.MaxLevelToDeploy && string.IsNullOrEmpty(p.DeployedFortId));

                if (session.LogicSettings.GymConfig.HealDefendersBeforeApplyToGym)
                {
                    if (pokemon.Stamina == 0)
                    {
                        await RevivePokemon(session, pokemon);
                    }

                    if (pokemon.Stamina < pokemon.StaminaMax)
                    {
                        await HealPokemon(session, pokemon);
                    }

                    if (pokemon.Stamina < pokemon.StaminaMax)
                    {
                        excluded.Add(pokemon.Id);
                        pokemon = null;
                    }
                }
            }
            return(pokemon);
        }