Example #1
0
        public async Task <PlayerUpdateResponse> HumanPathWalking(GpxReader.Trkpt trk,
                                                                  Func <Task <bool> > functionExecutedWhileWalking,
                                                                  ISession session,
                                                                  CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            //PlayerUpdateResponse result = null;

            var targetLocation = new GeoCoordinate(Convert.ToDouble(trk.Lat, CultureInfo.InvariantCulture),
                                                   Convert.ToDouble(trk.Lon, CultureInfo.InvariantCulture));
            var speedInMetersPerSecond = session.LogicSettings.UseWalkingSpeedVariant ? MajorWalkingSpeedVariant(session) :
                                         session.LogicSettings.WalkingSpeedInKilometerPerHour / 3.6;
            var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);

            LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation);
            var nextWaypointBearing  = LocationUtils.DegreeBearing(sourceLocation, targetLocation);
            var nextWaypointDistance = speedInMetersPerSecond;
            var waypoint             = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing,
                                                                    Convert.ToDouble(trk.Ele, CultureInfo.InvariantCulture));
            var requestSendDateTime    = DateTime.Now;
            var requestVariantDateTime = DateTime.Now;
            var result =
                await
                _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude);

            UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude);

            do
            {
                cancellationToken.ThrowIfCancellationRequested();

                var millisecondsUntilGetUpdatePlayerLocationResponse =
                    (DateTime.Now - requestSendDateTime).TotalMilliseconds;

                sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
                var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation);

                //if (currentDistanceToTarget < 40)
                //{
                //    if (speedInMetersPerSecond > SpeedDownTo)
                //    {
                //        //Logger.Write("We are within 40 meters of the target. Speeding down to 10 km/h to not pass the target.", LogLevel.Info);
                //        speedInMetersPerSecond = SpeedDownTo;
                //    }
                //}

                if (session.LogicSettings.UseWalkingSpeedVariant)
                {
                    speedInMetersPerSecond = MinorWalkingSpeedVariant(session);
                }

                nextWaypointDistance = Math.Min(currentDistanceToTarget,
                                                millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond);
                nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation);
                waypoint            = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing);

                requestSendDateTime = DateTime.Now;
                result =
                    await
                    _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude,
                                                        waypoint.Altitude);

                UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude);

                if (functionExecutedWhileWalking != null)
                {
                    await functionExecutedWhileWalking(); // look for pokemon & hit stops
                }
            } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30);

            return(result);
        }
Example #2
0
        public override async Task <PlayerUpdateResponse> Walk(IGeoLocation targetLocation,
                                                               Func <Task> functionExecutedWhileWalking, ISession session, CancellationToken cancellationToken,
                                                               double walkSpeed = 0.0)
        {
            base.OnStartWalking(session, targetLocation);

            var destinaionCoordinate = new GeoCoordinate(targetLocation.Latitude, targetLocation.Longitude);

            if (CurrentWalkingSpeed <= 0)
            {
                CurrentWalkingSpeed = session.LogicSettings.WalkingSpeedInKilometerPerHour;
            }
            if (session.LogicSettings.UseWalkingSpeedVariant && walkSpeed == 0)
            {
                CurrentWalkingSpeed = session.Navigation.VariantRandom(session, CurrentWalkingSpeed);
            }

            var rw = new Random();
            var speedInMetersPerSecond = (walkSpeed > 0 ? walkSpeed : CurrentWalkingSpeed) / 3.6;

            var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);

            var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, destinaionCoordinate);


            var nextWaypointDistance   = speedInMetersPerSecond;
            var waypoint               = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing);
            var requestSendDateTime    = DateTime.Now;
            var requestVariantDateTime = DateTime.Now;

            var result = await LocationUtils
                         .UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond);

            double SpeedVariantSec = rw.Next(1000, 10000);

            base.DoUpdatePositionEvent(session, waypoint.Latitude, waypoint.Longitude, CurrentWalkingSpeed);

            do
            {
                cancellationToken.ThrowIfCancellationRequested();
                TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
                var millisecondsUntilGetUpdatePlayerLocationResponse =
                    (DateTime.Now - requestSendDateTime).TotalMilliseconds;
                var millisecondsUntilVariant =
                    (DateTime.Now - requestVariantDateTime).TotalMilliseconds;

                sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
                var currentDistanceToTarget = LocationUtils
                                              .CalculateDistanceInMeters(sourceLocation, destinaionCoordinate);

                if (currentDistanceToTarget < 40)
                {
                    if (speedInMetersPerSecond > SpeedDownTo)
                    {
                        speedInMetersPerSecond = SpeedDownTo;
                    }
                }

                if (session.LogicSettings.UseWalkingSpeedVariant && walkSpeed == 0)
                {
                    CurrentWalkingSpeed = session.Navigation.VariantRandom(session, CurrentWalkingSpeed);
                }

                speedInMetersPerSecond = (walkSpeed > 0 ? walkSpeed : CurrentWalkingSpeed) / 3.6;

                nextWaypointDistance = Math.Min(currentDistanceToTarget,
                                                millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond);
                nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, destinaionCoordinate);
                var testeBear = LocationUtils.DegreeBearing(sourceLocation, new GeoCoordinate(40.780396, -73.974844));
                waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing);

                requestSendDateTime = DateTime.Now;
                result = await LocationUtils
                         .UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond);

                base.DoUpdatePositionEvent(session, waypoint.Latitude, waypoint.Longitude, CurrentWalkingSpeed);

                if (functionExecutedWhileWalking != null)
                {
                    await functionExecutedWhileWalking(); // look for pokemon
                }
            } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, destinaionCoordinate) >= (new Random()).Next(1, 10));

            return(result);
        }
        private static void PostProcessDataFetched(IEnumerable <SnipePokemonInfo> pokemons, bool displayList = true)
        {
            var rw = new Random();
            var speedInMetersPerSecond = _setting.WalkingSpeedInKilometerPerHour / 3.6;
            int count = 0;

            foreach (var item in pokemons)
            {
                //the pokemon data already in the list
                if (rarePokemons.Any(x => x.UniqueId == item.UniqueId ||
                                     (LocationUtils.CalculateDistanceInMeters(x.Latitude, x.Longitude, item.Latitude, item.Longitude) < 10 && item.Id == x.Id)))
                {
                    continue;
                }
                //check if pokemon in the snip list
                if (!pokemonToBeSnipedIds.Any(x => x == item.PokemonId))
                {
                    continue;
                }

                count++;
                var snipeSetting = _setting.HumanWalkSnipeFilters.FirstOrDefault(x => x.Key == item.PokemonId);

                HumanWalkSnipeFilter config = new HumanWalkSnipeFilter(_setting.HumanWalkingSnipeMaxDistance,
                                                                       _setting.HumanWalkingSnipeMaxEstimateTime,
                                                                       3, //default priority
                                                                       _setting.HumanWalkingSnipeTryCatchEmAll,
                                                                       _setting.HumanWalkingSnipeSpinWhileWalking,
                                                                       _setting.HumanWalkingSnipeAllowSpeedUp,
                                                                       _setting.HumanWalkingSnipeMaxSpeedUpSpeed,
                                                                       _setting.HumanWalkingSnipeDelayTimeAtDestination);

                if (_setting.HumanWalkSnipeFilters.Any(x => x.Key == item.PokemonId))
                {
                    config = _setting.HumanWalkSnipeFilters.First(x => x.Key == item.PokemonId).Value;
                }
                item.Setting = Clone <HumanWalkSnipeFilter>(config);

                CalculateDistanceAndEstTime(item);

                if (item.Distance < 10000)  //only add if distance <10km
                {
                    rarePokemons.Add(item);
                }
            }
            rarePokemons = rarePokemons.OrderBy(p => p.Setting.Priority).ThenBy(p => p.Distance).ToList();

            //remove troll data

            var grouped = rarePokemons.GroupBy(p => p.PokemonId);

            foreach (var g in grouped)
            {
                if (g.Count() > 5)
                {
                    //caculate distance to betweek pokemon
                }
            }
            if (count > 0)
            {
                _session.EventDispatcher.Send(new HumanWalkSnipeEvent()
                {
                    Type     = HumanWalkSnipeEventTypes.PokemonScanned,
                    Pokemons = ApplyFilter(rarePokemons),
                });

                if (_setting.HumanWalkingSnipeDisplayList)
                {
                    var ordered = rarePokemons.Where(p => p.ExpiredTime > DateTime.Now.AddSeconds(p.EstimatedTime) && !p.IsVisited).ToList();

                    if (ordered.Count > 0 && displayList)
                    {
                        Logger.Write(string.Format("     Source      |  Name               |    Distance    |   Expires        |  Travel times   | Catchable"));
                        foreach (var pokemon in ordered)
                        {
                            string name = _session.Translation.GetPokemonTranslation(pokemon.PokemonId);
                            name += "".PadLeft(16 - name.Length, ' ');
                            string source = pokemon.Source;
                            source += "".PadLeft(16 - source.Length, ' ');
                            Logger.Write(string.Format(" {0} |  {1}  |  {2:0.00}m  \t|  {3:mm} min {3:ss} sec  |  {4:00} min {5:00} sec  | {6}",
                                                       source,
                                                       name,
                                                       pokemon.Distance,
                                                       pokemon.ExpiredTime - DateTime.Now,
                                                       pokemon.EstimatedTime / 60,
                                                       pokemon.EstimatedTime % 60,
                                                       pokemon.ExpiredTime > DateTime.Now.AddSeconds(pokemon.EstimatedTime) ? "Possible" : "Missied"
                                                       ));
                        }
                    }
                }
            }
        }
Example #4
0
        public async Task <PlayerUpdateResponse> Walk(GeoCoordinate targetLocation, Func <Task <bool> > functionExecutedWhileWalking, ISession session, CancellationToken cancellationToken)
        {
            if (CurrentWalkingSpeed <= 0)
            {
                CurrentWalkingSpeed = session.LogicSettings.WalkingSpeedInKilometerPerHour;
            }
            if (session.LogicSettings.UseWalkingSpeedVariant)
            {
                CurrentWalkingSpeed = session.Navigation.VariantRandom(session, CurrentWalkingSpeed);
            }

            var rw = new Random();
            var speedInMetersPerSecond = CurrentWalkingSpeed / 3.6;
            var sourceLocation         = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);

            var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation);


            var nextWaypointDistance   = speedInMetersPerSecond;
            var waypoint               = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing);
            var requestSendDateTime    = DateTime.Now;
            var requestVariantDateTime = DateTime.Now;

            var result = await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint);

            double SpeedVariantSec = rw.Next(1000, 10000);

            UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude);

            do
            {
                cancellationToken.ThrowIfCancellationRequested();

                var millisecondsUntilGetUpdatePlayerLocationResponse = (DateTime.Now - requestSendDateTime).TotalMilliseconds;
                var millisecondsUntilVariant = (DateTime.Now - requestVariantDateTime).TotalMilliseconds;

                sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
                var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation);

                if (currentDistanceToTarget < 40)
                {
                    if (speedInMetersPerSecond > SpeedDownTo)
                    {
                        speedInMetersPerSecond = SpeedDownTo;
                    }
                }

                if (session.LogicSettings.UseWalkingSpeedVariant)
                {
                    CurrentWalkingSpeed    = session.Navigation.VariantRandom(session, CurrentWalkingSpeed);
                    speedInMetersPerSecond = CurrentWalkingSpeed / 3.6;
                }

                nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond);
                nextWaypointBearing  = LocationUtils.DegreeBearing(sourceLocation, targetLocation);
                var testeBear = LocationUtils.DegreeBearing(sourceLocation, new GeoCoordinate(40.780396, -73.974844));
                waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing);

                requestSendDateTime = DateTime.Now;
                result = await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint);

                UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude);

                if (functionExecutedWhileWalking != null)
                {
                    await functionExecutedWhileWalking(); // look for pokemon
                }
            } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30);

            return(result);
        }
Example #5
0
        private async Task ExecuteCatchAllNearbyPokemons()
        {
            var client     = _client;
            var mapObjects = await client.GetMapObjects();

            //var pokemons = mapObjects.MapCells.SelectMany(i => i.CatchablePokemons);
            var pokemons =
                mapObjects.MapCells.SelectMany(i => i.CatchablePokemons)
                .OrderBy(
                    i =>
                    LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, i.Latitude, i.Longitude));

            if (pokemons != null && pokemons.Any())
            {
                Logger.ColoredConsoleWrite(ConsoleColor.Magenta, $"Found {pokemons.Count()} catchable Pokemon(s).");
            }

            foreach (var pokemon in pokemons)
            {
                count++;
                if (count >= 3)
                {
                    count = 0;
                    await StatsLog(client);

                    if (_clientSettings.EvolvePokemonsIfEnoughCandy)
                    {
                        await EvolveAllPokemonWithEnoughCandy();
                    }
                    await TransferDuplicatePokemon(_clientSettings.keepPokemonsThatCanEvolve);
                    await RecycleItems();
                }

                if (_clientSettings.catchPokemonSkipList.Contains(pokemon.PokemonId))
                {
                    Logger.ColoredConsoleWrite(ConsoleColor.Green, "Skipped Pokemon: " + pokemon.PokemonId);
                    continue;
                }

                var distance = LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, pokemon.Latitude, pokemon.Longitude);
                await Task.Delay(distance > 100? 1000 : 100);

                var encounterPokemonResponse = await _client.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnpointId);

                if (encounterPokemonResponse.Status == EncounterResponse.Types.Status.EncounterSuccess)
                {
                    var bestPokeball = await GetBestBall(encounterPokemonResponse?.WildPokemon);

                    if (bestPokeball == MiscEnums.Item.ITEM_UNKNOWN)
                    {
                        Logger.ColoredConsoleWrite(ConsoleColor.Red, $"We dont own Pokeballs! - We missed a {pokemon.PokemonId} with CP {encounterPokemonResponse?.WildPokemon?.PokemonData?.Cp}");
                        return;
                    }
                    CatchPokemonResponse caughtPokemonResponse;
                    do
                    {
                        var inventoryBerries = await _inventory.GetItems();

                        var probability = encounterPokemonResponse?.CaptureProbability?.CaptureProbability_?.FirstOrDefault();
                        var bestBerry   = await GetBestBerry(encounterPokemonResponse?.WildPokemon);

                        var berries = inventoryBerries.Where(p => (ItemId)p.Item_ == bestBerry).FirstOrDefault();
                        if (bestBerry != ItemId.ItemUnknown && probability.HasValue && probability.Value < 0.35)
                        {
                            //Throw berry is we can
                            var useRaspberry = await _client.UseCaptureItem(pokemon.EncounterId, bestBerry, pokemon.SpawnpointId);

                            Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Used {bestBerry}. Remaining: {berries.Count}.", LogLevel.Info);
                            await RandomHelper.RandomDelay(50, 200);
                        }

                        caughtPokemonResponse = await _client.CatchPokemon(pokemon.EncounterId, pokemon.SpawnpointId, pokemon.Latitude, pokemon.Longitude, bestPokeball);
                    }while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed || caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape);

                    if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                    {
                        foreach (int xp in caughtPokemonResponse.Scores.Xp)
                        {
                            _botStats.addExperience(xp);
                        }

                        Logger.ColoredConsoleWrite(ConsoleColor.Magenta, $"We caught a {StringUtils.getPokemonNameByLanguage(_clientSettings, pokemon.PokemonId)} with CP {encounterPokemonResponse?.WildPokemon?.PokemonData?.Cp} ({PokemonInfo.CalculatePokemonPerfection(encounterPokemonResponse?.WildPokemon.PokemonData)}% perfect) using a {bestPokeball} and we got {caughtPokemonResponse.Scores.Xp.Sum()} XP.");

                        //try
                        //{
                        //    var r = (HttpWebRequest)WebRequest.Create("http://pokemon.becher.xyz/index.php?pokeName=" + pokemon.PokemonId);
                        //    var rp = (HttpWebResponse)r.GetResponse();
                        //    var rps = new StreamReader(rp.GetResponseStream()).ReadToEnd();
                        //    Logger.ColoredConsoleWrite(ConsoleColor.Magenta, $"We caught a {pokemon.PokemonId} ({rps}) with CP {encounterPokemonResponse?.WildPokemon?.PokemonData?.Cp} using a {bestPokeball}");
                        //} catch (Exception)
                        //{
                        //    Logger.ColoredConsoleWrite(ConsoleColor.Magenta, $"We caught a {pokemon.PokemonId} (Language Server Offline) with CP {encounterPokemonResponse?.WildPokemon?.PokemonData?.Cp} using a {bestPokeball}");
                        //}

                        _botStats.addPokemon(1);
                    }
                    else
                    {
                        Logger.ColoredConsoleWrite(ConsoleColor.DarkYellow, $"{StringUtils.getPokemonNameByLanguage(_clientSettings, pokemon.PokemonId)} with CP {encounterPokemonResponse?.WildPokemon?.PokemonData?.Cp} ({PokemonInfo.CalculatePokemonPerfection(encounterPokemonResponse?.WildPokemon.PokemonData)} % perfect) got away while using a {bestPokeball}..");
                        failed_softban++;
                    }
                }
                else
                {
                    Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Error Catching Pokemon: {encounterPokemonResponse?.Status}");
                }
                await RandomHelper.RandomDelay(50, 200);
            }
        }
