Skip to content
This repository has been archived by the owner on Nov 7, 2019. It is now read-only.

Commit

Permalink
feat: optimizations to get more experience per hour ( 80+k per hour )
Browse files Browse the repository at this point in the history
Main changes:
    - Add a loop to Spin Fort worker, now we spin every ready and in range fort per tick.
    - Add a loop in CatchLuredPokemon, same as above.
    - Remove a bunch of logs (it's hard to see what happens)
    - Change some logs (to make it easy to see the experience)
    - Add PR PokemonGoF#2252 (thanks @Moonlight-Angel) and PR PokemonGoF#2240 (thanks @lucasfevi)

BREAKING CHANGES:
    - Add tick_count and delayed some workers (RecycleItem, TransferPokemon)
  • Loading branch information
matheussampaio committed Aug 3, 2016
1 parent e58bf3d commit d7f5c51
Show file tree
Hide file tree
Showing 15 changed files with 431 additions and 154 deletions.
15 changes: 12 additions & 3 deletions pokemongo_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,24 @@ def _setup_event_system(self):

def tick(self):
self.cell = self.get_meta_cell()
self.tick_count += 1

# Check if session token has expired
self.check_session(self.position[0:2])
start_tick = time.time()

for worker in self.workers:
if worker.work() == WorkerResult.RUNNING:

if worker.work(tick_count = self.tick_count) == WorkerResult.RUNNING:
return

end_tick = time.time()

if end_tick - start_tick < 5:
logger.log('Waiting {:.2f}...'.format(5 - (end_tick - start_tick)))
time.sleep(5 - (end_tick - start_tick))

self.tick_count += 1

def get_meta_cell(self):
location = self.position[0:2]
cells = self.find_close_cells(*location)
Expand All @@ -103,7 +112,7 @@ def get_meta_cell(self):
wild_pokemons += cell["wild_pokemons"]
if "catchable_pokemons" in cell and len(cell["catchable_pokemons"]):
catchable_pokemons += cell["catchable_pokemons"]

# If there are forts present in the cells sent from the server or we don't yet have any cell data, return all data retrieved
if len(forts) > 1 or not self.cell:
return {
Expand Down
3 changes: 2 additions & 1 deletion pokemongo_bot/cell_workers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@
from collect_level_up_reward import CollectLevelUpReward
from base_task import BaseTask
from follow_cluster import FollowCluster
from sleep_schedule import SleepSchedule
from sleep_schedule import SleepSchedule
from update_title_stats import UpdateTitleStats
53 changes: 32 additions & 21 deletions pokemongo_bot/cell_workers/catch_lured_pokemon.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,47 @@
import time

from pokemongo_bot import logger
from pokemongo_bot.cell_workers.utils import fort_details
from pokemongo_bot.constants import Constants
from pokemongo_bot.cell_workers.utils import fort_details, distance
from pokemongo_bot.cell_workers.pokemon_catch_worker import PokemonCatchWorker
from pokemongo_bot.cell_workers.base_task import BaseTask

class CatchLuredPokemon(BaseTask):
def work(self):
def work(self, *args, **kwargs):
lured_pokemon = self.get_lured_pokemon()
if lured_pokemon:
self.catch_pokemon(lured_pokemon)

def get_lured_pokemon(self):
forts = self.bot.get_forts(order_by_distance=True)

if len(forts) == 0:
return False

fort = forts[0]
details = fort_details(self.bot, fort_id=fort['id'],
latitude=fort['latitude'],
longitude=fort['longitude'])
fort_name = details.get('name', 'Unknown').encode('utf8', 'replace')

encounter_id = fort.get('lure_info', {}).get('encounter_id', None)

if encounter_id:
logger.log('Lured pokemon at fort {}'.format(fort_name))
return {
'encounter_id': encounter_id,
'fort_id': fort['id'],
'latitude': fort['latitude'],
'longitude': fort['longitude']
}
forts_in_range = []

for fort in forts:
distance_to_fort = distance(
self.bot.position[0],
self.bot.position[1],
fort['latitude'],
fort['longitude']
)

if distance_to_fort <= Constants.MAX_DISTANCE_FORT_IS_REACHABLE:
forts_in_range.append(fort)

forts_with_lured_pokemons = [fort for fort in forts_in_range if fort.get('lure_info', {}).get('encounter_id', None)]

for fort in forts_with_lured_pokemons:
encounter_id = fort.get('lure_info', {}).get('encounter_id', None)

if encounter_id:
self.catch_pokemon({
'encounter_id': encounter_id,
'fort_id': fort['id'],
'latitude': fort['latitude'],
'longitude': fort['longitude']
})

time.sleep(1)

return False

Expand Down
4 changes: 2 additions & 2 deletions pokemongo_bot/cell_workers/catch_visible_pokemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@


class CatchVisiblePokemon(BaseTask):
def work(self):
def work(self, *args, **kwargs):
if 'catchable_pokemons' in self.bot.cell and len(self.bot.cell['catchable_pokemons']) > 0:
logger.log('Something rustles nearby!')
# logger.log('Something rustles nearby!')
# Sort all by distance from current pos- eventually this should
# build graph & A* it
self.bot.cell['catchable_pokemons'].sort(
Expand Down
9 changes: 6 additions & 3 deletions pokemongo_bot/cell_workers/collect_level_up_reward.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ def initialize(self):
self.current_level = self._get_current_level()
self.previous_level = 0

def work(self):
def work(self, *args, **kwargs):
if kwargs.get('tick_count', -1) % 50:
return

self.current_level = self._get_current_level()

# let's check level reward on bot initialization
Expand All @@ -34,13 +37,13 @@ def _collect_level_reward(self):
.get('items_awarded', []))

if data:
logger.log('Collected level up rewards:', 'green')
logger.log('Collected level up rewards:')

for item in data:
if 'item_id' in item and str(item['item_id']) in self.bot.item_list:
got_item = self.bot.item_list[str(item['item_id'])]
count = 'item_count' in item and item['item_count'] or 0
logger.log('{} x {}'.format(got_item, count), 'green')
logger.log('+{} {}'.format(count, got_item), 'green')

def _get_current_level(self):
level = 0
Expand Down
5 changes: 4 additions & 1 deletion pokemongo_bot/cell_workers/handle_soft_ban.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@


class HandleSoftBan(BaseTask):
def work(self):
def work(self, *args, **kwargs):
if kwargs.get('tick_count', -1) % 20:
return

if not self.should_run():
return

Expand Down
33 changes: 19 additions & 14 deletions pokemongo_bot/cell_workers/incubate_eggs.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ def initialize(self):
def _process_config(self):
self.longer_eggs_first = self.config.get("longer_eggs_first", True)

def work(self):
def work(self, *args, **kwargs):
if kwargs.get('tick_count', -1) % 1:
return

try:
self._check_inventory()
except:
Expand All @@ -31,7 +34,7 @@ def work(self):
if km_left <= 0:
self._hatch_eggs()
else:
logger.log('[x] Current egg hatches in {:.2f} km'.format(km_left),'yellow')
logger.log('Current egg hatches in {:.2f} km'.format(km_left))
IncubateEggs.last_km_walked = self.km_walked

sorting = self.longer_eggs_first
Expand Down Expand Up @@ -138,7 +141,7 @@ def _hatch_eggs(self):
stardust = result.get('stardust_awarded', "error")
candy = result.get('candy_awarded', "error")
xp = result.get('experience_awarded', "error")
sleep(self.hatching_animation_delay)
# sleep(self.hatching_animation_delay)
self.bot.latest_inventory = None
try:
pokemon_data = self._check_inventory(pokemon_ids)
Expand All @@ -150,17 +153,19 @@ def _hatch_eggs(self):
pokemon['name'] = "error"
except:
pokemon_data = [{"name":"error","cp":"error","iv":"error"}]
logger.log("-"*30, log_color)
logger.log("-"*30)
if not pokemon_ids or pokemon_data[0]['name'] == "error":
logger.log("[!] Eggs hatched, but we had trouble with the response. Please check your inventory to find your new pokemon!",'red')
# logger.log("[!] Eggs hatched, but we had trouble with the response. Please check your inventory to find your new pokemon!",'red')
return
logger.log("[!] {} eggs hatched! Received:".format(len(pokemon_data)), log_color)

logger.log("[{:>+5d} xp] EGG - {} eggs hatched! Received:".format(xp, len(pokemon_data)), 'green')

for i in range(len(pokemon_data)):
logger.log("-"*30,log_color)
logger.log("[!] Pokemon: {}".format(pokemon_data[i]['name']), log_color)
logger.log("[!] CP: {}".format(pokemon_data[i].get('cp',0)), log_color)
logger.log("[!] IV: {} ({:.2f})".format("/".join(map(str, pokemon_data[i]['iv'])),(sum(pokemon_data[i]['iv'])/self.max_iv)), log_color)
logger.log("[!] XP: {}".format(xp[i]), log_color)
logger.log("[!] Stardust: {}".format(stardust[i]), log_color)
logger.log("[!] Candy: {}".format(candy[i]), log_color)
logger.log("-"*30, log_color)
logger.log("-"*3)
logger.log("[!] Pokemon: {}".format(pokemon_data[i]['name']))
logger.log("[!] CP: {}".format(pokemon_data[i].get('cp',0)))
logger.log("[!] IV: {} ({:.2f})".format("/".join(map(str, pokemon_data[i]['iv'])),(sum(pokemon_data[i]['iv'])/self.max_iv)))
logger.log("[!] XP: {}".format(xp[i]))
logger.log("[!] Stardust: {}".format(stardust[i]))
logger.log("[!] Candy: {}".format(candy[i]))
logger.log("-"*30)
22 changes: 7 additions & 15 deletions pokemongo_bot/cell_workers/move_to_fort.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pokemongo_bot.step_walker import StepWalker
from pokemongo_bot.worker_result import WorkerResult
from pokemongo_bot.cell_workers.base_task import BaseTask
from utils import distance, format_dist, fort_details
from utils import distance, format_dist


class MoveToFort(BaseTask):
Expand All @@ -13,19 +13,10 @@ def initialize(self):
self.lure_attraction = self.config.get("lure_attraction", True)
self.lure_max_distance = self.config.get("lure_max_distance", 2000)

def should_run(self):
has_space_for_loot = self.bot.has_space_for_loot()
if not has_space_for_loot:
logger.log("Not moving to any forts as there aren't enough space. You might want to change your config to recycle more items if this message appears consistently.", 'yellow')
return has_space_for_loot or self.bot.softban

def is_attracted(self):
return (self.lure_distance > 0)

def work(self):
if not self.should_run():
return WorkerResult.SUCCESS

def work(self, *args, **kwargs):
nearest_fort = self.get_nearest_fort()

if nearest_fort is None:
Expand All @@ -34,8 +25,6 @@ def work(self):
lat = nearest_fort['latitude']
lng = nearest_fort['longitude']
fortID = nearest_fort['id']
details = fort_details(self.bot, fortID, lat, lng)
fort_name = details.get('name', 'Unknown').encode('utf8', 'replace')

unit = self.bot.config.distance_unit # Unit to use when printing formatted distance

Expand All @@ -52,7 +41,7 @@ def work(self):
else:
add_str = ''

logger.log('Moving towards fort {}, {} left{}'.format(fort_name, format_dist(dist, unit), add_str))
logger.log('Moving towards fort {}, {} left{}'.format(fortID, format_dist(dist, unit), add_str))

step_walker = StepWalker(
self.bot,
Expand All @@ -64,7 +53,8 @@ def work(self):
if not step_walker.step():
return WorkerResult.RUNNING

logger.log('Arrived at pokestop.')
logger.log('Arrived at pokestop: {}'.format(fortID))

return WorkerResult.SUCCESS

def _get_nearest_fort_on_lure_way(self, forts):
Expand Down Expand Up @@ -113,6 +103,8 @@ def get_nearest_fort(self):
# Remove stops that are still on timeout
forts = filter(lambda x: x["id"] not in self.bot.fort_timeouts, forts)

forts = filter(lambda x: 'cooldown_complete_timestamp_ms' not in x, forts)

next_attracted_pts, lure_distance = self._get_nearest_fort_on_lure_way(forts)

# Remove all forts which were spun in the last ticks to avoid circles if set
Expand Down
Loading

0 comments on commit d7f5c51

Please sign in to comment.