public static async Task Execute(ISession session, CancellationToken cancellationToken) { if (!CheckSnipeConditions(session)) { return; } inProgress = true; double originalLatitude = session.Client.CurrentLatitude; double originalLongitude = session.Client.CurrentLongitude; session.KnownLatitudeBeforeSnipe = originalLatitude; session.KnownLongitudeBeforeSnipe = originalLongitude; //Logger.Write($"DEBUG : Location before snipe : {originalLatitude},{originalLongitude}"); var pth = Path.Combine(Directory.GetCurrentDirectory(), "SnipeMS.json"); try { if (OutOffBallBlock > DateTime.Now || ( File.Exists(pth) && autoSnipePokemons.Count == 0 && manualSnipePokemons.Count == 0 && pokedexSnipePokemons.Count == 0)) { return; } if (autoSnipePokemons.Count > 0 && !(await CheckPokeballsToSnipe( session.LogicSettings.MinPokeballsToSnipe + 1, session, cancellationToken).ConfigureAwait(false))) { session.EventDispatcher.Send(new WarnEvent() { Message = session.Translation.GetTranslation(TranslationString.AutoSnipeDisabled, session.LogicSettings.SnipePauseOnOutOfBallTime) }); OutOffBallBlock = DateTime.Now.AddMinutes(session.LogicSettings.SnipePauseOnOutOfBallTime); return; } List <MSniperInfo2> mSniperLocation2 = new List <MSniperInfo2>(); if (File.Exists(pth)) { var sr = new StreamReader(pth, Encoding.UTF8); var jsn = sr.ReadToEnd(); sr.Close(); mSniperLocation2 = JsonConvert.DeserializeObject <List <MSniperInfo2> >(jsn); File.Delete(pth); if (mSniperLocation2 == null) { mSniperLocation2 = new List <MSniperInfo2>(); } } using (await locker.LockAsync().ConfigureAwait(false)) { if (pokedexSnipePokemons.Count > 0) { mSniperLocation2.Add(pokedexSnipePokemons.OrderByDescending(x => x.PokemonId).FirstOrDefault()); pokedexSnipePokemons.Clear(); } if (manualSnipePokemons.Count > 0) { mSniperLocation2.AddRange(manualSnipePokemons); manualSnipePokemons.Clear(); } else { autoSnipePokemons.RemoveAll(x => x.AddedTime.AddSeconds(SNIPE_SAFE_TIME) < DateTime.Now); // || ( x.ExpiredTime >0 && x.ExpiredTime < DateTime.Now.ToUnixTime())); autoSnipePokemons.OrderBy(x => x.Priority) .ThenByDescending(x => PokemonGradeHelper.GetPokemonGrade((PokemonId)x.PokemonId)) .ThenByDescending(x => x.Iv) .ThenByDescending(x => x.PokemonId) .ThenByDescending(x => x.AddedTime); var batch = autoSnipePokemons.Take(session.LogicSettings.AutoSnipeBatchSize); if (batch != null && batch.Count() > 0) { mSniperLocation2.AddRange(batch); autoSnipePokemons.RemoveAll(x => batch.Contains(x)); } } } foreach (var location in mSniperLocation2) { if (session.Stats.CatchThresholdExceeds(session) || isBlocking) { break; } using (await locker.LockAsync().ConfigureAwait(false)) { if (location.EncounterId > 0 && expiredCache.Get(location.EncounterId.ToString()) != null) { continue; } if (pokedexSnipePokemons.Count > 0 || manualSnipePokemons.Count > 0) { break; //should return item back to snipe list } } session.EventDispatcher.Send(new SnipePokemonStarted(location)); if (location.EncounterId > 0 && session.Cache[CatchPokemonTask.GetEncounterCacheKey(location.EncounterId)] != null) { continue; } if (!(await CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsWhileSnipe + 1, session, cancellationToken).ConfigureAwait(false))) { session.EventDispatcher.Send(new WarnEvent() { Message = session.Translation.GetTranslation(TranslationString.AutoSnipeDisabled) }); OutOffBallBlock = DateTime.Now.AddMinutes(session.LogicSettings.SnipePauseOnOutOfBallTime); break; } if (location.AddedTime.AddSeconds(SNIPE_SAFE_TIME) < DateTime.Now) { continue; } //If bot already catch the same pokemon, and very close this location. if (session.Cache.Get(CatchPokemonTask.GetUsernameGeoLocationCacheKey(session.Settings.Username, (PokemonId)location.PokemonId, location.Latitude, location.Longitude)) != null) { continue; } session.Cache.Add(CatchPokemonTask.GetEncounterCacheKey(location.EncounterId), true, DateTime.Now.AddMinutes(15)); cancellationToken.ThrowIfCancellationRequested(); TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); session.EventDispatcher.Send(new SnipeScanEvent { Bounds = new Location(location.Latitude, location.Longitude), PokemonId = (PokemonId)location.PokemonId, Source = "InternalSnipe", Iv = location.Iv }); session.Stats.IsSnipping = true; var result = await CatchWithSnipe(session, location, cancellationToken).ConfigureAwait(false); if (result) { snipeFailedCount = 0; } else { snipeFailedCount++; if (snipeFailedCount >= 3) { break; //maybe softban, stop snipe wait until verify it not been } } //await Task.Delay(1000, cancellationToken).ConfigureAwait(false); session.Stats.LastSnipeTime = DateTime.Now; session.Stats.SnipeCount++; waitNextPokestop = true; } } catch (ActiveSwitchByPokemonException ex) { throw ex; } catch (ActiveSwitchAccountManualException ex) { throw ex; } catch (ActiveSwitchByRuleException ex) { throw ex; } catch (CaptchaException cex) { throw cex; } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException is CaptchaException) { throw ex.InnerException; } File.Delete(pth); var ee = new ErrorEvent { Message = ex.Message }; if (ex.InnerException != null) { ee.Message = ex.InnerException.Message; } session.EventDispatcher.Send(ee); } finally { inProgress = false; session.Stats.IsSnipping = false; //Logger.Write($"DEBUG : Back to home location: {originalLatitude},{originalLongitude}"); await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(originalLatitude, originalLongitude), 0).ConfigureAwait(false); } }
private static async Task FarmPokestop(ISession session, FortData pokeStop, FortDetailsResponse fortInfo, CancellationToken cancellationToken, bool doNotRetry = false) { var manager = TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>(); // 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 (manager.AllowMultipleBot() && session.LogicSettings.MultipleBotConfig.SwitchOnPokestopLimit) { throw new Exceptions.ActiveSwitchByRuleException(SwitchRules.SpinPokestopReached, session.LogicSettings.PokeStopLimit); } return; } //await session.Client.Map.GetMapObjects().ConfigureAwait(false); 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) { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude), 0).ConfigureAwait(false); await session.Client.Misc.RandomAPICall().ConfigureAwait(false); } 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).ConfigureAwait(false); if (fortSearch.Result == FortSearchResponse.Types.Result.OutOfRange) { if (retry > 2) { await Task.Delay(500).ConfigureAwait(false); } else { await session.Client.Map.GetMapObjects(true).ConfigureAwait(false); } 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; await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(latitude, longitude), 0).ConfigureAwait(false); 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).ConfigureAwait(false); } 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 = (await session.Inventory.GetItems().ConfigureAwait(false)).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).ConfigureAwait(false); _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 (manager.AllowMultipleBot()) { if (fortTry >= retryNumber - zeroCheck) { softbanCount++; //only check if PokestopSoftbanCount > 0 if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings, manager) && 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).ConfigureAwait(false); } } }
public static async Task <bool> SnipeUnverifiedPokemon(ISession session, MSniperInfo2 sniperInfo, CancellationToken cancellationToken) { var latitude = sniperInfo.Latitude; var longitude = sniperInfo.Longitude; var originalLatitude = session.Client.CurrentLatitude; var originalLongitude = session.Client.CurrentLongitude; var catchedPokemon = false; session.EventDispatcher.Send(new SnipeModeEvent { Active = true }); MapPokemon catchablePokemon; int retry = 3; bool useWalk = session.LogicSettings.EnableHumanWalkingSnipe; try { var distance = LocationUtils.CalculateDistanceInMeters(new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude), new GeoCoordinate(latitude, longitude)); if (useWalk) { Logger.Write($"Walking to snipe target. Distance: {distance}", LogLevel.Info); await session.Navigation.Move( new MapLocation(latitude, longitude, 0), async() => { cancellationToken.ThrowIfCancellationRequested(); await ActionsWhenTravelToSnipeTarget(session, cancellationToken, new MapLocation(latitude, longitude, 0), session.LogicSettings.HumanWalkingSnipeCatchPokemonWhileWalking, session.LogicSettings.HumanWalkingSnipeSpinWhileWalking).ConfigureAwait(false); }, session, cancellationToken, session.LogicSettings.HumanWalkingSnipeAllowSpeedUp?session.LogicSettings.HumanWalkingSnipeMaxSpeedUpSpeed : 200 ).ConfigureAwait(false); } else { Logger.Write($"Jumping to snipe target. Distance: {distance}", LogLevel.Info); await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(latitude, longitude, 10d), 0).ConfigureAwait(false); // Set speed to 0 for random speed. session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = latitude, Longitude = longitude }); } try { do { retry--; var mapObjects = await session.Client.Map.GetMapObjects(true, false).ConfigureAwait(false); catchablePokemon = mapObjects.MapCells.SelectMany(q => q.CatchablePokemons) .Where(q => sniperInfo.PokemonId == (short)q.PokemonId) .OrderByDescending(pokemon => PokemonInfo.CalculateMaxCp(pokemon.PokemonId)) .FirstOrDefault(); } while (catchablePokemon == null && retry > 0); } catch (HasherException ex) { throw ex; } catch (CaptchaException ex) { throw ex; } catch (Exception e) { Logger.Write($"Error: {e.Message}", LogLevel.Error); throw e; } if (catchablePokemon == null) { session.EventDispatcher.Send(new SnipeEvent { Message = session.Translation.GetTranslation(TranslationString.NoPokemonToSnipe), }); session.EventDispatcher.Send(new SnipeFailedEvent { Latitude = latitude, Longitude = longitude, PokemonId = (PokemonId)sniperInfo.PokemonId, EncounterId = sniperInfo.EncounterId }); return(false); } if (catchablePokemon != null) { EncounterResponse encounter; try { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(catchablePokemon.Latitude, catchablePokemon.Longitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed. encounter = await session.Client.Encounter.EncounterPokemon(catchablePokemon.EncounterId, catchablePokemon.SpawnPointId).ConfigureAwait(false); } catch (HasherException ex) { throw ex; } catch (CaptchaException ex) { throw ex; } switch (encounter.Status) { case EncounterResponse.Types.Status.EncounterSuccess: catchedPokemon = await CatchPokemonTask.Execute(session, cancellationToken, encounter, catchablePokemon, 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) }); } return(false); default: session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation( TranslationString.EncounterProblem, encounter.Status) }); break; } await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken).ConfigureAwait(false); } if (catchedPokemon) { session.Stats.SnipeCount++; } session.EventDispatcher.Send(new SnipeModeEvent { Active = false }); return(true); } finally { if (useWalk) { Logger.Write($"Walking back to original location.", LogLevel.Info); await session.Navigation.Move( new MapLocation(originalLatitude, originalLongitude, 0), async() => { cancellationToken.ThrowIfCancellationRequested(); await ActionsWhenTravelToSnipeTarget(session, cancellationToken, new MapLocation(latitude, longitude, 0), session.LogicSettings.HumanWalkingSnipeCatchPokemonWhileWalking, session.LogicSettings.HumanWalkingSnipeSpinWhileWalking).ConfigureAwait(false); }, session, cancellationToken, session.LogicSettings.HumanWalkingSnipeAllowSpeedUp?session.LogicSettings.HumanWalkingSnipeMaxSpeedUpSpeed : 200 ).ConfigureAwait(false); } else { Logger.Write($"Jumping back to original location.", LogLevel.Info); await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(originalLatitude, originalLongitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed. session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = originalLatitude, Longitude = originalLongitude }); await session.Client.Map.GetMapObjects(true).ConfigureAwait(false); } } }
public static async Task <bool> Snipe(ISession session, IEnumerable <PokemonId> pokemonIds, double latitude, double longitude, CancellationToken cancellationToken) { //if (LocsVisited.Contains(new PokemonLocation(latitude, longitude))) // return; var originalLatitude = session.Client.CurrentLatitude; var originalLongitude = session.Client.CurrentLongitude; var catchedPokemon = false; session.EventDispatcher.Send(new SnipeModeEvent { Active = true }); List <MapPokemon> catchablePokemon; int retry = 3; try { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(latitude, longitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed. session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = latitude, Longitude = longitude }); try { do { retry--; var mapObjects = await session.Client.Map.GetMapObjects(true, false).ConfigureAwait(false); catchablePokemon = mapObjects.MapCells.SelectMany(q => q.CatchablePokemons) .Where(q => pokemonIds.Contains(q.PokemonId)) .OrderByDescending(pokemon => PokemonInfo.CalculateMaxCp(pokemon.PokemonId)) .ToList(); } while (catchablePokemon.Count == 0 && retry > 0); } catch (HasherException ex) { throw ex; } catch (CaptchaException ex) { throw ex; } catch (Exception e) { Logger.Write($"Error: {e.Message}", LogLevel.Error); throw e; } if (catchablePokemon.Count == 0) { // Pokemon not found but we still add to the locations visited, so we don't keep sniping // locations with no pokemon. if (!LocsVisited.Contains(new PokemonLocation(latitude, longitude))) { LocsVisited.Add(new PokemonLocation(latitude, longitude)); } session.EventDispatcher.Send(new SnipeEvent { Message = session.Translation.GetTranslation(TranslationString.NoPokemonToSnipe), }); session.EventDispatcher.Send(new SnipeFailedEvent { Latitude = latitude, Longitude = longitude, PokemonId = pokemonIds.FirstOrDefault() }); return(false); } foreach (var pokemon in catchablePokemon) { EncounterResponse encounter; try { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(pokemon.Latitude, pokemon.Longitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed. encounter = await session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId).ConfigureAwait(false); } catch (HasherException ex) { throw ex; } catch (CaptchaException ex) { throw ex; } switch (encounter.Status) { case EncounterResponse.Types.Status.EncounterSuccess: if (!LocsVisited.Contains(new PokemonLocation(latitude, longitude))) { LocsVisited.Add(new PokemonLocation(latitude, longitude)); } //Also add exact pokemon location to LocsVisited, some times the server one differ a little. if (!LocsVisited.Contains(new PokemonLocation(pokemon.Latitude, pokemon.Longitude))) { LocsVisited.Add(new PokemonLocation(pokemon.Latitude, pokemon.Longitude)); } catchedPokemon = await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon, 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) }); } return(false); default: session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation( TranslationString.EncounterProblem, encounter.Status) }); break; } if (!Equals(catchablePokemon.ElementAtOrDefault(catchablePokemon.Count - 1), pokemon)) { await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken).ConfigureAwait(false); } } _lastSnipe = DateTime.Now; if (catchedPokemon) { session.Stats.SnipeCount++; session.Stats.LastSnipeTime = _lastSnipe; } session.EventDispatcher.Send(new SnipeModeEvent { Active = false }); return(true); } finally { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(originalLatitude, originalLongitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed. session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = originalLatitude, Longitude = originalLongitude }); await session.Client.Map.GetMapObjects(true).ConfigureAwait(false); } //await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions, cancellationToken).ConfigureAwait(false); }
public static async Task Snipe(ISession session, IEnumerable <PokemonId> pokemonIds, double latitude, double longitude, CancellationToken cancellationToken) { if (LocsVisited.Contains(new PokemonLocation(latitude, longitude))) { return; } var CurrentLatitude = session.Client.CurrentLatitude; var CurrentLongitude = session.Client.CurrentLongitude; var catchedPokemon = false; session.EventDispatcher.Send(new SnipeModeEvent { Active = true }); List <MapPokemon> catchablePokemon; try { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(latitude, longitude, session.Client.CurrentAltitude)); session.EventDispatcher.Send(new UpdatePositionEvent { Longitude = longitude, Latitude = latitude }); var mapObjects = session.Client.Map.GetMapObjects().Result; catchablePokemon = mapObjects.Item1.MapCells.SelectMany(q => q.CatchablePokemons) .Where(q => pokemonIds.Contains(q.PokemonId)) .OrderByDescending(pokemon => PokemonInfo.CalculateMaxCpMultiplier(pokemon.PokemonId)) .ToList(); } finally { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(CurrentLatitude, CurrentLongitude, session.Client.CurrentAltitude)); } if (catchablePokemon.Count == 0) { // Pokemon not found but we still add to the locations visited, so we don't keep sniping // locations with no pokemon. if (!LocsVisited.Contains(new PokemonLocation(latitude, longitude))) { LocsVisited.Add(new PokemonLocation(latitude, longitude)); } } foreach (var pokemon in catchablePokemon) { EncounterResponse encounter; try { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(latitude, longitude, session.Client.CurrentAltitude)); encounter = session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId).Result; } finally { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(CurrentLatitude, CurrentLongitude, session.Client.CurrentAltitude)); } if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess) { if (!LocsVisited.Contains(new PokemonLocation(latitude, longitude))) { LocsVisited.Add(new PokemonLocation(latitude, longitude)); } //Also add exact pokemon location to LocsVisited, some times the server one differ a little. if (!LocsVisited.Contains(new PokemonLocation(pokemon.Latitude, pokemon.Longitude))) { LocsVisited.Add(new PokemonLocation(pokemon.Latitude, pokemon.Longitude)); } session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = CurrentLatitude, Longitude = CurrentLongitude }); await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon); catchedPokemon = true; } else if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { if (session.LogicSettings.EvolveAllPokemonAboveIv || session.LogicSettings.EvolveAllPokemonWithEnoughCandy || session.LogicSettings.UseLuckyEggsWhileEvolving || session.LogicSettings.KeepPokemonsThatCanEvolve) { await EvolvePokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.TransferDuplicatePokemon) { 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 (!Equals(catchablePokemon.ElementAtOrDefault(catchablePokemon.Count - 1), pokemon)) { await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken); } } if (!catchedPokemon) { session.EventDispatcher.Send(new SnipeEvent { Message = session.Translation.GetTranslation(TranslationString.NoPokemonToSnipe) }); } _lastSnipe = DateTime.Now; if (catchedPokemon) { session.Stats.SnipeCount++; session.Stats.LastSnipeTime = _lastSnipe; } session.EventDispatcher.Send(new SnipeModeEvent { Active = false }); await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions, cancellationToken); }
public static async Task Execute(ISession session, CancellationToken cancellationToken, PokemonId priority = PokemonId.Missingno, bool sessionAllowTransfer = true) { var manager = TinyIoCContainer.Current.Resolve <MultiAccountManager>(); manager.ThrowIfSwitchAccountRequested(); cancellationToken.ThrowIfCancellationRequested(); if (!session.LogicSettings.CatchPokemon) { return; } var totalBalls = (await session.Inventory.GetItems().ConfigureAwait(false)).Where(x => x.ItemId == ItemId.ItemPokeBall || x.ItemId == ItemId.ItemGreatBall || x.ItemId == ItemId.ItemUltraBall).Sum(x => x.Count); if (session.SaveBallForByPassCatchFlee && totalBalls < 130) { return; } if (session.Stats.CatchThresholdExceeds(session)) { if (manager.AllowMultipleBot() && session.LogicSettings.MultipleBotConfig.SwitchOnCatchLimit && manager.AllowSwitch() ) { throw new ActiveSwitchByRuleException() { MatchedRule = SwitchRules.CatchLimitReached, ReachedValue = session.LogicSettings.CatchPokemonLimit }; } return; } Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForPokemon), LogLevel.Debug); var nearbyPokemons = await GetNearbyPokemons(session).ConfigureAwait(false); if (nearbyPokemons == null) { return; } Logger.Write($"Spotted {nearbyPokemons.Count()} pokemon in the area. Trying to catch them all.", LogLevel.Debug); var priorityPokemon = nearbyPokemons.Where(p => p.PokemonId == priority).FirstOrDefault(); var pokemons = nearbyPokemons.Where(p => p.PokemonId != priority).ToList(); //add pokemons to map OnPokemonEncounterEvent(pokemons.ToList()); EncounterResponse encounter = null; //if that is snipe pokemon and inventories if full, execute transfer to get more room for pokemon if (priorityPokemon != null) { pokemons.Insert(0, priorityPokemon); await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(priorityPokemon.Latitude, priorityPokemon.Longitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed. encounter = await session.Client.Encounter .EncounterPokemon(priorityPokemon.EncounterId, priorityPokemon.SpawnPointId).ConfigureAwait(false); if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { if (session.LogicSettings.TransferDuplicatePokemon) { await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } if (session.LogicSettings.TransferWeakPokemon) { await TransferWeakPokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } if (session.LogicSettings.EvolveAllPokemonAboveIv || session.LogicSettings.EvolveAllPokemonWithEnoughCandy || session.LogicSettings.UseLuckyEggsWhileEvolving || session.LogicSettings.KeepPokemonsThatCanEvolve) { await EvolvePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } } } var allitems = await session.Inventory.GetItems().ConfigureAwait(false); var pokeBallsCount = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemPokeBall)?.Count; var greatBallsCount = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemGreatBall)?.Count; var ultraBallsCount = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemUltraBall)?.Count; var masterBallsCount = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemMasterBall)?.Count; masterBallsCount = masterBallsCount ?? 0; //return null ATM. need this code to logic check work var PokeBalls = pokeBallsCount + greatBallsCount + ultraBallsCount + masterBallsCount; if (pokemons.Count > 0) { if (PokeBalls >= session.LogicSettings.PokeballsToKeepForSnipe) // Don't display if not enough Pokeballs - TheWizrad1328 { Logger.Write($"Catching {pokemons.Count} Pokemon Nearby...", LogLevel.Info); } else { Logger.Write($"{session.LogicSettings.PokeballsToKeepForSnipe - PokeBalls} more Pokeballs are needed to catch {pokemons.Count} nearby Pokemon...", LogLevel.Info); } } foreach (var pokemon in pokemons) { await MSniperServiceTask.Execute(session, cancellationToken).ConfigureAwait(false); /* * if (LocationUtils.CalculateDistanceInMeters(pokemon.Latitude, pokemon.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude) > session.Client.GlobalSettings.MapSettings.EncounterRangeMeters) * { * Logger.Debug($"THIS POKEMON IS TOO FAR, {pokemon.Latitude}, {pokemon.Longitude}"); * continue; * } */ cancellationToken.ThrowIfCancellationRequested(); TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); if (session.Cache.GetCacheItem(CatchPokemonTask.GetEncounterCacheKey(pokemon.EncounterId)) != null) { continue; //this pokemon has been skipped because not meet with catch criteria before. } if (PokeBalls < session.LogicSettings.PokeballsToKeepForSnipe && session.CatchBlockTime < DateTime.Now) { session.CatchBlockTime = DateTime.Now.AddMinutes(session.LogicSettings.OutOfBallCatchBlockTime); Logger.Write(session.Translation.GetTranslation(TranslationString.CatchPokemonDisable, session.LogicSettings.OutOfBallCatchBlockTime, session.LogicSettings.PokeballsToKeepForSnipe)); return; } if (session.CatchBlockTime > DateTime.Now) { return; } if ((session.LogicSettings.UsePokemonToCatchLocallyListOnly && !session.LogicSettings.PokemonToCatchLocally.Pokemon.Contains(pokemon.PokemonId)) || (session.LogicSettings.UsePokemonToNotCatchFilter && session.LogicSettings.PokemonsNotToCatch.Contains(pokemon.PokemonId))) { Logger.Write(session.Translation.GetTranslation(TranslationString.PokemonSkipped, session.Translation.GetPokemonTranslation(pokemon.PokemonId))); continue; } /* * var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, * session.Client.CurrentLongitude, pokemon.Latitude, pokemon.Longitude); * await Task.Delay(distance > 100 ? 500 : 100, cancellationToken).ConfigureAwait(false); */ //to avoid duplicated encounter when snipe priority pokemon if (encounter == null || encounter.Status != EncounterResponse.Types.Status.EncounterSuccess) { //await LocationUtils.UpdatePlayerLocationWithAltitude(session, // new GeoCoordinate(pokemon.Latitude, pokemon.Longitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed. encounter = await session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId).ConfigureAwait(false); } if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess && session.LogicSettings.CatchPokemon) { // Catch the Pokemon await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon, currentFortData : null, sessionAllowTransfer : sessionAllowTransfer).ConfigureAwait(false); } else if (encounter.Status == EncounterResponse.Types.Status.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).ConfigureAwait(false); } if (session.LogicSettings.TransferWeakPokemon) { await TransferWeakPokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } if (session.LogicSettings.EvolveAllPokemonAboveIv || session.LogicSettings.EvolveAllPokemonWithEnoughCandy || session.LogicSettings.UseLuckyEggsWhileEvolving || session.LogicSettings.KeepPokemonsThatCanEvolve) { await EvolvePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } } 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) }); } encounter = null; // If pokemon is not last pokemon in list, create delay between catches, else keep moving. if (!Equals(pokemons.ElementAtOrDefault(pokemons.Count() - 1), pokemon)) { await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken).ConfigureAwait(false); } } }
public static async Task Execute(ISession session, CancellationToken cancellationToken, PokemonId priority = PokemonId.Missingno, bool sessionAllowTransfer = true) { TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); cancellationToken.ThrowIfCancellationRequested(); if (!session.LogicSettings.CatchPokemon) { return; } 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; } Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForPokemon), LogLevel.Debug); var nearbyPokemons = await GetNearbyPokemons(session); if (nearbyPokemons == null) { return; } var priorityPokemon = nearbyPokemons.Where(p => p.PokemonId == priority).FirstOrDefault(); var pokemons = nearbyPokemons.Where(p => p.PokemonId != priority).ToList(); EncounterResponse encounter = null; //if that is snipe pokemon and inventories if full, execute transfer to get more room for pokemon if (priorityPokemon != null) { pokemons.Insert(0, priorityPokemon); LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(priorityPokemon.Latitude, priorityPokemon.Longitude, session.Client.CurrentAltitude), 0); // Set speed to 0 for random speed. encounter = await session.Client.Encounter .EncounterPokemon(priorityPokemon.EncounterId, priorityPokemon.SpawnPointId); if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { 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); } } } foreach (var pokemon in pokemons) { await MSniperServiceTask.Execute(session, cancellationToken); //should load it dynamic from - MapSettings.encounterRangeMeters_ if (LocationUtils.CalculateDistanceInMeters(pokemon.Latitude, pokemon.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude) > session.Client.GlobalSettings.MapSettings.EncounterRangeMeters) { Logger.Debug($"THIS POKEMON IS TOO FAR, {pokemon.Latitude}, {pokemon.Longitude}"); continue; } cancellationToken.ThrowIfCancellationRequested(); TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); string pokemonUniqueKey = $"{pokemon.EncounterId}"; if (session.Cache.GetCacheItem(pokemonUniqueKey) != null) { continue; //this pokemon has been skipped because not meet with catch criteria before. } var allitems = session.Inventory.GetItems(); var pokeBallsCount = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemPokeBall)?.Count; var greatBallsCount = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemGreatBall)?.Count; var ultraBallsCount = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemUltraBall)?.Count; var masterBallsCount = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemMasterBall)?.Count; masterBallsCount = masterBallsCount == null ? 0 : masterBallsCount; //return null ATM. need this code to logic check work if (pokeBallsCount + greatBallsCount + ultraBallsCount + masterBallsCount < session.LogicSettings.PokeballsToKeepForSnipe && session.CatchBlockTime < DateTime.Now) { session.CatchBlockTime = DateTime.Now.AddMinutes(session.LogicSettings.OutOfBallCatchBlockTime); Logger.Write(session.Translation.GetTranslation(TranslationString.CatchPokemonDisable, session.LogicSettings.OutOfBallCatchBlockTime, session.LogicSettings.PokeballsToKeepForSnipe)); return; } if (session.CatchBlockTime > DateTime.Now) { return; } if ((session.LogicSettings.UsePokemonSniperFilterOnly && !session.LogicSettings.PokemonToSnipe.Pokemon.Contains(pokemon.PokemonId)) || (session.LogicSettings.UsePokemonToNotCatchFilter && session.LogicSettings.PokemonsNotToCatch.Contains(pokemon.PokemonId))) { Logger.Write(session.Translation.GetTranslation(TranslationString.PokemonSkipped, session.Translation.GetPokemonTranslation(pokemon.PokemonId))); continue; } var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, pokemon.Latitude, pokemon.Longitude); await Task.Delay(distance > 100? 500 : 100, cancellationToken); //to avoid duplicated encounter when snipe priority pokemon if (encounter == null || encounter.Status != EncounterResponse.Types.Status.EncounterSuccess) { LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(pokemon.Latitude, pokemon.Longitude, session.Client.CurrentAltitude), 0); // Set speed to 0 for random speed. encounter = await session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId); } if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess && session.LogicSettings.CatchPokemon) { // Catch the Pokemon await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon, currentFortData : null, sessionAllowTransfer : sessionAllowTransfer); } else if (encounter.Status == EncounterResponse.Types.Status.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 { session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.EncounterProblem, encounter.Status) }); } encounter = null; // If pokemon is not last pokemon in list, create delay between catches, else keep moving. if (!Equals(pokemons.ElementAtOrDefault(pokemons.Count() - 1), pokemon)) { await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken); } } }
public async Task <PlayerUpdateResponse> Walk(GeoCoordinate targetLocation, Func <Task <bool> > functionExecutedWhileWalking, ISession session, CancellationToken cancellationToken, double walkSpeed = 0.0) { 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; if (walkSpeed != 0) { speedInMetersPerSecond = walkSpeed / 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; } if (walkSpeed != 0) { speedInMetersPerSecond = walkSpeed / 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) >= (new Random()).Next(1, 10)); return(result); }
public override async Task <PlayerUpdateResponse> Walk(IGeoLocation targetLocation, Func <Task> functionExecutedWhileWalking, ISession session, CancellationToken cancellationToken, double walkSpeed = 0.0) { var curLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var destinaionCoordinate = new GeoCoordinate(targetLocation.Latitude, targetLocation.Longitude); var dist = LocationUtils.CalculateDistanceInMeters(curLocation, destinaionCoordinate); if (dist >= 100) { var nextWaypointDistance = dist * 70 / 100; var nextWaypointBearing = LocationUtils.DegreeBearing(curLocation, destinaionCoordinate); var waypoint = LocationUtils.CreateWaypoint(curLocation, nextWaypointDistance, nextWaypointBearing); var sentTime = DateTime.Now; var result = await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, 0); // We are setting speed to 0, so it will be randomly generated speed. base.DoUpdatePositionEvent(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, destinaionCoordinate); dist = LocationUtils.CalculateDistanceInMeters(curLocation, destinaionCoordinate); if (dist >= 100) { nextWaypointDistance = dist * 70 / 100; } else { nextWaypointDistance = dist; } nextWaypointBearing = LocationUtils.DegreeBearing(curLocation, destinaionCoordinate); waypoint = LocationUtils.CreateWaypoint(curLocation, nextWaypointDistance, nextWaypointBearing); sentTime = DateTime.Now; result = await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, 0); // We are setting speed to 0, so it will be randomly generated speed. base.DoUpdatePositionEvent(waypoint.Latitude, waypoint.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(curLocation, destinaionCoordinate) >= 10); return(result); } else { var result = await LocationUtils.UpdatePlayerLocationWithAltitude(session, targetLocation.ToGeoCoordinate(), 0); // We are setting speed to 0, so it will be randomly generated speed. base.DoUpdatePositionEvent(targetLocation.Latitude, targetLocation.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon } return(result); } }
public static async Task <bool> SnipeUnverifiedPokemon(ISession session, MSniperInfo2 sniperInfo, CancellationToken cancellationToken) { var latitude = sniperInfo.Latitude; var longitude = sniperInfo.Longitude; var currentLatitude = session.Client.CurrentLatitude; var currentLongitude = session.Client.CurrentLongitude; var catchedPokemon = false; session.EventDispatcher.Send(new SnipeModeEvent { Active = true }); MapPokemon catchablePokemon; int retry = 3; bool isCaptchaShow = false; try { do { retry--; await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(latitude, longitude, 10d), 0).ConfigureAwait(false); // Set speed to 0 for random speed. latitude += 0.00000001; longitude += 0.00000001; session.EventDispatcher.Send(new UpdatePositionEvent { Longitude = longitude, Latitude = latitude }); var mapObjects = await session.Client.Map.GetMapObjects(true, false).ConfigureAwait(false); catchablePokemon = mapObjects.MapCells.SelectMany(q => q.CatchablePokemons) .Where(q => sniperInfo.PokemonId == (short)q.PokemonId) .OrderByDescending(pokemon => PokemonInfo.CalculateMaxCp(pokemon.PokemonId)) .FirstOrDefault(); } while (catchablePokemon != null && retry > 0); } catch (HasherException ex) { throw ex; } catch (CaptchaException ex) { throw ex; } catch (Exception e) { Logger.Write($"Error: {e.Message}", LogLevel.Error); throw e; } finally { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(currentLatitude, currentLongitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed. } if (catchablePokemon == null) { session.EventDispatcher.Send(new SnipeEvent { Message = session.Translation.GetTranslation(TranslationString.NoPokemonToSnipe), }); session.EventDispatcher.Send(new SnipeFailedEvent { Latitude = latitude, Longitude = longitude, PokemonId = (PokemonId)sniperInfo.PokemonId, EncounterId = sniperInfo.EncounterId }); return(false); } isCaptchaShow = false; if (catchablePokemon != null) { EncounterResponse encounter; try { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(catchablePokemon.Latitude, catchablePokemon.Longitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed. encounter = await session.Client.Encounter.EncounterPokemon(catchablePokemon.EncounterId, catchablePokemon.SpawnPointId).ConfigureAwait(false); } catch (HasherException ex) { throw ex; } catch (CaptchaException ex) { isCaptchaShow = true; throw ex; } finally { if (!isCaptchaShow) { await LocationUtils.UpdatePlayerLocationWithAltitude(session, // Set speed to 0 for random speed. new GeoCoordinate(currentLatitude, currentLongitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); } } switch (encounter.Status) { case EncounterResponse.Types.Status.EncounterSuccess: session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = currentLatitude, Longitude = currentLongitude }); catchedPokemon = await CatchPokemonTask.Execute(session, cancellationToken, encounter, catchablePokemon, 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) }); } return(false); default: session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation( TranslationString.EncounterProblem, encounter.Status) }); break; } await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken).ConfigureAwait(false); } if (catchedPokemon) { session.Stats.SnipeCount++; } session.EventDispatcher.Send(new SnipeModeEvent { Active = false }); return(true); //await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions, cancellationToken).ConfigureAwait(false); }
public static async Task <bool> CatchFromService(ISession session, CancellationToken cancellationToken, MSniperInfo2 encounterId) { cancellationToken.ThrowIfCancellationRequested(); double originalLat = session.Client.CurrentLatitude; double originalLng = session.Client.CurrentLongitude; EncounterResponse encounter; try { // Speed set to 0 for random speed. await LocationUtils.UpdatePlayerLocationWithAltitude( session, new GeoCoordinate(encounterId.Latitude, encounterId.Longitude, session.Client.CurrentAltitude), 0 ).ConfigureAwait(false); await session.Client.Misc.RandomAPICall().ConfigureAwait(false); encounter = await session.Client.Encounter.EncounterPokemon(encounterId.EncounterId, encounterId.SpawnPointId).ConfigureAwait(false); if (encounter != null && encounter.Status != EncounterResponse.Types.Status.EncounterSuccess) { Logger.Debug($"{encounter}"); } //pokemon has expired, send event to remove it. if (encounter != null && (encounter.Status == EncounterResponse.Types.Status.EncounterClosed || encounter.Status == EncounterResponse.Types.Status.EncounterNotFound)) { session.EventDispatcher.Send(new SnipePokemonUpdateEvent(encounterId.EncounterId.ToString(), false, null)); } } catch (CaptchaException ex) { throw ex; } catch (Exception) { return(false); } finally { session.Client.Player.SetCoordinates(originalLat, originalLng, session.Client.CurrentAltitude); //only reset d } if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { Logger.Write("Pokemon bag full, snipe cancel"); await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); return(false); } if (encounter.Status == EncounterResponse.Types.Status.EncounterClosed) { Logger.Write("This pokemon has been expired"); return(true); } PokemonData encounteredPokemon; // Catch if it's a WildPokemon (MSniping not allowed for Incense pokemons) if (encounter?.Status == EncounterResponse.Types.Status.EncounterSuccess) { encounteredPokemon = encounter.WildPokemon?.PokemonData; } else { Logger.Write($"Pokemon despawned or wrong link format!", LogLevel.Service, ConsoleColor.Gray); return(false); //return await CatchWithSnipe(session, encounterId, cancellationToken).ConfigureAwait(false);// No success to work with } var pokemon = new MapPokemon { EncounterId = encounterId.EncounterId, Latitude = encounterId.Latitude, Longitude = encounterId.Longitude, PokemonId = encounteredPokemon.PokemonId, SpawnPointId = encounterId.SpawnPointId }; return(await CatchPokemonTask.Execute( session, cancellationToken, encounter, pokemon, currentFortData : null, sessionAllowTransfer : true ).ConfigureAwait(false)); }
public static async Task <bool> CatchFromService(ISession session, CancellationToken cancellationToken, MSniperInfo2 encounterId) { cancellationToken.ThrowIfCancellationRequested(); TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); double lat = session.Client.CurrentLatitude; double lon = session.Client.CurrentLongitude; bool captchaShowed = false; EncounterResponse encounter; try { // Speed set to 0 for random speed. await LocationUtils.UpdatePlayerLocationWithAltitude( session, new GeoCoordinate(encounterId.Latitude, encounterId.Longitude, session.Client.CurrentAltitude), 0 ); await session.Client.Misc.RandomAPICall(); //await session.Client.Map.GetMapObjects(true); //await Task.Delay(1000, cancellationToken); encounter = await session.Client.Encounter.EncounterPokemon(encounterId.EncounterId, encounterId.SpawnPointId); #if DEBUG if (encounter != null && encounter.Status != EncounterResponse.Types.Status.EncounterSuccess) { Debug.WriteLine($"{encounter}"); Logger.Write($"{encounter}"); } #endif //pokemon has expired, send event to remove it. if (encounter != null && (encounter.Status == EncounterResponse.Types.Status.EncounterClosed || encounter.Status == EncounterResponse.Types.Status.EncounterNotFound)) { session.EventDispatcher.Send(new SnipePokemonUpdateEvent(encounterId.EncounterId.ToString(), false, null)); } } catch (CaptchaException ex) { captchaShowed = true; throw ex; } catch (Exception) { return(false); } finally { if (!captchaShowed) { //TODO - What if udpate location failed // Speed set to 0 for random speed. var response = await LocationUtils.UpdatePlayerLocationWithAltitude( session, new GeoCoordinate(lat, lon, session.Client.CurrentAltitude), 0 ); } else { session.Client.Player.SetCoordinates(lat, lon, session.Client.CurrentAltitude); //only reset d } } if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { Logger.Write("Pokemon bag full, snipe cancel"); await TransferDuplicatePokemonTask.Execute(session, cancellationToken); return(false); } if (encounter.Status == EncounterResponse.Types.Status.EncounterClosed) { Logger.Write("This pokemon has been expired"); return(true); } PokemonData encounteredPokemon; // Catch if it's a WildPokemon (MSniping not allowed for Incense pokemons) if (encounter?.Status == EncounterResponse.Types.Status.EncounterSuccess) { encounteredPokemon = encounter.WildPokemon?.PokemonData; } else { Logger.Write($"Pokemon despawned or wrong link format!", LogLevel.Service, ConsoleColor.Gray); return(false); //return await CatchWithSnipe(session, encounterId, cancellationToken);// No success to work with } var pokemon = new MapPokemon { EncounterId = encounterId.EncounterId, Latitude = encounterId.Latitude, Longitude = encounterId.Longitude, PokemonId = encounteredPokemon.PokemonId, SpawnPointId = encounterId.SpawnPointId }; return(await CatchPokemonTask.Execute( session, cancellationToken, encounter, pokemon, currentFortData : null, sessionAllowTransfer : true )); }
public static async Task <bool> CatchFromService(ISession session, CancellationToken cancellationToken, MSniperInfo2 encounterId) { cancellationToken.ThrowIfCancellationRequested(); double lat = session.Client.CurrentLatitude; double lon = session.Client.CurrentLongitude; bool captchaShowed = false; EncounterResponse encounter; try { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(encounterId.Latitude, encounterId.Longitude, session.Client.CurrentAltitude), 0); // Speed set to 0 for random speed. await Task.Delay(1000, cancellationToken); encounter = await session.Client.Encounter.EncounterPokemon(encounterId.EncounterId, encounterId.SpawnPointId); } catch (CaptchaException ex) { captchaShowed = true; throw ex; } catch (Exception ex) { return(false); } finally { if (!captchaShowed) { //TODO - What if udpate location failed var response = await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(lat, lon, session.Client.CurrentAltitude), 0); // Speed set to 0 for random speed. } else { session.Client.Player.SetCoordinates(lat, lon, session.Client.CurrentAltitude); //only reset d } } if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { Logger.Write("Pokemon bag full, snipe cancel"); await TransferDuplicatePokemonTask.Execute(session, cancellationToken); return(false); } PokemonData encounteredPokemon; // Catch if it's a WildPokemon (MSniping not allowed for Incense pokemons) if (encounter?.Status == EncounterResponse.Types.Status.EncounterSuccess) { encounteredPokemon = encounter.WildPokemon?.PokemonData; } else { Logger.Write($"Pokemon despawned or wrong link format!", LogLevel.Service, ConsoleColor.Gray); return(false); //return await CatchWithSnipe(session, encounterId, cancellationToken);// No success to work with } var pokemon = new MapPokemon { EncounterId = encounterId.EncounterId, Latitude = encounterId.Latitude, Longitude = encounterId.Longitude, PokemonId = encounteredPokemon.PokemonId, SpawnPointId = encounterId.SpawnPointId }; return(await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon, currentFortData : null, sessionAllowTransfer : true)); }
public static async Task OwnSnipe(ISession session, PokemonId targetPokemonId, double latitude, double longitude, CancellationToken cancellationToken, bool sessionAllowTransfer = true) { var currentLatitude = session.Client.CurrentLatitude; var currentLongitude = session.Client.CurrentLongitude; session.EventDispatcher.Send(new SnipeModeEvent { Active = true }); List <MapPokemon> catchablePokemon; try { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(latitude, longitude, session.Client.CurrentAltitude)); session.EventDispatcher.Send(new UpdatePositionEvent { Longitude = longitude, Latitude = latitude }); var nearbyPokemons = await GetPokemons(session); catchablePokemon = nearbyPokemons.Where(p => p.PokemonId == targetPokemonId).ToList(); } finally { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(currentLatitude, currentLongitude, session.Client.CurrentAltitude)); } if (catchablePokemon.Count > 0) { foreach (var pokemon in catchablePokemon) { cancellationToken.ThrowIfCancellationRequested(); EncounterResponse encounter; try { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(latitude, longitude, session.Client.CurrentAltitude)); encounter = await session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId); } finally { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(currentLatitude, currentLongitude, session.Client.CurrentAltitude)); } switch (encounter.Status) { case EncounterResponse.Types.Status.EncounterSuccess: session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = currentLatitude, Longitude = currentLongitude }); await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon); session.Stats.SnipeCount++; session.Stats.LastSnipeTime = DateTime.Now; break; case EncounterResponse.Types.Status.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); } } else { session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually) }); } break; default: session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.EncounterProblem, encounter.Status) }); break; } if (!Equals(catchablePokemon.ElementAtOrDefault(catchablePokemon.Count() - 1), pokemon)) { await Task.Delay(2000, cancellationToken); } } } else { session.EventDispatcher.Send(new SnipeEvent { Message = session.Translation.GetTranslation(TranslationString.NoPokemonToSnipe) }); } await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(currentLatitude, currentLongitude, session.Client.CurrentAltitude)); session.EventDispatcher.Send(new SnipeModeEvent { Active = false }); await Task.Delay(5000, cancellationToken); }
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()); } } OnGetRouteEvent(points); 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 = await LocationUtils.CreateWaypoint(currentLocation, nextStepDistance, nextStepBearing).ConfigureAwait(false); walkedPointsList.Add(waypoint); var previousLocation = currentLocation; //store the current location for comparison and correction purposes var requestSendDateTime = DateTime.Now; await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond).ConfigureAwait(false); 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 = await LocationUtils.CreateWaypoint(currentLocation, nextStepDistance, nextStepBearing).ConfigureAwait(false); walkedPointsList.Add(waypoint); //store the current location for comparison and correction purposes previousLocation = currentLocation; requestSendDateTime = DateTime.Now; await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond).ConfigureAwait(false); UpdatePositionEvent?.Invoke(session, waypoint.Latitude, waypoint.Longitude, _currentWalkingSpeed); await Task.Delay(timeToWalk).ConfigureAwait(false); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking().ConfigureAwait(false); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(currentLocation, nextStep) >= 2); UpdatePositionEvent?.Invoke(session, nextStep.Latitude, nextStep.Longitude, _currentWalkingSpeed); } }
public async Task <PlayerUpdateResponse> Walk(GeoCoordinate targetLocation, Func <Task <bool> > functionExecutedWhileWalking, ISession session, CancellationToken cancellationToken, double walkSpeed = 0.0) { cancellationToken.ThrowIfCancellationRequested(); //PlayerUpdateResponse result = null; 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); LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); 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) // { // //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) { CurrentWalkingSpeed = session.Navigation.VariantRandom(session, CurrentWalkingSpeed); speedInMetersPerSecond = CurrentWalkingSpeed / 3.6; } nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond); nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); 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 & hit stops } } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 2); return(result); }
public override async Task 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 = await LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing).ConfigureAwait(false); var requestSendDateTime = DateTime.Now; var requestVariantDateTime = DateTime.Now; await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond).ConfigureAwait(false); 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 = await LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing).ConfigureAwait(false); requestSendDateTime = DateTime.Now; await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond).ConfigureAwait(false); base.DoUpdatePositionEvent(session, waypoint.Latitude, waypoint.Longitude, CurrentWalkingSpeed); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking().ConfigureAwait(false); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, destinaionCoordinate) >= (new Random()).Next(1, 10)); }
public override async Task Walk(IGeoLocation targetLocation, Func <Task> functionExecutedWhileWalking, ISession session, CancellationToken cancellationToken, double walkSpeed = 0.0) { cancellationToken.ThrowIfCancellationRequested(); TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); var destinaionCoordinate = new GeoCoordinate(targetLocation.Latitude, targetLocation.Longitude); //PlayerUpdateResponse result = null; 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); LocationUtils.CalculateDistanceInMeters(sourceLocation, destinaionCoordinate); var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, destinaionCoordinate); var nextWaypointDistance = speedInMetersPerSecond; var waypoint = await LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing).ConfigureAwait(false); var requestSendDateTime = DateTime.Now; var requestVariantDateTime = DateTime.Now; await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond).ConfigureAwait(false); double SpeedVariantSec = rw.Next(1000, 10000); base.DoUpdatePositionEvent(session, waypoint.Latitude, waypoint.Longitude, walkSpeed, 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) // { // //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 && walkSpeed == 0) { CurrentWalkingSpeed = session.Navigation.VariantRandom(session, CurrentWalkingSpeed); speedInMetersPerSecond = CurrentWalkingSpeed / 3.6; } nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond); nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, destinaionCoordinate); waypoint = await LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing).ConfigureAwait(false); requestSendDateTime = DateTime.Now; await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond).ConfigureAwait(false); base.DoUpdatePositionEvent(session, waypoint.Latitude, waypoint.Longitude, CurrentWalkingSpeed); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking().ConfigureAwait(false); // look for pokemon & hit stops } } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, destinaionCoordinate) >= 2); }