Example #6
0
        public async Task DoWalk(List <GeoCoordinate> points, ISession session,
                                 Func <Task> functionExecutedWhileWalking, GeoCoordinate sourceLocation, GeoCoordinate targetLocation,
                                 CancellationToken cancellationToken, double walkSpeed = 0.0)
        {
            var currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude,
                                                    _client.CurrentAltitude);

            //filter google defined waypoints and remove those that are too near to the previous ones
            var waypointsDists       = new Dictionary <Tuple <GeoCoordinate, GeoCoordinate>, double>();
            var minWaypointsDistance = RandomizeStepLength(_minStepLengthInMeters);

            for (var i = 0; i < points.Count; i++)
            {
                if (i > 0)
                {
                    var dist = LocationUtils.CalculateDistanceInMeters(points[i - 1], points[i]);
                    waypointsDists[new Tuple <GeoCoordinate, GeoCoordinate>(points[i - 1], points[i])] = dist;
                }
            }

            var tooNearPoints = waypointsDists.Where(kvp => kvp.Value < minWaypointsDistance)
                                .Select(kvp => kvp.Key.Item1)
                                .ToList();

            foreach (var tooNearPoint in tooNearPoints)
            {
                points.Remove(tooNearPoint);
            }
            if (points.Any()
                ) //check if first waypoint is the current location (this is what google returns), in such case remove it!
            {
                var firstStep = points.First();
                if (firstStep == currentLocation)
                {
                    points.Remove(points.First());
                }
            }

            var walkedPointsList = new List <GeoCoordinate>();

            foreach (var nextStep in points)
            {
                currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
                if (_currentWalkingSpeed <= 0)
                {
                    _currentWalkingSpeed = session.LogicSettings.WalkingSpeedInKilometerPerHour;
                }
                if (session.LogicSettings.UseWalkingSpeedVariant && walkSpeed == 0)
                {
                    _currentWalkingSpeed = session.Navigation.VariantRandom(session, _currentWalkingSpeed);
                }

                var speedInMetersPerSecond = (walkSpeed > 0 ? walkSpeed : _currentWalkingSpeed) / 3.6;

                var nextStepBearing = LocationUtils.DegreeBearing(currentLocation, nextStep);
                //particular steps are limited by minimal length, first step is calculated from the original speed per second (distance in 1s)
                var nextStepDistance = Math.Max(RandomizeStepLength(_minStepLengthInMeters), speedInMetersPerSecond);

                var waypoint = LocationUtils.CreateWaypoint(currentLocation, nextStepDistance, nextStepBearing);
                walkedPointsList.Add(waypoint);

                var previousLocation =
                    currentLocation; //store the current location for comparison and correction purposes
                var requestSendDateTime = DateTime.Now;
                LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint,
                                                               (float)speedInMetersPerSecond);

                var realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation);
                if (realDistanceToTarget < 2)
                {
                    break;
                }

                do
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
                    var msToPositionChange = (DateTime.Now - requestSendDateTime).TotalMilliseconds;
                    currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
                    var currentDistanceToWaypoint = LocationUtils.CalculateDistanceInMeters(currentLocation, nextStep);
                    realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation);

                    var realSpeedinMperS   = nextStepDistance / (msToPositionChange / 1000);
                    var realDistanceWalked = LocationUtils.CalculateDistanceInMeters(previousLocation, currentLocation);
                    //if the real calculated speed is lower than the one expected, we will raise the speed for the following step
                    double speedRaise = 0;
                    if (realSpeedinMperS < speedInMetersPerSecond)
                    {
                        speedRaise = speedInMetersPerSecond - realSpeedinMperS;
                    }
                    double distanceRaise = 0;
                    if (realDistanceWalked < nextStepDistance)
                    {
                        distanceRaise = nextStepDistance - realDistanceWalked;
                    }

                    var realDistanceToTargetSpeedDown =
                        LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation);
                    if (realDistanceToTargetSpeedDown < 40)
                    {
                        if (speedInMetersPerSecond > SpeedDownTo)
                        {
                            speedInMetersPerSecond = SpeedDownTo;
                        }
                    }

                    if (session.LogicSettings.UseWalkingSpeedVariant && walkSpeed == 0)
                    {
                        _currentWalkingSpeed   = session.Navigation.VariantRandom(session, _currentWalkingSpeed);
                        speedInMetersPerSecond = _currentWalkingSpeed / 3.6;
                    }
                    speedInMetersPerSecond += speedRaise;
                    if (walkSpeed > 0)
                    {
                        speedInMetersPerSecond = walkSpeed / 3.6;
                    }
                    nextStepBearing = LocationUtils.DegreeBearing(currentLocation, nextStep);

                    //setting next step distance is limited by the target and the next waypoint distance (we don't want to miss them)
                    //also the minimal step length is used as we don't want to spend minutes jumping by cm lengths
                    nextStepDistance = Math.Min(Math.Min(realDistanceToTarget, currentDistanceToWaypoint),
                                                //also add the distance raise (bot overhead corrections) to the normal step length
                                                Math.Max(RandomizeStepLength(_minStepLengthInMeters) + distanceRaise,
                                                         (msToPositionChange / 1000) * speedInMetersPerSecond) + distanceRaise);
                    int timeToWalk = (int)((nextStepDistance * 1000) / speedInMetersPerSecond);
                    //Logger.Debug($"nextStepDistance {nextStepDistance} need {timeToWalk} ms");

                    waypoint = LocationUtils.CreateWaypoint(currentLocation, nextStepDistance, nextStepBearing);
                    walkedPointsList.Add(waypoint);

                    //store the current location for comparison and correction purposes
                    previousLocation    = currentLocation;
                    requestSendDateTime = DateTime.Now;
                    LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond);

                    UpdatePositionEvent?.Invoke(session, waypoint.Latitude, waypoint.Longitude, _currentWalkingSpeed);

                    await Task.Delay(timeToWalk);

                    if (functionExecutedWhileWalking != null)
                    {
                        await functionExecutedWhileWalking(); // look for pokemon
                    }
                } while (LocationUtils.CalculateDistanceInMeters(currentLocation, nextStep) >= 2);

                UpdatePositionEvent?.Invoke(session, nextStep.Latitude, nextStep.Longitude, _currentWalkingSpeed);
            }
        }
        private static async Task FortPokestop(ISession session, CancellationToken cancellationToken, FortData pokeStop)
        {
            var fortInfo = await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

            // we only move to the PokeStop, and send the associated FortTargetEvent, when not using GPX
            // also, GPX pathing uses its own EggWalker and calls the CatchPokemon tasks internally.
            if (!session.LogicSettings.UseGpxPathing)
            {
                var eggWalker = new EggWalker(1000, session);

                var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                       session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude);
                cancellationToken.ThrowIfCancellationRequested();

                if (!session.LogicSettings.UseGoogleWalk && !session.LogicSettings.UseYoursWalk)
                {
                    session.EventDispatcher.Send(new FortTargetEvent {
                        Name = fortInfo.Name, Distance = distance, Route = "NecroBot"
                    });
                }
                else
                {
                    BaseWalkStrategy.FortInfo = fortInfo;
                }

                await session.Navigation.Move(new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude,
                                                                LocationUtils.getElevation(session, pokeStop.Latitude, pokeStop.Longitude)),
                                              async() =>
                {
                    // Catch normal map Pokemon
                    await CatchNearbyPokemonsTask.Execute(session, cancellationToken);
                    //Catch Incense Pokemon
                    await CatchIncensePokemonsTask.Execute(session, cancellationToken);
                    return(true);
                },
                                              session,
                                              cancellationToken);

                // we have moved this distance, so apply it immediately to the egg walker.
                await eggWalker.ApplyDistance(distance, cancellationToken);
            }

            FortSearchResponse fortSearch;
            var       timesZeroXPawarded = 0;
            var       fortTry            = 0;  //Current check
            const int retryNumber        = 50; //How many times it needs to check to clear softban
            const int zeroCheck          = 5;  //How many times it checks fort before it thinks it's softban

            do
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (SearchThresholdExceeds(session))
                {
                    break;
                }

                fortSearch =
                    await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0)
                {
                    timesZeroXPawarded = 0;
                }
                if (fortSearch.ExperienceAwarded == 0)
                {
                    timesZeroXPawarded++;

                    if (timesZeroXPawarded > zeroCheck)
                    {
                        if ((int)fortSearch.CooldownCompleteTimestampMs != 0)
                        {
                            break; // Check if successfully looted, if so program can continue as this was "false alarm".
                        }

                        fortTry += 1;

                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry,
                            Max    = retryNumber - zeroCheck,
                            Looted = false
                        });

                        if (!session.LogicSettings.FastSoftBanBypass)
                        {
                            DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0);
                        }
                    }
                }
                else
                {
                    if (fortTry != 0)
                    {
                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry + 1,
                            Max    = retryNumber - zeroCheck,
                            Looted = true
                        });
                    }

                    session.EventDispatcher.Send(new FortUsedEvent
                    {
                        Id            = pokeStop.Id,
                        Name          = fortInfo.Name,
                        Exp           = fortSearch.ExperienceAwarded,
                        Gems          = fortSearch.GemsAwarded,
                        Items         = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded),
                        Latitude      = pokeStop.Latitude,
                        Longitude     = pokeStop.Longitude,
                        Altitude      = session.Client.CurrentAltitude,
                        InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull
                    });

                    if (fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull)
                    {
                        storeRI = 1;
                    }

                    session.Stats.PokeStopTimestamps.Add(DateTime.Now.Ticks);
                    break; //Continue with program as loot was succesfull.
                }
            } while (fortTry < retryNumber - zeroCheck);
            //Stop trying if softban is cleaned earlier or if 40 times fort looting failed.

            if (session.LogicSettings.RandomlyPauseAtStops)
            {
                if (++RandomStop >= RandomNumber)
                {
                    RandomNumber = rc.Next(4, 11);
                    RandomStop   = 0;
                    int RandomWaitTime = rc.Next(30, 120);
                    Thread.Sleep(RandomWaitTime);
                }
            }
        }
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            var tracks    = GetGpxTracks(session);
            var eggWalker = new EggWalker(1000, session);

            for (var curTrk = 0; curTrk < tracks.Count; curTrk++)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var track         = tracks.ElementAt(curTrk);
                var trackSegments = track.Segments;
                for (var curTrkSeg = 0; curTrkSeg < trackSegments.Count; curTrkSeg++)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var trackPoints = track.Segments.ElementAt(0).TrackPoints;
                    for (var curTrkPt = 0; curTrkPt < trackPoints.Count; curTrkPt++)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        var nextPoint = trackPoints.ElementAt(curTrkPt);
                        var distance  = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                                session.Client.CurrentLongitude,
                                                                                Convert.ToDouble(nextPoint.Lat, CultureInfo.InvariantCulture),
                                                                                Convert.ToDouble(nextPoint.Lon, CultureInfo.InvariantCulture));

                        if (distance > 5000)
                        {
                            session.EventDispatcher.Send(new ErrorEvent
                            {
                                Message =
                                    session.Translation.GetTranslation(TranslationString.DesiredDestTooFar,
                                                                       nextPoint.Lat, nextPoint.Lon, session.Client.CurrentLatitude,
                                                                       session.Client.CurrentLongitude)
                            });
                            break;
                        }

                        var pokestopList = await GetPokeStops(session);

                        session.EventDispatcher.Send(new PokeStopListEvent {
                            Forts = pokestopList
                        });

                        while (pokestopList.Any())
                        // warning: this is never entered due to ps cooldowns from UseNearbyPokestopsTask
                        {
                            cancellationToken.ThrowIfCancellationRequested();

                            pokestopList =
                                pokestopList.OrderBy(
                                    i =>
                                    LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                            session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList();
                            var pokeStop = pokestopList[0];
                            pokestopList.RemoveAt(0);

                            var fortInfo =
                                await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                            if (pokeStop.LureInfo != null)
                            {
                                await CatchLurePokemonsTask.Execute(session, pokeStop, cancellationToken);
                            }

                            var fortSearch =
                                await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                            if (fortSearch.ExperienceAwarded > 0)
                            {
                                session.EventDispatcher.Send(new FortUsedEvent
                                {
                                    Id        = pokeStop.Id,
                                    Name      = fortInfo.Name,
                                    Exp       = fortSearch.ExperienceAwarded,
                                    Gems      = fortSearch.GemsAwarded,
                                    Items     = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded),
                                    Latitude  = pokeStop.Latitude,
                                    Longitude = pokeStop.Longitude
                                });
                            }
                            if (fortSearch.ItemsAwarded.Count > 0)
                            {
                                await session.Inventory.RefreshCachedInventory();
                            }
                        }

                        if (DateTime.Now > _lastTasksCall)
                        {
                            _lastTasksCall =
                                DateTime.Now.AddMilliseconds(Math.Min(session.LogicSettings.DelayBetweenPlayerActions,
                                                                      3000));

                            await RecycleItemsTask.Execute(session, cancellationToken);

                            if (session.LogicSettings.SnipeAtPokestops || session.LogicSettings.UseSnipeLocationServer)
                            {
                                await SnipePokemonTask.Execute(session, cancellationToken);
                            }

                            if (session.LogicSettings.EvolveAllPokemonWithEnoughCandy ||
                                session.LogicSettings.EvolveAllPokemonAboveIv)
                            {
                                await EvolvePokemonTask.Execute(session, cancellationToken);
                            }

                            if (session.LogicSettings.TransferDuplicatePokemon)
                            {
                                await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                            }

                            if (session.LogicSettings.RenamePokemon)
                            {
                                await RenamePokemonTask.Execute(session, cancellationToken);
                            }
                        }

                        await session.Navigation.HumanPathWalking(
                            trackPoints.ElementAt(curTrkPt),
                            session.LogicSettings.WalkingSpeedInKilometerPerHour,
                            async() =>
                        {
                            await CatchNearbyPokemonsTask.Execute(session, cancellationToken);
                            //Catch Incense Pokemon
                            await CatchIncensePokemonsTask.Execute(session, cancellationToken);
                            await UseNearbyPokestopsTask.Execute(session, cancellationToken);
                            return(true);
                        },
                            cancellationToken
                            );

                        await eggWalker.ApplyDistance(distance, cancellationToken);
                    } //end trkpts
                }     //end trksegs
            }         //end tracks
        }
Example #9
0
 internal void UpdateDistance(double lat, double lng)
 {
     Distance = LocationUtils.CalculateDistanceInMeters(lat, lng, Latitude, Longitude);
     RaisePropertyChanged("Distance");
 }
        public static async Task <FortData> GetNextPokeStop(ISession session)
        {
            var priorityTarget = await SetMoveToTargetTask.GetTarget(session);

            if (priorityTarget != null)
            {
                return(priorityTarget);
            }


            if (session.Forts == null ||
                session.Forts.Count == 0 ||
                session.Forts.Count(p => p.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime()) == 0)
            {
                //TODO : A logic need to be add for handle this  case?
            }
            ;

            var deployedPokemons = session.Inventory.GetDeployedPokemons();

            //NOTE : This code is killing perfomance of BOT if GYM is turn on, need to refactor to avoid this hummer call API

            var forts = session.Forts
                        .Where(p => p.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime())
                        .Where(f => f.Type == FortType.Checkpoint ||
                               (session.LogicSettings.GymConfig.Enable && (
                                    UseGymBattleTask.CanAttackGym(session, f, deployedPokemons) ||
                                    UseGymBattleTask.CanTrainGym(session, f, deployedPokemons) ||
                                    UseGymBattleTask.CanDeployToGym(session, f, deployedPokemons))))
                        .ToList();

            if (session.LogicSettings.GymConfig.Enable &&
                ((session.LogicSettings.GymConfig.EnableAttackGym && forts.Where(w => w.Type == FortType.Gym && UseGymBattleTask.CanAttackGym(session, w, deployedPokemons)).Count() == 0) ||
                 (session.LogicSettings.GymConfig.EnableGymTraining && forts.Where(w => w.Type == FortType.Gym && UseGymBattleTask.CanTrainGym(session, w, deployedPokemons)).Count() == 0)
                ))
            {
                //Logger.Write("No usable gym found. Trying to refresh list.", LogLevel.Gym, ConsoleColor.Magenta);
                await GetPokeStops(session);
            }

            forts = forts.OrderBy(
                p =>
                session.Navigation.WalkStrategy.CalculateDistance(
                    session.Client.CurrentLatitude,
                    session.Client.CurrentLongitude,
                    p.Latitude,
                    p.Longitude,
                    session)
                ).ToList();

            if (session.LogicSettings.UseGpxPathing)
            {
                forts = forts.Where(p => LocationUtils.CalculateDistanceInMeters(p.Latitude, p.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude) < 40).ToList();
            }

            var reviveCount = session.Inventory.GetItems().Where(w => w.ItemId == POGOProtos.Inventory.Item.ItemId.ItemRevive || w.ItemId == POGOProtos.Inventory.Item.ItemId.ItemMaxRevive).Select(s => s.Count).Sum();

            if (!session.LogicSettings.GymConfig.Enable ||
                session.LogicSettings.GymConfig.MinRevivePotions > reviveCount
                /*|| session.Inventory.GetPlayerStats().FirstOrDefault().Level <= 5*/
                )
            {
                // Filter out the gyms
                forts = forts.Where(x => x.Type != FortType.Gym).ToList();
            }
            else if (session.LogicSettings.GymConfig.PrioritizeGymOverPokestop)
            {
                // Prioritize gyms over pokestops
                var gyms = forts.Where(x => x.Type == FortType.Gym &&
                                       LocationUtils.CalculateDistanceInMeters(x.Latitude, x.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude) < session.LogicSettings.GymConfig.MaxDistance);
                //.OrderBy(x => LocationUtils.CalculateDistanceInMeters(x.Latitude, x.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude));

                if (session.LogicSettings.GymConfig.PrioritizeGymWithFreeSlot)
                {
                    var freeSlots = gyms.Where(w => w.OwnedByTeam == session.Profile.PlayerData.Team && UseGymBattleTask.CanDeployToGym(session, w, deployedPokemons));
                    if (freeSlots.Count() > 0)
                    {
                        return(freeSlots.First());
                    }
                }

                // Return the first gym in range.
                if (gyms.Count() > 0)
                {
                    return(gyms.FirstOrDefault());
                }
            }

            return(forts.FirstOrDefault());
        }
        private static async Task FarmPokestop(ISession session, FortData pokeStop, FortDetailsResponse fortInfo, CancellationToken cancellationToken, bool doNotRetry = false)
        {
            // If the cooldown is in the future than don't farm the pokestop.
            if (pokeStop.CooldownCompleteTimestampMs > DateTime.UtcNow.ToUnixTime())
            {
                return;
            }

            if (session.Stats.SearchThresholdExceeds(session, true))
            {
                if (session.LogicSettings.AllowMultipleBot && session.LogicSettings.MultipleBotConfig.SwitchOnPokestopLimit)
                {
                    throw new Exceptions.ActiveSwitchByRuleException(SwitchRules.SpinPokestopReached, session.LogicSettings.PokeStopLimit);
                }
                return;
            }

            //await session.Client.Map.GetMapObjects();
            FortSearchResponse fortSearch;
            var timesZeroXPawarded = 0;
            var fortTry            = 0;                                     //Current check
            int retryNumber        = session.LogicSettings.ByPassSpinCount; //How many times it needs to check to clear softban
            int zeroCheck          = Math.Min(5, retryNumber);              //How many times it checks fort before it thinks it's softban

            var distance = LocationUtils.CalculateDistanceInMeters(pokeStop.Latitude, pokeStop.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude);

            if (distance > 30)
            {
                LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinatePortable.GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude), 0);
                await session.Client.Misc.RandomAPICall();
            }

            do
            {
                cancellationToken.ThrowIfCancellationRequested();
                TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
                int    retry     = 3;
                double latitude  = pokeStop.Latitude;
                double longitude = pokeStop.Longitude;
                do
                {
                    fortSearch = await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                    if (fortSearch.Result == FortSearchResponse.Types.Result.OutOfRange)
                    {
                        if (retry > 2)
                        {
                            await Task.Delay(500);
                        }
                        else
                        {
                            await session.Client.Map.GetMapObjects(true);
                        }

                        Logger.Debug($"Loot pokestop result: {fortSearch.Result}, distance to pokestop:[{pokeStop.Latitude}, {pokeStop.Longitude}] {distance:0.00}m, retry: #{4 - retry}");

                        latitude  += 0.000003;
                        longitude += 0.000005;
                        LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinatePortable.GeoCoordinate(latitude, longitude), 0);
                        retry--;
                    }
                }while (fortSearch.Result == FortSearchResponse.Types.Result.OutOfRange && retry > 0);
                Logger.Debug($"Loot pokestop result: {fortSearch.Result}");
                if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0)
                {
                    timesZeroXPawarded = 0;
                }
                if (fortSearch.ExperienceAwarded == 0 && fortSearch.Result != FortSearchResponse.Types.Result.InventoryFull)
                {
                    timesZeroXPawarded++;

                    if (timesZeroXPawarded > zeroCheck)
                    {
                        if ((int)fortSearch.CooldownCompleteTimestampMs != 0)
                        {
                            break; // Check if successfully looted, if so program can continue as this was "false alarm".
                        }

                        fortTry += 1;

                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry,
                            Max    = retryNumber - zeroCheck,
                            Looted = false
                        });
                        if (doNotRetry)
                        {
                            break;
                        }
                        if (!session.LogicSettings.FastSoftBanBypass)
                        {
                            DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0);
                        }
                    }
                }
                else
                {
                    softbanCount = 0;
                    if (fortTry != 0)
                    {
                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry + 1,
                            Max    = retryNumber - zeroCheck,
                            Looted = true
                        });
                    }

                    session.EventDispatcher.Send(new FortUsedEvent
                    {
                        Id            = pokeStop.Id,
                        Name          = fortInfo.Name,
                        Exp           = fortSearch.ExperienceAwarded,
                        Gems          = fortSearch.GemsAwarded,
                        Items         = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded),
                        Latitude      = pokeStop.Latitude,
                        Longitude     = pokeStop.Longitude,
                        Altitude      = session.Client.CurrentAltitude,
                        InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull,
                        Fort          = pokeStop
                    });
                    if (fortSearch.Result == FortSearchResponse.Types.Result.Success)
                    {
                        mapEmptyCount = 0;
                        foreach (var item in fortSearch.ItemsAwarded)
                        {
                            await session.Inventory.UpdateInventoryItem(item.ItemId);
                        }
                        if (fortSearch.PokemonDataEgg != null)
                        {
                            fortSearch.PokemonDataEgg.IsEgg = true;
                        }

                        // Update the cache
                        var fortFromCache = session.Client.Map.LastGetMapObjectResponse.MapCells.SelectMany(x => x.Forts).FirstOrDefault(f => f.Id == pokeStop.Id);

                        long newCooldown = TimeUtil.GetCurrentTimestampInMilliseconds() + (5 * 60 * 1000); /* 5 min */
                        fortFromCache.CooldownCompleteTimestampMs = newCooldown;
                        pokeStop.CooldownCompleteTimestampMs      = newCooldown;

                        if (session.SaveBallForByPassCatchFlee)
                        {
                            var totalBalls = session.Inventory.GetItems().Where(x => x.ItemId == ItemId.ItemPokeBall || x.ItemId == ItemId.ItemGreatBall || x.ItemId == ItemId.ItemUltraBall).Sum(x => x.Count);
                            Logger.Write($"Ball requires for by pass catch flee {totalBalls}/{CatchPokemonTask.BALL_REQUIRED_TO_BYPASS_CATCHFLEE}");
                        }
                        else
                        {
                            MSniperServiceTask.UnblockSnipe(false);
                        }
                    }
                    if (fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull)
                    {
                        await RecycleItemsTask.Execute(session, cancellationToken);

                        _storeRi = 1;
                    }

                    if (session.LogicSettings.UsePokeStopLimit)
                    {
                        session.Stats.AddPokestopTimestamp(DateTime.Now.Ticks);
                        session.EventDispatcher.Send(new PokestopLimitUpdate(session.Stats.GetNumPokestopsInLast24Hours(), session.LogicSettings.PokeStopLimit));
                    }
                    //add pokeStops to Map
                    OnLootPokestopEvent(pokeStop);
                    //end pokeStop to Map

                    break; //Continue with program as loot was succesfull.
                }
            } while (fortTry < retryNumber - zeroCheck);
            //Stop trying if softban is cleaned earlier or if 40 times fort looting failed.

            if (session.LogicSettings.AllowMultipleBot)
            {
                if (fortTry >= retryNumber - zeroCheck)
                {
                    softbanCount++;

                    //only check if PokestopSoftbanCount > 0
                    if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings) &&
                        session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount > 0 &&
                        session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount <= softbanCount &&
                        TinyIoCContainer.Current.Resolve <MultiAccountManager>().AllowSwitch())
                    {
                        softbanCount = 0;

                        //Activate switcher by pokestop
                        throw new ActiveSwitchByRuleException()
                              {
                                  MatchedRule  = SwitchRules.PokestopSoftban,
                                  ReachedValue = session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount
                              };
                    }
                }
            }
            else
            {
                softbanCount = 0; //reset softban count
            }

            if (session.LogicSettings.RandomlyPauseAtStops && !doNotRetry)
            {
                if (++_randomStop >= _randomNumber)
                {
                    _randomNumber = _rc.Next(4, 11);
                    _randomStop   = 0;
                    int randomWaitTime = _rc.Next(30, 120);
                    await Task.Delay(randomWaitTime, cancellationToken);
                }
            }
        }
Example #12
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            var ioc = TinyIoC.TinyIoCContainer.Current;

            //Setup Logger for API
            APIConfiguration.Logger = new APILogListener();

            //Application.EnableVisualStyles();
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2 Loading";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            //
            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write(
                            "Migrating existing json confix to excel config, please check the config.xlsm in your config folder"
                            );

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // Values are available here
                if (options.Init)
                {
                    settings.GenerateAccount(options.IsGoogle, options.Template, options.Start, options.End, options.Password);
                }
            }
            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    //If lastcoord is snipe coord, bot start from default location

                    if (LocationUtils.CalculateDistanceInMeters(lat, lng, settings.LocationConfig.DefaultLatitude, settings.LocationConfig.DefaultLongitude) < 2000)
                    {
                        settings.LocationConfig.DefaultLatitude  = lat;
                        settings.LocationConfig.DefaultLongitude = lng;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            if (!_ignoreKillSwitch)
            {
                if (CheckMKillSwitch() || CheckKillSwitch())
                {
                    return;
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            TinyIoC.TinyIoCContainer.Current.Register <ITranslation>(translation);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    )
                                .OrderBy(pt => pt.Distance)
                                .FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }

            IElevationService elevationService = new ElevationService(settings);

            if (boolNeedsSetup)
            {
                //validation auth.config
                AuthAPIForm form = new AuthAPIForm(true);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }

                _session = new Session(settings, new ClientSettings(settings, elevationService), logicSettings, elevationService, translation);

                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetEntryAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                //    var fileName = Assembly.GetExecutingAssembly().Location;
                //    Process.Start(fileName);
                //    Environment.Exit(0);
                //}
            }
            else
            {
                _session = new Session(settings, new ClientSettings(settings, elevationService), logicSettings, elevationService, translation);

                var apiCfg = settings.Auth.APIConfig;

                if (apiCfg.UsePogoDevAPI || apiCfg.UseCustomAPI)
                {
                    if (string.IsNullOrEmpty(apiCfg.AuthAPIKey))
                    {
                        Logger.Write(
                            "You have selected PogoDev API but you have not provided an API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer",
                            LogLevel.Error
                            );
                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    try
                    {
                        HttpClient client   = new HttpClient();
                        string     urlcheck = null;
                        client.DefaultRequestHeaders.Add("X-AuthToken", apiCfg.AuthAPIKey);
                        var maskedKey = apiCfg.AuthAPIKey.Substring(0, 4) + "".PadLeft(apiCfg.AuthAPIKey.Length - 8, 'X') + apiCfg.AuthAPIKey.Substring(apiCfg.AuthAPIKey.Length - 4, 4);
                        if (settings.Auth.APIConfig.UseCustomAPI)
                        {
                            urlcheck = $"{settings.Auth.APIConfig.UrlHashServices}{settings.Auth.APIConfig.EndPoint}";
                        }
                        else
                        {
                            urlcheck = $"https://pokehash.buddyauth.com/{Constants.ApiEndPoint}";
                        }
                        Logger.Write($"Hash End-Point Set to '{urlcheck}'", LogLevel.Info, ConsoleColor.Blue);
                        HttpResponseMessage response = client.PostAsync(urlcheck, null).Result;
                        string   AuthKey             = response.Headers.GetValues("X-AuthToken").FirstOrDefault();
                        string   MaxRequestCount     = response.Headers.GetValues("X-MaxRequestCount").FirstOrDefault();
                        DateTime AuthTokenExpiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified).AddSeconds(Convert.ToDouble(response.Headers.GetValues("X-AuthTokenExpiration").FirstOrDefault())).ToLocalTime();
                        TimeSpan Expiration          = AuthTokenExpiration - DateTime.Now;
                        string   Result = $"Key: {maskedKey} RPM: {MaxRequestCount} Expires in: {Expiration.Days - 1} days ({AuthTokenExpiration})";
                        Logger.Write(Result, LogLevel.Info, ConsoleColor.Green);
                    }
                    catch
                    {
                        Logger.Write("The HashKey is invalid or has expired, please press any key to exit and correct your auth.json, \r\nThe PogoDev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer", LogLevel.Error);
                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                }

                //GlobalSettings.Load(_subPath, _enableJsonValidation);

                //Logger.Write("Press a Key to continue...",
                //    LogLevel.Warning);
                //Console.ReadKey();
                //return;

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ioc.Register <ISession>(_session);

            Logger.SetLoggerContext(_session);

            MultiAccountManager accountManager = new MultiAccountManager(settings, logicSettings.Bots);

            ioc.Register(accountManager);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetEntryAssembly().Location;

                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                //    var fileName = Assembly.GetExecutingAssembly().Location;
                //    Process.Start(fileName);
                //    Environment.Exit(0);
                //}
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = _session.RuntimeStatistics;

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);

            stats.DirtyEvent +=
                () =>
            {
                GetPlayerResponse x    = _session.Client.Player.GetPlayer().Result;
                string            warn = x.Warn ? "*(Flagged)*-" : null;

                Console.Title = $"[NecroBot2 v{strVersion}] Team: {x.PlayerData.Team} - {warn}" +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            };
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);

            onBotStarted?.Invoke(_session, aggregator);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (session, lat, lng, speed) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng, Speed = speed
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += LoadSaveState.SaveLocationToDisk;

            ProgressBar.Fill(100);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            var bot = accountManager.GetStartUpAccount();

            _session.ReInitSessionWithNextBot(bot);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe &&
                _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session,
                                                         _session.CancellationTokenSource.Token).ConfigureAwait(false); // that need to keep data live
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }


            if (_session.LogicSettings.DataSharingConfig.EnableSyncData)
            {
                BotDataSocketClient.StartAsync(_session, Properties.Resources.EncryptKey);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;
                //temporary disable MSniper connection because site under attacking.
                //MSniperServiceTask.ConnectToService();
                //_session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }

            // jjskuld - Don't await the analytics service since it starts a worker thread that never returns.
#pragma warning disable 4014
            _session.AnalyticsService.StartAsync(_session, _session.CancellationTokenSource.Token);
#pragma warning restore 4014
            _session.EventDispatcher.EventReceived += evt => AnalyticsService.Listen(evt, _session);

            var trackFile = Path.GetTempPath() + "\\NecroBot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }

            QuitEvent.WaitOne();
        }
Example #13
0
        public static async Task Teleport(ISession session, CancellationToken cancellationToken, Random random)
        {
            bool ShownSoftBanMessage = false;
            int  stopsToHit          = 20; //We should return to the main loop after some point, might as well limit this.
            //Not sure where else we could put this? Configs maybe if we incorporate
            //deciding how many pokestops in a row we want to hit before doing things like recycling?
            //might increase xp/hr not stopping every 5 stops. - Pocket


            //TODO: run through this with a fine-tooth comb and optimize it.
            var pokestopList = await GetPokeStops(session);

            session.EventDispatcher.Send(new PokeStopListEvent {
                Forts = pokestopList.Select(x => x.BaseFortData).ToList()
            });

            for (int stopsHit = 0; stopsHit < stopsToHit; stopsHit++)
            {
                session.Runtime.BreakOutOfPathing = false;
                if (pokestopList.Count > 0)
                {
                    //start at 0 ends with 19 = 20 for the leechers{
                    cancellationToken.ThrowIfCancellationRequested();

                    var distanceFromStart = LocationUtils.CalculateDistanceInMeters(
                        session.Client.InitialLatitude, session.Client.InitialLongitude,
                        session.Client.CurrentLatitude, session.Client.CurrentLongitude);

                    // Edge case for when the client somehow ends up outside the defined radius
                    if (session.LogicSettings.MaxTravelDistanceInMeters != 0 &&
                        distanceFromStart > session.LogicSettings.MaxTravelDistanceInMeters)
                    {
                        session.EventDispatcher.Send(new WarnEvent()
                        {
                            Message = session.Translation.GetTranslation(TranslationString.FarmPokestopsOutsideRadius, distanceFromStart)
                        });
                        await Task.Delay(1000, cancellationToken);

                        await session.Navigation.Move(
                            new GeoCoordinate(session.Settings.DefaultLatitude, session.Settings.DefaultLongitude),
                            session.LogicSettings.WalkingSpeedMin, session.LogicSettings.WalkingSpeedMax, null, null, cancellationToken, session);
                    }
                    if (session.ForceMoveJustDone)
                    {
                        session.ForceMoveJustDone = false;
                    }
                    if (session.ForceMoveTo != null)
                    {
                        await ForceMoveTask.Execute(session, cancellationToken);

                        pokestopList = await GetPokeStops(session);
                    }
                    var eggWalker = new EggWalker(1000, session);

                    if (pokestopList.Count <= 0)
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message = session.Translation.GetTranslation(TranslationString.FarmPokestopsNoUsableFound)
                        });
                    }

                    cancellationToken.ThrowIfCancellationRequested();

                    //resort
                    pokestopList =
                        pokestopList.OrderBy(
                            i =>
                            LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                    session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList();

                    if (session.LogicSettings.UsePokeStopLuckyNumber)
                    {
                        if (pokestopList.Count >= session.LogicSettings.PokestopSkipLuckyNumberMinUse)
                        {
                            int rng = random.Next(session.LogicSettings.PokestopSkipLuckyMin, session.LogicSettings.PokestopSkipLuckyMax);
#if DEBUG
                            Logger.Write("Skip Pokestop RNG: " + rng.ToString() + " against " + session.LogicSettings.PokestopSkipLuckyNumber.ToString(), LogLevel.Debug);
#endif
                            if (rng == session.LogicSettings.PokestopSkipLuckyNumber)
                            {
#if DEBUG
                                Logger.Write("Skipping Pokestop due to the rng god's will.", LogLevel.Debug);
#endif
                                pokestopList.RemoveAt(0);
                            }
                        }
                    }


                    var pokeStop = pokestopList[0];
                    pokestopList.RemoveAt(0);
                    session.Runtime.TargetStopID = pokeStop.Id;
                    var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                           session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude);
                    var fortInfo = await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                    session.EventDispatcher.Send(new FortTargetEvent {
                        Id = fortInfo.FortId, Name = fortInfo.Name, Distance = distance, Latitude = fortInfo.Latitude, Longitude = fortInfo.Longitude, Description = fortInfo.Description, url = fortInfo.ImageUrls[0]
                    });
                    if (session.LogicSettings.Teleport)
                    {
                        await session.Client.Player.UpdatePlayerLocation(fortInfo.Latitude, fortInfo.Longitude,
                                                                         session.Client.Settings.DefaultAltitude);
                    }

                    else
                    {
                        await session.Navigation.Move(new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude),
                                                      session.LogicSettings.WalkingSpeedMin, session.LogicSettings.WalkingSpeedMax,
                                                      async() =>
                        {
                            if (session.LogicSettings.CatchWildPokemon)
                            {
                                // Catch normal map Pokemon
                                await CatchNearbyPokemonsTask.Execute(session, cancellationToken);
                                //Catch Incense Pokemon remove this for time contraints
                                //await CatchIncensePokemonsTask.Execute(session, cancellationToken);
                            }
                            return(true);
                        },
                                                      async() =>
                        {
                            await UseNearbyPokestopsTask.Execute(session, cancellationToken);
                            return(true);
                        },

                                                      cancellationToken, session);
                    }

                    if (!session.LogicSettings.LootPokestops)
                    {
                        session.MapCache.UsedPokestop(pokeStop, session);
                        continue;
                    }

                    if (!session.ForceMoveJustDone)
                    {
                        FortSearchResponse fortSearch;
                        var       timesZeroXPawarded = 0;
                        var       fortTry            = 0;  //Current check
                        const int retryNumber        = 50; //How many times it needs to check to clear softban
                        const int zeroCheck          = 5;  //How many times it checks fort before it thinks it's softban
                        if (session.Runtime.BreakOutOfPathing)
                        {
                            continue;
                        }
                        do
                        {
                            cancellationToken.ThrowIfCancellationRequested();

                            fortSearch =
                                await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                            if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0)
                            {
                                timesZeroXPawarded = 0;
                            }
                            if (fortSearch.ExperienceAwarded == 0)
                            {
                                timesZeroXPawarded++;

                                if (timesZeroXPawarded > zeroCheck)
                                {
                                    if ((int)fortSearch.CooldownCompleteTimestampMs != 0)
                                    {
                                        break;
                                        // Check if successfully looted, if so program can continue as this was "false alarm".
                                    }

                                    fortTry += 1;

                                    if (!ShownSoftBanMessage)
                                    {
                                        session.EventDispatcher.Send(new FortFailedEvent
                                        {
                                            Name = fortInfo.Name,
                                            Try  = fortTry,
                                            Max  = retryNumber - zeroCheck
                                        });
                                        ShownSoftBanMessage = true;
                                    }
                                    await Task.Delay(session.LogicSettings.DelaySoftbanRetry);
                                }
                            }
                            else
                            {
                                session.EventDispatcher.Send(new FortUsedEvent
                                {
                                    Id            = pokeStop.Id,
                                    Name          = fortInfo.Name,
                                    Exp           = fortSearch.ExperienceAwarded,
                                    Gems          = fortSearch.GemsAwarded,
                                    Items         = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded),
                                    Latitude      = pokeStop.Latitude,
                                    Longitude     = pokeStop.Longitude,
                                    InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull,
                                    Description   = fortInfo.Description,
                                    url           = fortInfo.ImageUrls[0]
                                });
                                session.MapCache.UsedPokestop(pokeStop, session);
                                session.EventDispatcher.Send(new InventoryNewItemsEvent()
                                {
                                    Items = fortSearch.ItemsAwarded.ToItemList()
                                });
                                break; //Continue with program as loot was succesfull.
                            }
                        } while (fortTry < retryNumber - zeroCheck);
                        //Stop trying if softban is cleaned earlier or if 40 times fort looting failed.

                        ShownSoftBanMessage = false;
                        await Task.Delay(session.LogicSettings.DelayPokestop);


                        //Catch Lure Pokemon

                        if (session.LogicSettings.CatchWildPokemon)
                        {
                            if (pokeStop.LureInfo != null)
                            {
                                await CatchLurePokemonsTask.Execute(session, pokeStop.BaseFortData, cancellationToken);
                            }
                            // Catch normal map Pokemon
                            if (session.LogicSettings.Teleport)
                            {
                                await CatchNearbyPokemonsTask.Execute(session, cancellationToken);
                            }
                            //Catch Incense Pokemon
                            await CatchIncensePokemonsTask.Execute(session, cancellationToken);
                        }


                        await eggWalker.ApplyDistance(distance, cancellationToken);

                        await MaintenanceTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.SnipeAtPokestops || session.LogicSettings.UseSnipeLocationServer)
                    {
                        await SnipePokemonTask.Execute(session, cancellationToken);
                    }
                }
            }
        }
Example #14
0
        public static async Task NoTeleport(ISession session, CancellationToken cancellationToken, Random random)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var distanceFromStart = LocationUtils.CalculateDistanceInMeters(
                session.Settings.DefaultLatitude, session.Settings.DefaultLongitude,
                session.Client.CurrentLatitude, session.Client.CurrentLongitude);

            // Edge case for when the client somehow ends up outside the defined radius
            if (session.LogicSettings.MaxTravelDistanceInMeters != 0 &&
                distanceFromStart > session.LogicSettings.MaxTravelDistanceInMeters)
            {
                session.EventDispatcher.Send(new WarnEvent()
                {
                    Message = session.Translation.GetTranslation(TranslationString.FarmPokestopsOutsideRadius, distanceFromStart)
                });
                await Task.Delay(1000, cancellationToken);

                await session.Navigation.Move(
                    new GeoCoordinate(session.Settings.DefaultLatitude, session.Settings.DefaultLongitude),
                    session.LogicSettings.WalkingSpeedMin, session.LogicSettings.WalkingSpeedMax, null, null, cancellationToken, session);
            }

            var pokestopList = await GetPokeStops(session);

            //var stopsHit = 0; //Replaced with RuntimeSettings.stopsHit;
            //var displayStatsHit = 0;

            session.EventDispatcher.Send(new PokeStopListEvent {
                Forts = pokestopList.Select(x => x.BaseFortData).ToList()
            });

            var eggWalker = new EggWalker(1000, session);

            if (pokestopList.Count <= 0)
            {
                session.EventDispatcher.Send(new WarnEvent
                {
                    Message = session.Translation.GetTranslation(TranslationString.FarmPokestopsNoUsableFound)
                });
            }
            var bestRoute = new List <GeoCoordinate>();

            while (pokestopList.Any())
            {
                session.Runtime.BreakOutOfPathing = false;
                cancellationToken.ThrowIfCancellationRequested();
                if (session.ForceMoveJustDone)
                {
                    session.ForceMoveJustDone = false;
                }
                if (session.ForceMoveTo != null)
                {
                    await ForceMoveTask.Execute(session, cancellationToken);

                    pokestopList = await GetPokeStops(session);
                }

                //resort
                pokestopList =
                    pokestopList.OrderBy(
                        i =>
                        LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList();

                if (session.LogicSettings.UsePokeStopLuckyNumber)
                {
                    if (pokestopList.Count >= session.LogicSettings.PokestopSkipLuckyNumberMinUse)
                    {
                        int rng = random.Next(session.LogicSettings.PokestopSkipLuckyMin, session.LogicSettings.PokestopSkipLuckyMax);
#if DEBUG
                        Logger.Write("Skip Pokestop RNG: " + rng.ToString() + " against " + session.LogicSettings.PokestopSkipLuckyNumber.ToString(), LogLevel.Debug);
#endif
                        if (rng == session.LogicSettings.PokestopSkipLuckyNumber)
                        {
#if DEBUG
                            Logger.Write("Skipping Pokestop due to the rng god's will.", LogLevel.Debug);
#endif
                            if (pokestopList.Count > 0)
                            {
                                pokestopList.RemoveAt(0);
                            }
                        }
                    }
                }
                if (pokestopList.Count == 0)
                {
                    break;
                }

                var pokeStop = pokestopList[0];
                pokestopList.RemoveAt(0);

                if (session.LogicSettings.RoutingService == RoutingService.GoogleDirections || session.LogicSettings.RoutingService == RoutingService.MapzenValhalla)
                {
                    bestRoute = RoutingUtils.GetBestRoute(pokeStop, pokestopList.Where(x => !session.MapCache.CheckPokestopUsed(x)), 20);
                    session.EventDispatcher.Send(new PokestopsOptimalPathEvent()
                    {
                        Coords = bestRoute.Select(x => Tuple.Create(x.Latitude, x.Longitude)).ToList()
                    });
                }

                session.Runtime.TargetStopID = pokeStop.Id;
                var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                       session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude);
                var fortInfo = await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                session.EventDispatcher.Send(new FortTargetEvent {
                    Id = fortInfo.FortId, Name = fortInfo.Name, Distance = distance, Latitude = fortInfo.Latitude, Longitude = fortInfo.Longitude, Description = fortInfo.Description, url = fortInfo.ImageUrls?.Count > 0 ? fortInfo.ImageUrls[0] : ""
                });

                await session.Navigation.Move(new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude),
                                              session.LogicSettings.WalkingSpeedMin, session.LogicSettings.WalkingSpeedMax,
                                              async() =>
                {
                    if (session.LogicSettings.CatchWildPokemon)
                    {
                        // Catch normal map Pokemon
                        await CatchNearbyPokemonsTask.Execute(session, cancellationToken);

                        //Catch Incense Pokemon remove this for time constraints
                        //await CatchIncensePokemonsTask.Execute(session, cancellationToken);
                    }
                    return(true);
                },
                                              async() =>
                {
                    await UseNearbyPokestopsTask.Execute(session, cancellationToken);
                    return(true);
                },
                                              cancellationToken, session, waypointsToVisit : bestRoute, eggWalker : eggWalker);

                if (!session.ForceMoveJustDone)
                {
                    var timesZeroXPawarded = 0;

                    var       fortTry     = 0;  //Current check
                    const int retryNumber = 50; //How many times it needs to check to clear softban
                    const int zeroCheck   = 5;  //How many times it checks fort before it thinks it's softban
                    if (session.Runtime.BreakOutOfPathing)
                    {
                        continue;
                    }
                    do
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        if (pokeStop.CooldownCompleteTimestampMS < DateTime.UtcNow.ToUnixTime())
                        {
                            break;                                                                      //already looted somehow
                        }
                        var fortSearch = await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                        if (fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull)
                        {
                            await RecycleItemsTask.Execute(session, cancellationToken);
                        }
                        if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0)
                        {
                            timesZeroXPawarded = 0;
                        }
                        if (fortSearch.ExperienceAwarded == 0)
                        {
                            timesZeroXPawarded++;

                            if (timesZeroXPawarded > zeroCheck)
                            {
                                if ((int)fortSearch.CooldownCompleteTimestampMs != 0)
                                {
                                    break;
                                    // Check if successfully looted, if so program can continue as this was "false alarm".
                                }

                                fortTry += 1;


                                if (session.LogicSettings.Teleport)
                                {
                                    session.EventDispatcher.Send(new FortFailedEvent
                                    {
                                        Name = fortInfo.Name,
                                        Try  = fortTry,
                                        Max  = retryNumber - zeroCheck
                                    });
                                    await Task.Delay(session.LogicSettings.DelaySoftbanRetry, cancellationToken);
                                }
                                else
                                {
                                    await DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 400);
                                }
                            }
                        }
                        else
                        {
                            session.EventDispatcher.Send(new FortUsedEvent
                            {
                                Id            = pokeStop.Id,
                                Name          = fortInfo.Name,
                                Exp           = fortSearch.ExperienceAwarded,
                                Gems          = fortSearch.GemsAwarded,
                                Items         = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded),
                                Latitude      = pokeStop.Latitude,
                                Longitude     = pokeStop.Longitude,
                                InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull,
                                Description   = fortInfo.Description,
                                url           = fortInfo.ImageUrls?[0]
                            });
                            session.Runtime.StopsHit++;
                            session.EventDispatcher.Send(new InventoryNewItemsEvent()
                            {
                                Items = fortSearch.ItemsAwarded.ToItemList()
                            });
                            session.MapCache.UsedPokestop(pokeStop, session);
                            break; //Continue with program as loot was succesfull.
                        }
                    } while (fortTry < 1);
                    //retryNumber - zeroCheck && fortSearch.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime());
                    //Stop trying if softban is cleaned earlier or if 40 times fort looting failed.


                    await Task.Delay(session.LogicSettings.DelayPokestop, cancellationToken);


                    //Catch Lure Pokemon

                    if (session.LogicSettings.CatchWildPokemon)
                    {
                        if (pokeStop.LureInfo != null)
                        {
                            await CatchLurePokemonsTask.Execute(session, pokeStop.BaseFortData, cancellationToken);
                        }
                        if (session.LogicSettings.Teleport)
                        {
                            await CatchNearbyPokemonsTask.Execute(session, cancellationToken);
                        }
                    }
                    await eggWalker.ApplyDistance(distance, cancellationToken);
                }
                if (session.LogicSettings.SnipeAtPokestops || session.LogicSettings.UseSnipeLocationServer)
                {
                    await SnipePokemonTask.Execute(session, cancellationToken);
                }
            }
        }
Example #15
0
 public async Task <double> CalculateDistance(double sourceLat, double sourceLng, double destinationLat, double destinationLng)
 {
     return(1.5 * LocationUtils.CalculateDistanceInMeters(sourceLat, sourceLng, destinationLat, destinationLng));
 }
Example #16
0
        public async Task <IState> Execute(ISession session, CancellationToken cancellationToken)
        {
            //Console.WriteLine($"waiting data....., {data.Count}");
            CatchablePokemon pkm = null;
            var currentLatitude  = session.Client.CurrentLatitude;
            var currentLongitude = session.Client.CurrentLongitude;

            do
            {
                pkm = data.FirstOrDefault(p => !p.Checked &&
                                          p.ExpiredTime > DateTime.Now &&
                                          LocationUtils.CalculateDistanceInMeters(
                                              currentLatitude,
                                              currentLongitude,
                                              p.Latitude,
                                              p.Longitude
                                              ) < 100);
                if (pkm == null)
                {
                    break;
                }

                EncounterResponse encounter;
                try
                {
                    //await
                    //    LocationUtils.UpdatePlayerLocationWithAltitude(session,
                    //        new GeoCoordinate(pkm.Latitude, pkm.Longitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed.

                    await session.Navigation.Move(
                        new MapLocation(pkm.Latitude, pkm.Longitude, session.Client.CurrentAltitude),
                        null, session, cancellationToken).ConfigureAwait(false);

                    encounter = await session.Client.Encounter.EncounterPokemon(pkm.EncounteredId, pkm.SpawnId).ConfigureAwait(false);
                }
                finally
                {
                    //await
                    //    LocationUtils.UpdatePlayerLocationWithAltitude(session,
                    //        new GeoCoordinate(currentLatitude, currentLongitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed.
                }
                switch (encounter.Status)
                {
                case EncounterResponse.Types.Status.EncounterSuccess:
                    await CatchPokemonTask.Execute(session, cancellationToken, encounter, pkm.ToMapPokemon(),
                                                   currentFortData : null, sessionAllowTransfer : true).ConfigureAwait(false);

                    break;

                case EncounterResponse.Types.Status.PokemonInventoryFull:
                    if (session.LogicSettings.TransferDuplicatePokemon)
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually)
                        });
                    }

                    if (session.LogicSettings.EvolveAllPokemonAboveIv ||
                        session.LogicSettings.EvolveAllPokemonWithEnoughCandy ||
                        session.LogicSettings.UseLuckyEggsWhileEvolving ||
                        session.LogicSettings.KeepPokemonsThatCanEvolve)
                    {
                        await EvolvePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                    }
                    break;

                default:
                    session.EventDispatcher.Send(new WarnEvent
                    {
                        Message =
                            session.Translation.GetTranslation(
                                TranslationString.EncounterProblem, encounter.Status)
                    });
                    break;
                }
                pkm.Checked = true;
                await Task.Delay(1000).ConfigureAwait(false);
            } while (pkm != null);
            await Task.Delay(3000).ConfigureAwait(false);

            return(this);
        }
Example #17
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);
        }
Example #18
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();

            session.EventDispatcher.Send(new DebugEvent()
            {
                Message = session.Translation.GetTranslation(TranslationString.LookingForPokemon)
            });

            var pokemons = await GetNearbyPokemons(session);

            foreach (var pokemon in pokemons)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var pokeBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall);

                var greatBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemGreatBall);

                var ultraBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemUltraBall);

                var masterBallsCount = await session.Inventory.GetItemAmountByType(ItemId.ItemMasterBall);

                if (pokeBallsCount + greatBallsCount + ultraBallsCount + masterBallsCount == 0)
                {
                    session.EventDispatcher.Send(new NoticeEvent()
                    {
                        Message = session.Translation.GetTranslation(TranslationString.ZeroPokeballInv)
                    });
                    return;
                }

                if (session.LogicSettings.UsePokemonToNotCatchFilter &&
                    session.LogicSettings.PokemonsNotToCatch.Contains(pokemon.PokemonId))
                {
                    session.EventDispatcher.Send(new NoticeEvent()
                    {
                        Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped, session.Translation.GetPokemonName(pokemon.PokemonId))
                    });
                    continue;
                }

                var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                       session.Client.CurrentLongitude, pokemon.Latitude, pokemon.Longitude);
                await Task.Delay(distance > 100? 3000 : 500, cancellationToken);

                var encounter =
                    await session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId);

                if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess)
                {
                    await CatchPokemonTask.Execute(session, encounter, pokemon);
                }
                else if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull)
                {
                    if (session.LogicSettings.TransferDuplicatePokemon)
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring)
                        });
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                    }
                    else
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually)
                        });
                    }
                }
                else
                {
                    session.EventDispatcher.Send(new WarnEvent
                    {
                        Message =
                            session.Translation.GetTranslation(TranslationString.EncounterProblem, encounter.Status)
                    });
                }

                // If pokemon is not last pokemon in list, create delay between catches, else keep moving.
                if (!Equals(pokemons.ElementAtOrDefault(pokemons.Count() - 1), pokemon))
                {
                    if (session.LogicSettings.Teleport)
                    {
                        await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch);
                    }
                    else
                    {
                        await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken);
                    }
                }
            }
        }
Example #19
0
        private static void Main(string[] args)
        {
            string strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = "NecroBot";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            if (args.Length > 0)
            {
                subPath = args[0];
            }

            Logger.SetLogger(new ConsoleLogger(LogLevel.LevelUp), subPath);

            if (CheckKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            GlobalSettings settings;
            Boolean        boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                // If the current program is not the latest version, ensure we skip saving the file after loading
                // This is to prevent saving the file with new options at their default values so we can check for differences
                settings = GlobalSettings.Load(subPath, !VersionCheckState.IsLatest());
            }
            else
            {
                settings                   = new GlobalSettings();
                settings.ProfilePath       = profilePath;
                settings.ProfileConfigPath = profileConfigPath;
                settings.GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config");
                settings.ConsoleConfig.TranslationLanguageCode = strCulture;

                boolNeedsSetup = true;
            }

            if (args.Length > 1)
            {
                string[] crds = args[1].Split(',');
                double   lat, lng;
                try
                {
                    lat = Double.Parse(crds[0]);
                    lng = Double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception) { }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var      text = File.ReadAllText(lastPosFile);
                string[] crds = text.Split(':');
                double   lat, lng;
                try
                {
                    lat = Double.Parse(crds[0]);
                    lng = Double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception) { }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    ).OrderBy(pt => pt.Distance).FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }

            session = new Session(new ClientSettings(settings), logicSettings, translation);

            Teste.Testar(session);
            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(session.Translation))
                {
                    session = GlobalSettings.SetupSettings(session, settings, configFile);

                    var fileName = Assembly.GetExecutingAssembly().Location;
                    System.Diagnostics.Process.Start(fileName);
                    Environment.Exit(0);
                }
                else
                {
                    GlobalSettings.Load(subPath);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }
            }

            ProgressBar.start("NecroBot is starting up", 10);

            session.Client.ApiFailure = new ApiFailureStrategy(session);
            ProgressBar.fill(20);

            /*SimpleSession session = new SimpleSession
             * {
             *  _client = new PokemonGo.RocketAPI.Client(new ClientSettings(settings)),
             *  _dispatcher = new EventDispatcher(),
             *  _localizer = new Localizer()
             * };
             *
             * BotService service = new BotService
             * {
             *  _session = session,
             *  _loginTask = new Login(session)
             * };
             *
             * service.Run();
             */

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.fill(30);
            string strVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot v{strVersion}] " +
                                stats.GetTemplatedStats(
                    session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.fill(60);
            var snipeEventListener = new SniperEventListener();

            session.EventDispatcher.EventReceived += evt => listener.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, session);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, session);
                session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, session);
            }

            ProgressBar.fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.fill(80);

            Logger.SetLoggerContext(session);
            ProgressBar.fill(90);

            session.Navigation.WalkStrategy.UpdatePositionEvent += (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;
            UseNearbyPokestopsTask.UpdateTimeStampsPokestop     += SaveTimeStampsPokestopToDisk;
            CatchPokemonTask.UpdateTimeStampsPokemon            += SaveTimeStampsPokemonToDisk;

            ProgressBar.fill(100);

            machine.AsyncStart(new VersionCheckState(), session, subPath);

            try
            { Console.Clear(); }
            catch (IOException) { }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                session.Telegram = new Logic.Service.TelegramService(settings.TelegramConfig.TelegramAPIKey, session);
            }

            if (session.LogicSettings.UseSnipeLocationServer)
            {
                SnipePokemonTask.AsyncStart(session);
            }

            settings.checkProxy(session.Translation);

            QuitEvent.WaitOne();
        }
        public static async Task Execute()
        {
            var distanceFromStart = LocationUtils.CalculateDistanceInMeters(
                Logic._client.Settings.DefaultLatitude, Logic._client.Settings.DefaultLongitude,
                Logic._client.CurrentLatitude, Logic._client.CurrentLongitude);

            // Edge case for when the client somehow ends up outside the defined radius
            if (Logic._client.Settings.MaxTravelDistanceInMeters != 0 &&
                distanceFromStart > Logic._client.Settings.MaxTravelDistanceInMeters)
            {
                Logger.Write(
                    $"You're outside of your defined radius! Walking to Default Coords ({distanceFromStart:0.##}m away). Is your LastCoords.ini file correct?",
                    LogLevel.Warning);
                await Navigation.HumanLikeWalking(
                    new GeoUtils(Logic._client.Settings.DefaultLatitude, Logic._client.Settings.DefaultLongitude),
                    async() =>
                {
                    // Catch normal map Pokemon
                    await CatchMapPokemonsTask.Execute();
                    //Catch Incense Pokemon
                    await CatchIncensePokemonsTask.Execute();
                    return(true);
                });
            }

            var pokestops = await Inventory.GetPokestops();

            if (pokestops == null || !pokestops.Any())
            {
                Logger.Write(
                    "No usable PokeStops found in your area. Reasons: Softbanned - Server Issues - MaxTravelDistanceInMeters too small",
                    LogLevel.Warning);
                return;
            }

            Logger.Write($"Found {pokestops.Count()} {(pokestops.Count() == 1 ? "Pokestop" : "Pokestops")}", LogLevel.Info);
            Gui.SetPokestopMarker(pokestops);

            while (pokestops.Any())
            {
                if (Logic._client.Settings.UseCSVExport && ExportPokemonToCsv._lastExportTime.AddMinutes(Logic._client.Settings.CSVExportInMinutes).Ticks < DateTime.Now.Ticks)
                {
                    var _playerProfile = await Logic._client.Player.GetPlayer();

                    await ExportPokemonToCsv.Execute(_playerProfile.PlayerData);
                }
                if (Logic._client.Settings.UseLuckyEggs)
                {
                    await UseLuckyEggTask.Execute();
                }
                if (Logic._client.Settings.CatchIncensePokemon)
                {
                    await UseIncenseTask.Execute();
                }

                var pokestopwithcooldown = pokestops.Where(p => p.CooldownCompleteTimestampMs > DateTime.UtcNow.ToUnixTime()).FirstOrDefault();
                if (pokestopwithcooldown != null)
                {
                    pokestops.Remove(pokestopwithcooldown);
                }

                var pokestop =
                    pokestops.Where(p => p.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime())
                    .OrderBy(
                        i =>
                        LocationUtils.CalculateDistanceInMeters(Logic._client.CurrentLatitude,
                                                                Logic._client.CurrentLongitude, i.Latitude, i.Longitude)).First();

                var lured    = string.Empty;
                var distance = LocationUtils.CalculateDistanceInMeters(Logic._client.CurrentLatitude, Logic._client.CurrentLongitude, pokestop.Latitude, pokestop.Longitude);
                if (distance > 100)
                {
                    var lurePokestop = pokestops.FirstOrDefault(x => x.LureInfo != null);
                    if (lurePokestop != null)
                    {
                        distance = LocationUtils.CalculateDistanceInMeters(Logic._client.CurrentLatitude, Logic._client.CurrentLongitude, pokestop.Latitude, pokestop.Longitude);
                        if (distance < 200)
                        {
                            lured    = " is Lured";
                            pokestop = lurePokestop;
                        }
                        else
                        {
                            pokestops.Remove(pokestop);
                        }
                    }
                }
                else
                {
                    pokestops.Remove(pokestop);
                }

                var fortInfo = await Logic._client.Fort.GetFort(pokestop.Id, pokestop.Latitude, pokestop.Longitude);

                var latlngDebug = string.Empty;
                if (Logic._client.Settings.DebugMode)
                {
                    latlngDebug = $" | Latitude: {pokestop.Latitude} - Longitude: {pokestop.Longitude}";
                }
                Logger.Write($"Name: {fortInfo.Name} in {distance:0.##} m distance{lured}{latlngDebug}", LogLevel.Pokestop);

                if (Logic._client.Settings.MovementBy == "UseTeleportInsteadOfWalking")
                {
                    await
                    Logic._client.Player.UpdatePlayerLocation(pokestop.Latitude, pokestop.Longitude,
                                                              Logic._client.Settings.DefaultAltitude);

                    await RandomHelper.RandomDelay(500);

                    Logger.Write($"Using Teleport instead of Walking!", LogLevel.Navigation);
                }
                else
                {
                    await
                    Navigation.HumanLikeWalking(new GeoUtils(pokestop.Latitude, pokestop.Longitude),
                                                async() =>
                    {
                        // Catch normal map Pokemon
                        await CatchMapPokemonsTask.Execute();
                        //Catch Incense Pokemon
                        await CatchIncensePokemonsTask.Execute();
                        return(true);
                    });
                }

                //Catch Lure Pokemon
                if (pokestop.LureInfo != null && Logic._client.Settings.CatchLuredPokemon)
                {
                    await CatchLurePokemonsTask.Execute(pokestop);
                }

                var       timesZeroXPawarded = 0;
                var       fortTry            = 0;  //Current check
                const int retryNumber        = 45; //How many times it needs to check to clear softban
                const int zeroCheck          = 5;  //How many times it checks fort before it thinks it's softban
                do
                {
                    var fortSearch = await Logic._client.Fort.SearchFort(pokestop.Id, pokestop.Latitude, pokestop.Longitude);

                    if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0)
                    {
                        timesZeroXPawarded = 0;
                    }
                    if (fortSearch.ExperienceAwarded == 0)
                    {
                        if (fortSearch.Result == FortSearchResponse.Types.Result.InCooldownPeriod)
                        {
                            Logger.Write("Pokestop is on Cooldown", LogLevel.Debug);
                            break;
                        }

                        timesZeroXPawarded++;
                        if (timesZeroXPawarded > zeroCheck)
                        {
                            fortTry += 1;

                            if (Logic._client.Settings.DebugMode)
                            {
                                Logger.Write(
                                    $"Seems your Soft-Banned. Trying to Unban via Pokestop Spins. Retry {fortTry} of {retryNumber - zeroCheck}",
                                    LogLevel.Warning);
                            }

                            await RandomHelper.RandomDelay(450);
                        }
                    }
                    else if (fortSearch.ExperienceAwarded != 0)
                    {
                        BotStats.ExperienceThisSession += fortSearch.ExperienceAwarded;
                        BotStats.UpdateConsoleTitle();
                        Logger.Write($"XP: {fortSearch.ExperienceAwarded}, Gems: {fortSearch.GemsAwarded}, Items: {StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded)}", LogLevel.Pokestop);
                        RecycleItemsTask._recycleCounter++;
                        HatchEggsTask._hatchUpdateDelay++;
                        break;                               //Continue with program as loot was succesfull.
                    }
                } while (fortTry < retryNumber - zeroCheck); //Stop trying if softban is cleaned earlier or if 40 times fort looting failed.

                if (RecycleItemsTask._recycleCounter >= 5)
                {
                    await RecycleItemsTask.Execute();
                }
                if (HatchEggsTask._hatchUpdateDelay >= 15)
                {
                    await HatchEggsTask.Execute();
                }
            }
        }
Example #21
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var pokestopList = await GetPokeStops(session);

            while (pokestopList.Any())
            {
                cancellationToken.ThrowIfCancellationRequested();
                await SnipeMSniperTask.CheckMSniperLocation(session, cancellationToken);

                pokestopList =
                    pokestopList.OrderBy(
                        i =>
                        LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList();

                // randomize next pokestop between first and second by distance
                //var pokestopListNum = 0;
                //if (pokestopList.Count > 1)
                //    pokestopListNum = rc.Next(0, 2);

                //var pokeStop = pokestopList[pokestopListNum];
                //pokestopList.RemoveAt(pokestopListNum);

                var pokeStop = pokestopList[0];
                pokestopList.RemoveAt(0);

                // Fixing the bug where lured Pokemons aren't caught when using GPX
                // Parent FarmPokestopsGPXTask (only) calls
                //        CatchNearbyPokemonsTask.Execute
                //        CatchIncensePokemonsTask.Execute
                //        UseNearbyPokestopsTask.Execute
                // Above happens while moving. Solution: check for lures in this module, and before doing
                // the other actions. The reason behind the bug could be cooldowns caused by the other tasks
                // leading to CatchLurePokemons not taking effect. This solution has been tested and works.
                if (pokeStop.LureInfo != null)
                {
                    await CatchLurePokemonsTask.Execute(session, pokeStop, cancellationToken);
                }

                await FortPokestop(session, cancellationToken, pokeStop);

                if (++stopsHit >= storeRI)     //TODO: OR item/pokemon bag is full //check stopsHit against storeRI random without dividing.
                {
                    storeRI  = rc.Next(6, 12); //set new storeRI for new random value
                    stopsHit = 0;

                    if (session.LogicSettings.UseNearActionRandom)
                    {
                        await HumanRandomActionTask.Execute(session, cancellationToken);
                    }
                    else
                    {
                        await RecycleItemsTask.Execute(session, cancellationToken);

                        if (session.LogicSettings.EvolveAllPokemonWithEnoughCandy ||
                            session.LogicSettings.EvolveAllPokemonAboveIv ||
                            session.LogicSettings.UseLuckyEggsWhileEvolving ||
                            session.LogicSettings.KeepPokemonsThatCanEvolve)
                        {
                            await EvolvePokemonTask.Execute(session, cancellationToken);
                        }
                        if (session.LogicSettings.UseLuckyEggConstantly)
                        {
                            await UseLuckyEggConstantlyTask.Execute(session, cancellationToken);
                        }
                        if (session.LogicSettings.UseIncenseConstantly)
                        {
                            await UseIncenseConstantlyTask.Execute(session, cancellationToken);
                        }
                        if (session.LogicSettings.TransferDuplicatePokemon)
                        {
                            await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                        }
                        if (session.LogicSettings.TransferWeakPokemon)
                        {
                            await TransferWeakPokemonTask.Execute(session, cancellationToken);
                        }
                        if (session.LogicSettings.RenamePokemon)
                        {
                            await RenamePokemonTask.Execute(session, cancellationToken);
                        }
                        if (session.LogicSettings.AutoFavoritePokemon)
                        {
                            await FavoritePokemonTask.Execute(session, cancellationToken);
                        }
                        if (session.LogicSettings.AutomaticallyLevelUpPokemon)
                        {
                            await LevelUpPokemonTask.Execute(session, cancellationToken);
                        }

                        await GetPokeDexCount.Execute(session, cancellationToken);
                    }
                }

                if (session.LogicSettings.SnipeAtPokestops || session.LogicSettings.UseSnipeLocationServer)
                {
                    await SnipePokemonTask.Execute(session, cancellationToken);
                }

                //samuraitruong: temoporary not allow human walk snipe until we implement a good logic to use.
                if (session.LogicSettings.EnableHumanWalkingSnipe && !session.LogicSettings.UseGpxPathing)
                {
                    //refactore to move this code inside the task later.
                    await HumanWalkSnipeTask.Execute(session, cancellationToken,
                                                     async (double lat, double lng) =>
                    {
                        //idea of this function is to spin pokestop on way. maybe risky.
                        var reachablePokestops = pokestopList.Where(i =>
                                                                    LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                                                            session.Client.CurrentLongitude, i.Latitude, i.Longitude) < 30.0)
                                                 .ToList();
                        reachablePokestops = reachablePokestops.OrderBy(i =>
                                                                        LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                                                                session.Client.CurrentLongitude, i.Latitude, i.Longitude))
                                             .ToList();
                        foreach (var ps in reachablePokestops)
                        {
                            pokestopList.Remove(ps);
                            await FortPokestop(session, cancellationToken, ps);
                        }
                    },
                                                     async() =>
                    {
                        var nearestStop = pokestopList.OrderBy(i =>
                                                               LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                                                       session.Client.CurrentLongitude, i.Latitude, i.Longitude)).FirstOrDefault();

                        var walkedDistance = LocationUtils.CalculateDistanceInMeters(nearestStop.Latitude,
                                                                                     nearestStop.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude);
                        if (walkedDistance > session.LogicSettings.HumanWalkingSnipeWalkbackDistanceLimit)
                        {
                            await Task.Delay(3000);
                            var nearbyPokeStops = await UpdateFortsData(session);
                            var notexists       = nearbyPokeStops.Where(p => !pokestopList.Any(x => x.Id == p.Id)).ToList();
                            pokestopList.AddRange(notexists);
                            session.EventDispatcher.Send(new PokeStopListEvent {
                                Forts = pokestopList
                            });
                            session.EventDispatcher.Send(new HumanWalkSnipeEvent()
                            {
                                Type           = HumanWalkSnipeEventTypes.PokestopUpdated,
                                Pokestops      = notexists,
                                NearestDistane = walkedDistance
                            });
                        }
                    }
                                                     );
                }
            }
        }
Example #22
0
        private static void ExecuteSwitcher(ISession session, EncounteredEvent encounterEV, string cacheKey)
        {
            //if distance is very far. that is snip pokemon
            var accountManager = TinyIoCContainer.Current.Resolve <MultiAccountManager>();

            var curentkey = session.Settings.AuthType == AuthType.Google
                  ? session.Settings.GoogleUsername
                  : session.Settings.PtcUsername;

            curentkey += encounterEV.EncounterId;
            session.Cache.Add(curentkey, encounterEV, DateTime.Now.AddMinutes(15));

            var evalNextBot = accountManager.FindAvailableAccountForPokemonSwitch(encounterEV.EncounterId);

            if (evalNextBot == null)
            {
                return;
            }
            if (session.Stats.IsSnipping
                //assume that all pokemon catch from 250+m is snipe
                || LocationUtils.CalculateDistanceInMeters(
                    encounterEV.Latitude,
                    encounterEV.Longitude,
                    session.Client.CurrentLatitude,
                    session.Client.CurrentLongitude
                    ) > 1000)
            {
                var snipePokemonFiler = session.LogicSettings.PokemonSnipeFilters.GetFilter <SnipeFilter>(encounterEV.PokemonId);

                if (session.LogicSettings.PokemonSnipeFilters.ContainsKey(encounterEV.PokemonId))
                {
                    var filter = session.LogicSettings.PokemonSnipeFilters[encounterEV.PokemonId];
                    if (session.LogicSettings.AllowMultipleBot &&
                        filter.AllowMultiAccountSnipe &&
                        filter.IsMatch(encounterEV.IV,
                                       (PokemonMove)Enum.Parse(typeof(PokemonMove), encounterEV.Move1),
                                       (PokemonMove)Enum.Parse(typeof(PokemonMove), encounterEV.Move2),
                                       encounterEV.Level, true))
                    {
                        //thow
                        throw new ActiveSwitchByPokemonException()
                              {
                                  EncounterData          = encounterEV,
                                  LastLatitude           = encounterEV.Latitude,
                                  LastLongitude          = encounterEV.Longitude,
                                  LastEncounterPokemonId = encounterEV.PokemonId,
                                  Snipe = true,
                                  Bot   = evalNextBot
                              };
                    }
                }

                return;
            }

            if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings) &&
                session.LogicSettings.MultipleBotConfig.OnRarePokemon &&
                (
                    session.LogicSettings.MultipleBotConfig.MinIVToSwitch < encounterEV.IV ||
                    (
                        session.LogicSettings.BotSwitchPokemonFilters.ContainsKey(encounterEV.PokemonId) &&
                        (
                            session.LogicSettings.BotSwitchPokemonFilters[encounterEV.PokemonId].IV < encounterEV.IV ||
                            (session.LogicSettings.BotSwitchPokemonFilters[encounterEV.PokemonId].LV > 0 && session
                             .LogicSettings.BotSwitchPokemonFilters[encounterEV.PokemonId]
                             .LV < encounterEV.Level)
                        )
                    )
                ))
            {
                if (evalNextBot != null)
                {
                    //cancel all running task.
                    session.CancellationTokenSource.Cancel();
                    throw new ActiveSwitchByPokemonException()
                          {
                              LastLatitude           = encounterEV.Latitude,
                              LastLongitude          = encounterEV.Longitude,
                              LastEncounterPokemonId = encounterEV.PokemonId,
                              Bot = evalNextBot
                          };
                }
            }
        }
Example #23
0
        private async Task ExecuteFarmingPokestopsAndPokemons(Client client)
        {
            var distanceFromStart = LocationUtils.CalculateDistanceInMeters(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude, _client.CurrentLat, _client.CurrentLng);

            if (_clientSettings.MaxWalkingRadiusInMeters != 0 && distanceFromStart > _clientSettings.MaxWalkingRadiusInMeters)
            {
                Logger.ColoredConsoleWrite(ConsoleColor.Green, "Youre outside of the defined Max Walking Radius. Walking back!");
                var update = await _navigation.HumanLikeWalking(new GeoCoordinate(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons);

                var start = await _navigation.HumanLikeWalking(new GeoCoordinate(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons);
            }

            Resources.OutPutWalking = true;
            var mapObjects = await _client.GetMapObjects();

            //var pokeStops = mapObjects.MapCells.SelectMany(i => i.Forts).Where(i => i.Type == FortType.Checkpoint && i.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime());

            var pokeStops =
                _navigation.pathByNearestNeighbour(
                    mapObjects.MapCells.SelectMany(i => i.Forts)
                    .Where(
                        i =>
                        i.Type == FortType.Checkpoint &&
                        i.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime())
                    .OrderBy(
                        i =>
                        LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, i.Latitude, i.Longitude)).ToArray(), _clientSettings.WalkingSpeedInKilometerPerHour);


            if (_clientSettings.MaxWalkingRadiusInMeters != 0)
            {
                pokeStops = pokeStops.Where(i => LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, i.Latitude, i.Longitude) <= _clientSettings.MaxWalkingRadiusInMeters).ToArray();
                if (pokeStops.Count() == 0)
                {
                    Logger.ColoredConsoleWrite(ConsoleColor.Red, "We cant find any PokeStops in a range of " + _clientSettings.MaxWalkingRadiusInMeters + "m!");
                    await ExecuteCatchAllNearbyPokemons();
                }
            }


            if (pokeStops.Count() == 0)
            {
                Logger.ColoredConsoleWrite(ConsoleColor.Red, "We cant find any PokeStops, which are unused! Probably Server unstable, or you visted them all. Retrying..");
                await ExecuteCatchAllNearbyPokemons();
            }
            else
            {
                Logger.ColoredConsoleWrite(ConsoleColor.Yellow, "We found " + pokeStops.Count() + " PokeStops near.");
            }

            foreach (var pokeStop in pokeStops)
            {
                // replace this true with settings variable!!
                await UseIncense();
                await ExecuteCatchAllNearbyPokemons();

                if (count >= 3)
                {
                    count = 0;
                    await StatsLog(client);

                    if (_clientSettings.EvolvePokemonsIfEnoughCandy)
                    {
                        await EvolveAllPokemonWithEnoughCandy();
                    }
                    await TransferDuplicatePokemon(_clientSettings.keepPokemonsThatCanEvolve);
                    await RecycleItems();
                }
                if (_clientSettings.pokevision)
                {
                    foreach (spottedPoke p in await _pokevision.GetNearPokemons(_client.CurrentLat, _client.CurrentLng))
                    {
                        var dist = LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, p._lat, p._lng);
                        Logger.ColoredConsoleWrite(ConsoleColor.Magenta, $"PokeVision: A {StringUtils.getPokemonNameByLanguage(_clientSettings, p._pokeId)} in {dist:0.##}m distance. Trying to catch.");
                        var upd = await _navigation.HumanLikeWalking(new GeoCoordinate(p._lat, p._lng), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons);
                    }
                }

                var distance = LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, pokeStop.Latitude, pokeStop.Longitude);
                var fortInfo = await _client.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                if (fortInfo == null)
                {
                    continue;
                }
                Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Next Pokestop: {fortInfo.Name} in {distance:0.##}m distance.");
                var update = await _navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons);

                ////var fortInfo = await client.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);
                var fortSearch = await _client.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                count++;

                if (fortSearch.ExperienceAwarded > 0)
                {
                    failed_softban = 0;
                    _botStats.addExperience(fortSearch.ExperienceAwarded);
                    var egg = "";
                    if (fortSearch.PokemonDataEgg != null)
                    {
                        egg = "Egg " + fortSearch.PokemonDataEgg.EggKmWalkedTarget;
                    }
                    else
                    {
                        egg = "/";
                    }

                    var i = "";
                    if (StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded) != "")
                    {
                        i = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded);
                    }
                    else
                    {
                        i = "/";
                    }

                    Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Farmed XP: {fortSearch.ExperienceAwarded}, Gems: { fortSearch.GemsAwarded}, Eggs: {egg} Items: {i}", LogLevel.Info);
                }
                else
                {
                    failed_softban++;
                    if (failed_softban >= 6)
                    {
                        Logger.Error("Detected a Softban. Trying to use our Special 1337 Unban Methode.");
                        for (int i = 0; i < 60; i++)
                        {
                            var unban = await client.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                            if (unban.ExperienceAwarded > 0)
                            {
                                break;
                            }
                        }
                        failed_softban = 0;
                        Logger.ColoredConsoleWrite(ConsoleColor.Green, "Probably unbanned you.");
                    }
                }

                await RandomHelper.RandomDelay(50, 200);
            }
            if (_clientSettings.WalkBackToDefaultLocation)
            {
                Logger.ColoredConsoleWrite(ConsoleColor.Green, "Walking back to Default Location.");
                await _navigation.HumanLikeWalking(new GeoCoordinate(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons);
            }
        }
Example #24
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)
        {
            TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
            // 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 (session.Stats.CatchThresholdExceeds(session))
            {
                if (session.LogicSettings.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())
                {
                    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 = 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(),
                };

                //add catch to avoid snipe duplicate
                string uniqueCacheKey =
                    $"{session.Settings.PtcUsername}{session.Settings.GoogleUsername}{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.MaxPokeballsPerPokemon > 0 &&
                         attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon))
                    {
                        break;
                    }

                    pokeball = 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 (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);
                    }

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


                    await session.Inventory.UpdateInventoryItem(pokeball);

                    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)
                    {
                        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    = session.Inventory.GetCandyFamily(pokemon.PokemonId);

                        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();

                    evt.BallAmount = 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 (session.LogicSettings.AllowMultipleBot)
                {
                    if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchFlee)
                    {
                        CatchFleeContinuouslyCount++;
                        if (CatchFleeContinuouslyCount > session.LogicSettings.MultipleBotConfig.CatchFleeCount &&
                            TinyIoCContainer.Current.Resolve <MultiAccountManager>().AllowSwitch())
                        {
                            CatchFleeContinuouslyCount = 0;

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

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

                if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings))
                {
                    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);
                    }
                    else
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                    }
                }
            }
            return(true);
        }
Example #25
0
 public override double CalculateDistance(double sourceLat, double sourceLng, double destinationLat,
                                          double destinationLng, ISession session = null)
 {
     return(LocationUtils.CalculateDistanceInMeters(sourceLat, sourceLng, destinationLat, destinationLng));
 }
Example #26
0
        public static async Task Execute(ISession session, FortData currentFortData,
                                         CancellationToken cancellationToken)
        {
            TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
            cancellationToken.ThrowIfCancellationRequested();
            if (!session.LogicSettings.CatchPokemon ||
                session.CatchBlockTime > DateTime.Now)
            {
                return;
            }

            if (session.KnownLongitudeBeforeSnipe != 0 && session.KnownLatitudeBeforeSnipe != 0 &&
                LocationUtils.CalculateDistanceInMeters(session.KnownLatitudeBeforeSnipe,
                                                        session.KnownLongitudeBeforeSnipe,
                                                        session.Client.CurrentLatitude,
                                                        session.Client.CurrentLongitude) > 1000)
            {
                Logger.Write($"ERROR - Bot stucked at snipe location({session.Client.CurrentLatitude},{session.Client.CurrentLongitude}). Teleport him back home - if you see this message please PM samuraitruong");

                session.Client.Player.SetCoordinates(session.KnownLatitudeBeforeSnipe, session.KnownLongitudeBeforeSnipe, session.Client.CurrentAltitude);
                return;
            }


            Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForLurePokemon), LogLevel.Debug);

            var fortId = currentFortData.Id;

            var pokemonId = currentFortData.LureInfo.ActivePokemonId;

            if ((session.LogicSettings.UsePokemonToNotCatchFilter &&
                 session.LogicSettings.PokemonsNotToCatch.Contains(pokemonId)))
            {
                session.EventDispatcher.Send(new NoticeEvent
                {
                    Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped, pokemonId)
                });
            }
            else
            {
                var encounterId = currentFortData.LureInfo.EncounterId;
                if (session.Cache.Get(currentFortData.LureInfo.EncounterId.ToString()) != null)
                {
                    return; //pokemon been ignore before
                }
                var encounter = await session.Client.Encounter.EncounterLurePokemon(encounterId, fortId);

                if (encounter.Result == DiskEncounterResponse.Types.Result.Success &&
                    session.LogicSettings.CatchPokemon)
                {
                    var pokemon = new MapPokemon
                    {
                        EncounterId           = encounterId,
                        ExpirationTimestampMs = currentFortData.LureInfo.LureExpiresTimestampMs,
                        Latitude     = currentFortData.Latitude,
                        Longitude    = currentFortData.Longitude,
                        PokemonId    = currentFortData.LureInfo.ActivePokemonId,
                        SpawnPointId = currentFortData.Id
                    };

                    //add delegate function
                    OnPokemonEncounterEvent(new List <MapPokemon> {
                        pokemon
                    });

                    // Catch the Pokemon
                    await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon,
                                                   currentFortData, sessionAllowTransfer : true);
                }
                else if (encounter.Result == DiskEncounterResponse.Types.Result.PokemonInventoryFull)
                {
                    if (session.LogicSettings.TransferDuplicatePokemon || session.LogicSettings.TransferWeakPokemon)
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring)
                        });
                        if (session.LogicSettings.TransferDuplicatePokemon)
                        {
                            await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                        }
                        if (session.LogicSettings.TransferWeakPokemon)
                        {
                            await TransferWeakPokemonTask.Execute(session, cancellationToken);
                        }
                        if (session.LogicSettings.EvolveAllPokemonAboveIv ||
                            session.LogicSettings.EvolveAllPokemonWithEnoughCandy ||
                            session.LogicSettings.UseLuckyEggsWhileEvolving ||
                            session.LogicSettings.KeepPokemonsThatCanEvolve)
                        {
                            await EvolvePokemonTask.Execute(session, cancellationToken);
                        }
                    }
                    else
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually)
                        });
                    }
                }
                else
                {
                    if (encounter.Result.ToString().Contains("NotAvailable"))
                    {
                        return;
                    }
                    session.EventDispatcher.Send(new WarnEvent
                    {
                        Message =
                            session.Translation.GetTranslation(TranslationString.EncounterProblemLurePokemon,
                                                               encounter.Result)
                    });
                }
            }
        }
        public static async Task Execute(ISession session, CancellationToken cancellationToken, Func <double, double, Task> actionWhenWalking = null, Func <Task> afterCatchFunc = null)
        {
            pokestopCount++;
            pokestopCount = pokestopCount % 3;

            if (pokestopCount > 0 && !prioritySnipeFlag)
            {
                return;
            }

            InitSession(session);
            if (!_setting.CatchPokemon && !prioritySnipeFlag)
            {
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (_setting.HumanWalkingSnipeTryCatchEmAll)
            {
                var checkBall = await CheckPokeballsToSnipe(_setting.HumanWalkingSnipeCatchEmAllMinBalls, session, cancellationToken);

                if (!checkBall && !prioritySnipeFlag)
                {
                    return;
                }
            }

            bool             caughtAnyPokemonInThisWalk = false;
            SnipePokemonInfo pokemon = null;

            do
            {
                prioritySnipeFlag = false;
                pokemon           = GetNextSnipeablePokemon(session.Client.CurrentLatitude, session.Client.CurrentLongitude, !caughtAnyPokemonInThisWalk);
                if (pokemon != null)
                {
                    caughtAnyPokemonInThisWalk = true;
                    CalculateDistanceAndEstTime(pokemon);
                    var    remainTimes         = (pokemon.ExpiredTime - DateTime.Now).TotalSeconds * 0.95; //just use 90% times
                    var    catchPokemonTimeEST = (pokemon.Distance / 100) * 10;                            //assume that 100m we catch 1 pokemon and it took 10 second for each.
                    string strPokemon          = session.Translation.GetPokemonTranslation(pokemon.PokemonId);
                    var    spinPokestopEST     = (pokemon.Distance / 100) * 5;

                    bool catchPokemon = (pokemon.EstimatedTime + catchPokemonTimeEST) < remainTimes && pokemon.Setting.CatchPokemonWhileWalking;
                    bool spinPokestop = pokemon.Setting.SpinPokestopWhileWalking && (pokemon.EstimatedTime + catchPokemonTimeEST + spinPokestopEST) < remainTimes;
                    pokemon.IsCatching = true;
                    session.EventDispatcher.Send(new HumanWalkSnipeEvent()
                    {
                        PokemonId        = pokemon.PokemonId,
                        Latitude         = pokemon.Latitude,
                        Longitude        = pokemon.Longitude,
                        Distance         = pokemon.Distance,
                        Expires          = (pokemon.ExpiredTime - DateTime.Now).TotalSeconds,
                        Estimate         = (int)pokemon.EstimatedTime,
                        Setting          = pokemon.Setting,
                        CatchPokemon     = catchPokemon,
                        Pokemons         = ApplyFilter(rarePokemons),
                        SpinPokeStop     = pokemon.Setting.SpinPokestopWhileWalking,
                        WalkSpeedApplied = pokemon.Setting.AllowSpeedUp ? pokemon.Setting.MaxSpeedUpSpeed : _session.LogicSettings.WalkingSpeedInKilometerPerHour,
                        Type             = HumanWalkSnipeEventTypes.StartWalking,
                        Rarity           = PokemonGradeHelper.GetPokemonGrade(pokemon.PokemonId).ToString()
                    });

                    await session.Navigation.Move(new GeoCoordinate(pokemon.Latitude, pokemon.Longitude,
                                                                    LocationUtils.getElevation(session, pokemon.Latitude, pokemon.Longitude)),
                                                  async() =>
                    {
                        var distance = LocationUtils.CalculateDistanceInMeters(pokemon.Latitude, pokemon.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude);

                        if (catchPokemon && distance > 100.0)
                        {
                            // Catch normal map Pokemon
                            await CatchNearbyPokemonsTask.Execute(session, cancellationToken, sessionAllowTransfer: false);
                        }
                        if (actionWhenWalking != null && spinPokestop)
                        {
                            await actionWhenWalking(session.Client.CurrentLatitude, session.Client.CurrentLongitude);
                        }
                        return(true);
                    },
                                                  session,
                                                  cancellationToken, pokemon.Setting.AllowSpeedUp?pokemon.Setting.MaxSpeedUpSpeed : 0);

                    session.EventDispatcher.Send(new HumanWalkSnipeEvent()
                    {
                        Latitude      = pokemon.Latitude,
                        Longitude     = pokemon.Longitude,
                        PauseDuration = pokemon.Setting.DelayTimeAtDestination / 1000,
                        Type          = HumanWalkSnipeEventTypes.DestinationReached,
                        UniqueId      = pokemon.UniqueId
                    });
                    //await CatchNearbyPokemonsTask.Execute(session, cancellationToken, pokemon.PokemonId,false);
                    //await CatchIncensePokemonsTask.Execute(session, cancellationToken);

                    await Task.Delay(pokemon.Setting.DelayTimeAtDestination);

                    // if (!pokemon.IsVisited)
                    {
                        await CatchNearbyPokemonsTask.Execute(session, cancellationToken, pokemon.PokemonId, false);

                        await CatchIncensePokemonsTask.Execute(session, cancellationToken);
                    }
                    pokemon.IsVisited  = true;
                    pokemon.IsCatching = false;
                }
            }while (pokemon != null && _setting.HumanWalkingSnipeTryCatchEmAll);

            if (caughtAnyPokemonInThisWalk && !_setting.HumanWalkingSnipeAlwaysWalkBack)
            {
                await afterCatchFunc?.Invoke();
            }
        }
Example #28
0
        public static StartGymBattleResponse StartGymBattle(Client client, string gymId, ulong defendingPokemonId,
                                                            IEnumerable <ulong> attackingPokemonIds)
        {
            StartGymBattleResponse resp = null;
            var numTries = 3;
            var startOk  = false;

            do
            {
                try {
                    resp = client.Fort.StartGymBattle(gymId, defendingPokemonId, attackingPokemonIds).Result;
                    if (resp == null)
                    {
                        Logger.Debug("(Gym) - Response to start battle was null.");
                    }
                    else
                    {
                        if (resp.BattleLog == null)
                        {
                            Logger.Debug("(Gym) - BatlleLog to start battle was null");
                        }
                        else
                        {
                            startOk = true;
                            Logger.Debug("StartGymBattle Response:" + resp);
                        }
                    }
                } catch (Exception ex1) {
                    Logger.ExceptionInfo("StartGymBattle: " + ex1);
                    RandomHelper.RandomSleep(5000);
                    if (GlobalVars.Gyms.Testing == "Relogin")
                    {
                        client.Login.DoLogin().Wait();
                    }
                    else if (GlobalVars.Gyms.Testing == "GetPlayer")
                    {
                        client.Player.GetPlayer();
                        RandomHelper.RandomSleep(3000);
                    }
                    else if (GlobalVars.Gyms.Testing == "Wait 2 minutes catching pokemons")
                    {
                        if (GlobalVars.CatchPokemon)
                        {
                            Logger.Info("Trying to catch pokemons until next attack");
                        }
                        // 0.00001 = 1 meters
                        // http://www.um.es/geograf/sigmur/temariohtml/node6_mn.html
                        //http://gizmodo.com/how-precise-is-one-degree-of-longitude-or-latitude-1631241162
                        var gymloc = new GeoCoordinate(client.CurrentLongitude, client.CurrentLatitude, client.CurrentAltitude);
                        for (var times = 1; times < 5; times++)
                        {
                            var rnd = RandomHelper.GetLongRandom(8, 9) * 0.00001;
                            Logger.Debug("going to 8 meters far of gym");
                            LocationUtils.updatePlayerLocation(client, gymloc.Longitude + rnd, gymloc.Latitude, gymloc.Altitude);
                            RandomHelper.RandomSleep(10000);
                            CatchingLogic.Execute();
                            rnd = RandomHelper.GetLongRandom(8, 9) * 0.00001;
                            Logger.Debug("going to 8 meters far of gym");
                            LocationUtils.updatePlayerLocation(client, gymloc.Longitude + rnd, gymloc.Latitude, gymloc.Altitude);
                            RandomHelper.RandomSleep(10000);
                            CatchingLogic.Execute();
                            Logger.Debug("returning to gym location");
                            // go back
                            LocationUtils.updatePlayerLocation(client, gymloc.Longitude, gymloc.Latitude, gymloc.Altitude);
                            RandomHelper.RandomSleep(10000);
                            CatchingLogic.Execute();
                        }
                        RandomHelper.RandomSleep(2000);
                    }
                    else
                    {
                        RandomHelper.RandomSleep(115000);
                        client.Login.DoLogin().Wait();
                    }
                }
                numTries--;
            } while (!startOk && numTries > 0);
            return(resp);
        }
Example #29
0
 public FortData[] pathByNearestNeighbour(FortData[] pokeStops, double walkingSpeedInKilometersPerHour)
 {
     ////Start Gen. alg.
     //if (pokeStops.Length > 15)
     //{
     //    //Config
     //    int ITERATIONS = 100000;
     //    int POPSIZE = pokeStops.Length * 60;
     //    double CROSSPROP = 99;
     //    double MUTPROP = 20;
     //    List<List<int>> population = new List<List<int>>();
     //    Random rnd = new Random();
     //    //Create Population
     //    for (var i = POPSIZE; i > 0; --i)
     //    {
     //        List<int> tempChromosome = new List<int>();
     //        int items = rnd.Next(2, pokeStops.Length * 3 / 4);
     //        do
     //        {
     //            int tempIndex = rnd.Next(0, pokeStops.Length - 1);
     //            //Add only if new Index
     //            while (tempChromosome.Exists(x => x == tempIndex))
     //            {
     //                tempIndex = rnd.Next(0, pokeStops.Length - 1);
     //            }
     //            tempChromosome.Add(tempIndex);
     //        } while (--items > 0);
     //        if (calcFitness(ref pokeStops, tempChromosome, walkingSpeedInKilometersPerHour) > 0.0)
     //        {
     //            tempChromosome.Add(tempChromosome[0]);
     //            population.Add(tempChromosome);
     //        }
     //    }
     //    if (population.Count > 10)
     //    {
     //        for (int i = 0; i < ITERATIONS; ++i)
     //        {
     //            //Selection
     //            var parents = selection(pokeStops, population, walkingSpeedInKilometersPerHour);
     //            List<int> child1 = parents[0], child2 = parents[1];
     //            //Crossing
     //            if (rnd.Next(0, 100) < CROSSPROP)
     //            {
     //                child1 = calcCrossing(parents[0], parents[1]);
     //                child2 = calcCrossing(parents[1], parents[0]);
     //            }
     //            //Mutation
     //            if (rnd.Next(0, 100) < MUTPROP)
     //            {
     //                mutate(ref child1);
     //            }
     //            if (rnd.Next(0, 100) < MUTPROP)
     //            {
     //                mutate(ref child2);
     //            }
     //            //Replace
     //            List<int> fittnes = new List<int>();
     //            int sumPop = 0;
     //            for (int c = 0; c < population.Count; ++c)
     //            {
     //                var temp = calcFitness(ref pokeStops, population[c], walkingSpeedInKilometersPerHour);
     //                sumPop += temp;
     //                fittnes.Add(temp);
     //            }
     //            List<int> fittnesSorted = new List<int>(fittnes);
     //            fittnesSorted.Sort();
     //            if (fittnesSorted[0] <= calcFitness(ref pokeStops, child1, walkingSpeedInKilometersPerHour))
     //            {
     //                var tempSelcetedChr = fittnes.FindIndex(x => x == fittnesSorted[0]);
     //                population[tempSelcetedChr] = child1;
     //            }
     //            if (fittnesSorted[1] <= calcFitness(ref pokeStops, child2, walkingSpeedInKilometersPerHour))
     //            {
     //                var tempSelcetedChr = fittnes.FindIndex(x => x == fittnesSorted[1]);
     //                population[tempSelcetedChr] = child2;
     //            }
     //            //get best Generation
     //            List<int> fittnes2 = new List<int>();
     //            for (int c = 0; c < population.Count; ++c)
     //            {
     //                var temp = calcFitness(ref pokeStops, population[c], walkingSpeedInKilometersPerHour);
     //                fittnes2.Add(temp);
     //            }
     //            List<int> fittnesSorted2 = new List<int>(fittnes2);
     //            fittnesSorted2.Sort();
     //            var tempSelcetedChr2 = fittnes2.FindIndex(x => x == fittnesSorted2[fittnesSorted2.Count - 1]);
     //            List<FortData> newPokeStops = new List<FortData>();
     //            foreach (var element in population[tempSelcetedChr2])
     //            {
     //                newPokeStops.Add(pokeStops[element]);
     //            }
     //            Logger.ColoredConsoleWrite(ConsoleColor.Yellow, $"{Math.Round(newPokeStops.Count * 3600 / calcTime(ref pokeStops, population[tempSelcetedChr2], walkingSpeedInKilometersPerHour))} PokeStops per Hour.");
     //            return newPokeStops.ToArray();
     //        }
     //    }
     //}
     //End gen. alg
     //Normal calculation
     for (var i = 1; i < pokeStops.Length - 1; i++)
     {
         var closest    = i + 1;
         var cloestDist = LocationUtils.CalculateDistanceInMeters(pokeStops[i].Latitude, pokeStops[i].Longitude, pokeStops[closest].Latitude, pokeStops[closest].Longitude);
         for (var j = closest; j < pokeStops.Length; j++)
         {
             var initialDist = cloestDist;
             var newDist     = LocationUtils.CalculateDistanceInMeters(pokeStops[i].Latitude, pokeStops[i].Longitude, pokeStops[j].Latitude, pokeStops[j].Longitude);
             if (initialDist > newDist)
             {
                 cloestDist = newDist;
                 closest    = j;
             }
         }
         var tmpPok = pokeStops[closest];
         pokeStops[closest] = pokeStops[i + 1];
         pokeStops[i + 1]   = tmpPok;
     }
     return(pokeStops);
 }
Example #30
0
        public async Task <PlayerUpdateResponse> Move(GeoCoordinate targetLocation, Func <Task <bool> > functionExecutedWhileWalking,
                                                      ISession session,
                                                      CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (!session.LogicSettings.DisableHumanWalking)
            {
                PlayerUpdateResponse result = null;
                List <GeoCoordinate> points = new List <GeoCoordinate>();
                var route = Route(session,
                                  new GeoCoordinate(
                                      _client.CurrentLatitude,
                                      _client.CurrentLongitude,
                                      _client.CurrentAltitude),
                                  targetLocation);

                foreach (var item in route)
                {
                    points.Add(new GeoCoordinate(item.ToArray()[1], item.ToArray()[0]));
                }

                for (int i = 0; i < points.Count; i++)
                {
                    var speedInMetersPerSecond = session.LogicSettings.UseWalkingSpeedVariant ? MajorWalkingSpeedVariant(session) :
                                                 session.LogicSettings.WalkingSpeedInKilometerPerHour / 3.6;
                    var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);

                    var nextWaypointBearing  = LocationUtils.DegreeBearing(sourceLocation, points.ToArray()[i]);
                    var nextWaypointDistance = speedInMetersPerSecond;
                    var waypoint             = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing);

                    var requestSendDateTime = DateTime.Now;
                    result =
                        await
                        _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude,
                                                            waypoint.Altitude);

                    UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude);

                    var realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation);
                    if (realDistanceToTarget < 30)
                    {
                        break;
                    }

                    do
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        var millisecondsUntilGetUpdatePlayerLocationResponse =
                            (DateTime.Now - requestSendDateTime).TotalMilliseconds;

                        sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
                        var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, points.ToArray()[i]);

                        var realDistanceToTargetSpeedDown = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation);
                        if (realDistanceToTargetSpeedDown < 40)
                        {
                            if (speedInMetersPerSecond > SpeedDownTo)
                            {
                                speedInMetersPerSecond = SpeedDownTo;
                            }
                        }

                        if (session.LogicSettings.UseWalkingSpeedVariant)
                        {
                            speedInMetersPerSecond = MinorWalkingSpeedVariant(session);
                        }

                        nextWaypointDistance = Math.Min(currentDistanceToTarget,
                                                        millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond);
                        nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, points.ToArray()[i]);
                        waypoint            = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing);

                        requestSendDateTime = DateTime.Now;
                        result =
                            await
                            _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude,
                                                                waypoint.Altitude);

                        UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude);

                        if (functionExecutedWhileWalking != null)
                        {
                            await functionExecutedWhileWalking(); // look for pokemon
                        }
                    } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, points.ToArray()[i]) >= 2);

                    UpdatePositionEvent?.Invoke(points.ToArray()[i].Latitude, points.ToArray()[i].Longitude);
                }

                return(result);
            }

            var curLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
            var dist        = LocationUtils.CalculateDistanceInMeters(curLocation, targetLocation);

            if (dist >= 100)
            {
                var nextWaypointDistance = dist * 70 / 100;
                var nextWaypointBearing  = LocationUtils.DegreeBearing(curLocation, targetLocation);

                var waypoint = LocationUtils.CreateWaypoint(curLocation, nextWaypointDistance, nextWaypointBearing);
                var sentTime = DateTime.Now;

                var result =
                    await
                    _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude,
                                                        waypoint.Altitude);

                UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude);

                do
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var millisecondsUntilGetUpdatePlayerLocationResponse =
                        (DateTime.Now - sentTime).TotalMilliseconds;

                    curLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
                    var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(curLocation, targetLocation);

                    dist = LocationUtils.CalculateDistanceInMeters(curLocation, targetLocation);

                    if (dist >= 100)
                    {
                        nextWaypointDistance = dist * 70 / 100;
                    }
                    else
                    {
                        nextWaypointDistance = dist;
                    }

                    nextWaypointBearing = LocationUtils.DegreeBearing(curLocation, targetLocation);
                    waypoint            = LocationUtils.CreateWaypoint(curLocation, nextWaypointDistance, nextWaypointBearing);
                    sentTime            = DateTime.Now;
                    result =
                        await
                        _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude,
                                                            waypoint.Altitude);

                    UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude);


                    if (functionExecutedWhileWalking != null)
                    {
                        await functionExecutedWhileWalking(); // look for pokemon
                    }
                } while (LocationUtils.CalculateDistanceInMeters(curLocation, targetLocation) >= 10);
                return(result);
            }
            else
            {
                var result =
                    await
                    _client.Player.UpdatePlayerLocation(targetLocation.Latitude, targetLocation.Longitude,
                                                        LocationUtils.getElevation(targetLocation.Latitude, targetLocation.Longitude));

                UpdatePositionEvent?.Invoke(targetLocation.Latitude, targetLocation.Longitude);
                if (functionExecutedWhileWalking != null)
                {
                    await functionExecutedWhileWalking(); // look for pokemon
                }
                return(result);
            }
        }