From 8a0ede1c71e4e8315694846996809d348bafc487 Mon Sep 17 00:00:00 2001 From: Petar Toshev Date: Fri, 22 Dec 2023 18:44:46 +0200 Subject: [PATCH] Rename getCity properties to be in English with more descriptive wording (#194) --- ikabot/config.py | 3 ++ ikabot/function/alertLowWine.py | 7 ++--- ikabot/function/constructionList.py | 8 +++--- ikabot/function/distributeResources.py | 12 ++++---- ikabot/function/donate.py | 2 +- ikabot/function/donationBot.py | 2 +- ikabot/function/dumpWorld.py | 6 ++-- ikabot/function/getStatus.py | 4 +-- ikabot/function/investigate.py | 2 +- ikabot/function/searchForIslandSpaces.py | 8 +++--- ikabot/function/sellResources.py | 4 +-- ikabot/function/sendResources.py | 6 ++-- ikabot/function/trainArmy.py | 8 +++--- ikabot/helpers/getJson.py | 24 ++++++++-------- ikabot/helpers/pedirInfo.py | 16 +++-------- ikabot/helpers/planRoutes.py | 6 ++-- ikabot/helpers/resources.py | 2 +- tests/function/test_distributeResources.py | 32 +++++++++++----------- 18 files changed, 73 insertions(+), 79 deletions(-) diff --git a/ikabot/config.py b/ikabot/config.py index 88469fd4..1b63fcea 100644 --- a/ikabot/config.py +++ b/ikabot/config.py @@ -65,3 +65,6 @@ class logLevels: debugON_constructionList = False debugON_buyResources = False debugON_activateMiracle = False + +MAXIMUM_CITY_NAME_LENGTH = 20 +SECONDS_IN_HOUR = 60 * 60 diff --git a/ikabot/function/alertLowWine.py b/ikabot/function/alertLowWine.py index 3bacb693..0246c9ad 100644 --- a/ikabot/function/alertLowWine.py +++ b/ikabot/function/alertLowWine.py @@ -84,12 +84,11 @@ def do_it(session, hours): if 'tavern' not in [building['building'] for building in city['position']]: continue - consumption_per_hour = city['consumo'] + consumption_per_hour = city['wineConsumptionPerHour'] # is a wine city if cities[cityId]['tradegood'] == '1': - wine_production = getProductionPerSecond(session, cityId)[1] - wine_production = wine_production * 60 * 60 + wine_production = getProductionPerSecond(session, cityId)[1] * SECONDS_IN_HOUR if consumption_per_hour > wine_production: consumption_per_hour -= wine_production else: @@ -97,7 +96,7 @@ def do_it(session, hours): continue consumption_per_seg = Decimal(consumption_per_hour) / Decimal(3600) - wine_available = city['recursos'][1] + wine_available = city['availableResources'][1] if consumption_per_seg == 0: if was_alerted[cityId] is False: diff --git a/ikabot/function/constructionList.py b/ikabot/function/constructionList.py index 2d1b17d6..04b1830b 100644 --- a/ikabot/function/constructionList.py +++ b/ikabot/function/constructionList.py @@ -305,7 +305,7 @@ def sendResourcesNeeded(session, destination_city_id, city_origins, missing_reso if missing == 0: break - available = cityOrigin['recursos'][i] + available = cityOrigin['availableResources'][i] send = min(available, missing) missing -= send toSend = [0] * len(materials_names) @@ -350,7 +350,7 @@ def chooseResourceProviders(session, cities_ids, cities, city_id, resource, miss html = session.get(city_url + cityId) city = getCity(html) - available = city['recursos'][resource] + available = city['availableResources'][resource] if available == 0: continue @@ -541,8 +541,8 @@ def constructionList(session, event, stdin_fd, predetermined_input): # calculate the resources that are missing missing = [0] * len(materials_names) for i in range(len(materials_names)): - if city['recursos'][i] < resourcesNeeded[i]: - missing[i] = resourcesNeeded[i] - city['recursos'][i] + if city['availableResources'][i] < resourcesNeeded[i]: + missing[i] = resourcesNeeded[i] - city['availableResources'][i] # show missing resources to the user if sum(missing) > 0: diff --git a/ikabot/function/distributeResources.py b/ikabot/function/distributeResources.py index a57d5ce9..e5faf2ef 100644 --- a/ikabot/function/distributeResources.py +++ b/ikabot/function/distributeResources.py @@ -108,7 +108,7 @@ def distribute_evenly(session, resource_type): html = session.get(city_url + cityID) # load html from the get request for that particular city city = getCity(html) # convert the html to a city object - resourceTotal += city['recursos'][resource_type] # the cities resources are added to the total + resourceTotal += city['availableResources'][resource_type] # the cities resources are added to the total allCities[cityID] = city # adds the city to all cities # if a city doesn't have enough storage to fit resourceAverage @@ -133,10 +133,10 @@ def distribute_evenly(session, resource_type): for cityID in allCities: if cityID in destinationCities: continue - if allCities[cityID]['recursos'][resource_type] > resourceAverage: - originCities[cityID] = allCities[cityID]['recursos'][resource_type] - resourceAverage + if allCities[cityID]['availableResources'][resource_type] > resourceAverage: + originCities[cityID] = allCities[cityID]['availableResources'][resource_type] - resourceAverage else: - destinationCities[cityID] = resourceAverage - allCities[cityID]['recursos'][resource_type] + destinationCities[cityID] = resourceAverage - allCities[cityID]['availableResources'][resource_type] break originCities = {k: v for k, v in sorted(originCities.items(), key=lambda item: item[1], reverse=True)} # sort origin cities in descending order @@ -191,9 +191,9 @@ def distribute_unevenly(session, resource_type): html = session.get(city_url + destination_city_id) city = getCity(html) if resource_type == 1: # wine - city['available_amount_of_resource'] = city['recursos'][resource_type] - city['consumo'] - 1 + city['available_amount_of_resource'] = city['availableResources'][resource_type] - city['wineConsumptionPerHour'] - 1 else: - city['available_amount_of_resource'] = city['recursos'][resource_type] + city['available_amount_of_resource'] = city['availableResources'][resource_type] if city['available_amount_of_resource'] < 0: city['available_amount_of_resource'] = 0 total_available_resources_from_all_cities += city['available_amount_of_resource'] diff --git a/ikabot/function/donate.py b/ikabot/function/donate.py index 786472a5..b6c192ce 100644 --- a/ikabot/function/donate.py +++ b/ikabot/function/donate.py @@ -32,7 +32,7 @@ def donate(session, event, stdin_fd, predetermined_input): city = chooseCity(session) banner() - woodAvailable = city['recursos'][0] + woodAvailable = city['availableResources'][0] islandId = city['islandId'] html = session.get(island_url + islandId) diff --git a/ikabot/function/donationBot.py b/ikabot/function/donationBot.py index 1affe0f5..b6de1aee 100644 --- a/ikabot/function/donationBot.py +++ b/ikabot/function/donationBot.py @@ -132,7 +132,7 @@ def do_it(session, cities_ids, cities_dict, waiting_time, max_random_waiting_tim # get the storageCapacity and the wood this city has html = session.get(city_url + cityId) city = getCity(html) - wood = city['recursos'][0] + wood = city['availableResources'][0] storageCapacity = city['storageCapacity'] # get the percentage diff --git a/ikabot/function/dumpWorld.py b/ikabot/function/dumpWorld.py index 26cc65e7..e47ebdd2 100644 --- a/ikabot/function/dumpWorld.py +++ b/ikabot/function/dumpWorld.py @@ -315,7 +315,7 @@ def view_dump(session, event): players = [] for island in selected_dump['islands']: for city in island['cities']: - if city['type'] != 'empty' and player_name in city['Name']: + if city['type'] != 'empty' and player_name in city['ownerName']: players.append((player_name, island['id'])) # return if none are found if not len(players): @@ -344,9 +344,9 @@ def view_dump(session, event): print('The nearest 25 inactive players are: ') #below follows the unholiest way to get the first n cities which are contained in an island object which is contained in a list of islands without duplicates in one line of code using python list comprehension seen = set() - inactives = [city for island in islands_sorted for city in island['cities'] if city['type'] != 'empty' and city['state'] == 'inactive' and isinstance([(seen.add(city['Name']),) if city['Name'] not in seen else None][0],tuple)][:number_of_inactives] + inactives = [city for island in islands_sorted for city in island['cities'] if city['type'] != 'empty' and city['state'] == 'inactive' and isinstance([(seen.add(city['ownerName']),) if city['ownerName'] not in seen else None][0],tuple)][:number_of_inactives] for i, city in enumerate(inactives): - print(str(i+1) + ') ' + city['Name']) + print(str(i+1) + ') ' + city['ownerName']) enter() diff --git a/ikabot/function/getStatus.py b/ikabot/function/getStatus.py index 131f7aa2..3b3b8eb0 100644 --- a/ikabot/function/getStatus.py +++ b/ikabot/function/getStatus.py @@ -96,7 +96,7 @@ def getStatus(session, event, stdin_fd, predetermined_input): (wood, good, typeGood) = getProductionPerSecond(session, city['id']) print('\033[1m{}{}{}'.format(color_arr[int(typeGood)], city['cityName'], color_arr[0])) - resources = city['recursos'] + resources = city['availableResources'] storageCapacity = city['storageCapacity'] color_resources = [] for i in range(len(materials_names)): @@ -117,7 +117,7 @@ def getStatus(session, event, stdin_fd, predetermined_input): hasTavern = 'tavern' in [building['building'] for building in city['position']] if hasTavern: - consumption_per_hour = city['consumo'] + consumption_per_hour = city['wineConsumptionPerHour'] if consumption_per_hour == 0: print(_('{}{}Does not consume wine!{}').format(bcolors.RED, bcolors.BOLD, bcolors.ENDC)) else: diff --git a/ikabot/function/investigate.py b/ikabot/function/investigate.py index 2ba0bc75..8c457860 100644 --- a/ikabot/function/investigate.py +++ b/ikabot/function/investigate.py @@ -119,7 +119,7 @@ def investigate(session, event, stdin_fd, predetermined_input): banner() print('Pick city: ') city = chooseCity(session) - total_glass = int(city['recursos'][3]) + total_glass = int(city['availableResources'][3]) # Check if enough glass if (total_glass < 300000 ): diff --git a/ikabot/function/searchForIslandSpaces.py b/ikabot/function/searchForIslandSpaces.py index 57bcb446..c2765172 100644 --- a/ikabot/function/searchForIslandSpaces.py +++ b/ikabot/function/searchForIslandSpaces.py @@ -126,24 +126,24 @@ def do_it(session, islandList, time, fights): for city_before in cities_before: if city_before['id'] not in [city_now['id'] for city_now in cities_now]: # we didn't find the city_before in the cities_now - msg = _('The city {} of the player {} disappeared in {} {}:{} {}').format(city_before['name'], city_before['Name'], materials_names[int(island['tradegood'])], island['x'], island['y'], island['name']) + msg = _('The city {} of the player {} disappeared in {} {}:{} {}').format(city_before['name'], city_before['ownerName'], materials_names[int(island['tradegood'])], island['x'], island['y'], island['name']) sendToBot(session, msg) if fights.lower() == 'y': for city_now in cities_now: if city_now['id'] == city_before['id']: if 'infos' in city_now and 'infos' not in city_before and 'armyAction' in city_now['infos'] and city_now['infos']['armyAction'] == 'fight': - msg = _('A fight started in the city {} of the player {} on island {} {}:{} {}').format(city_before['name'], city_before['Name'], materials_names[int(island['tradegood'])], island['x'], island['y'], island['name']) + msg = _('A fight started in the city {} of the player {} on island {} {}:{} {}').format(city_before['name'], city_before['ownerName'], materials_names[int(island['tradegood'])], island['x'], island['y'], island['name']) sendToBot(session, msg) if 'infos' not in city_now and 'infos' in city_before and 'armyAction' in city_before['infos'] and city_before['infos']['armyAction'] == 'fight': - msg = _('A fight stopped in the city {} of the player {} on island {} {}:{} {}').format(city_before['name'], city_before['Name'], materials_names[int(island['tradegood'])], island['x'], island['y'], island['name']) + msg = _('A fight stopped in the city {} of the player {} on island {} {}:{} {}').format(city_before['name'], city_before['ownerName'], materials_names[int(island['tradegood'])], island['x'], island['y'], island['name']) sendToBot(session, msg) # someone colonised for city_now in cities_now: if city_now['id'] not in [city_before['id'] for city_before in cities_before]: # we didn't find the city_now in the cities_before - msg = _('Player {} created a new city {} in {} {}:{} {}').format(city_now['Name'], city_now['name'], materials_names[int(island['tradegood'])], island['x'], island['y'], island['name']) + msg = _('Player {} created a new city {} in {} {}:{} {}').format(city_now['ownerName'], city_now['name'], materials_names[int(island['tradegood'])], island['x'], island['y'], island['name']) sendToBot(session, msg) cities_before_per_island[islandId] = cities_now.copy() # update cities_before_per_island for the current island diff --git a/ikabot/function/sellResources.py b/ikabot/function/sellResources.py index c614bdb6..15dfc6f3 100644 --- a/ikabot/function/sellResources.py +++ b/ikabot/function/sellResources.py @@ -119,7 +119,7 @@ def sellToOffers(session, city_to_buy_from, resource_type, event): event.set() return - available = city_to_buy_from['recursos'][resource_type] + available = city_to_buy_from['availableResources'][resource_type] amount_to_sell = min(available, total_amount) banner() @@ -173,7 +173,7 @@ def createOffer(session, my_offering_market_city, resource_type, event): html = getMarketInfo(session, my_offering_market_city) sell_market_capacity = storageCapacityOfMarket(html) - total_available_amount_of_resource = my_offering_market_city['recursos'][resource_type] + total_available_amount_of_resource = my_offering_market_city['availableResources'][resource_type] print(_('How much do you want to sell? [max = {}]').format(addThousandSeparator(total_available_amount_of_resource))) amount_to_sell = read(min=0, max=total_available_amount_of_resource) diff --git a/ikabot/function/sendResources.py b/ikabot/function/sendResources.py index 9cbc306f..b300de39 100644 --- a/ikabot/function/sendResources.py +++ b/ikabot/function/sendResources.py @@ -54,7 +54,7 @@ def sendResources(session, event, stdin_fd, predetermined_input): if cityO['id'] == cityD['id']: continue - resources_left = cityO['recursos'] + resources_left = cityO['availableResources'] for route in routes: (origin_city, destination_city, __, *toSend) = route if origin_city['id'] == cityO['id']: @@ -62,13 +62,13 @@ def sendResources(session, event, stdin_fd, predetermined_input): resources_left[i] -= toSend[i] # the destination city might be from another player - if cityD['propia'] and destination_city['id'] == cityD['id']: + if cityD['isOwnCity'] and destination_city['id'] == cityD['id']: for i in range(len(materials_names)): cityD['freeSpaceForResources'][i] -= toSend[i] banner() # the destination city might be from another player - if cityD['propia']: + if cityD['isOwnCity']: msg = '' for i in range(len(materials_names)): if resources_left[i] > cityD['freeSpaceForResources'][i]: diff --git a/ikabot/function/trainArmy.py b/ikabot/function/trainArmy.py index 9cfc482b..3b54479a 100644 --- a/ikabot/function/trainArmy.py +++ b/ikabot/function/trainArmy.py @@ -102,8 +102,8 @@ def planTrainings(session, city, trainings, trainTroops): city = getCity(html) city['pos'] = buildingPos - resourcesAvailable = city['recursos'].copy() - resourcesAvailable.append(city['ciudadanosDisp']) + resourcesAvailable = city['availableResources'].copy() + resourcesAvailable.append(city['freeCitizens']) # for each unit type in training for unit in training: @@ -319,8 +319,8 @@ def trainArmy(session, event, stdin_fd, predetermined_input): cityTrainings.append(cityId) # calculate if the city has enough resources - resourcesAvailable = city['recursos'].copy() - resourcesAvailable.append(city['ciudadanosDisp']) + resourcesAvailable = city['availableResources'].copy() + resourcesAvailable.append(city['freeCitizens']) for training in tranings: for unit in training: diff --git a/ikabot/helpers/getJson.py b/ikabot/helpers/getJson.py index d79b3c29..3d0149bc 100644 --- a/ikabot/helpers/getJson.py +++ b/ikabot/helpers/getJson.py @@ -19,12 +19,12 @@ def getFreeCitizens(html): freeCitizens : int an integer representing the amount of free citizens in the given city. """ - ciudadanosDisp = re.search(r'js_GlobalMenu_citizens">(.*?)', html).group(1) - return int(ciudadanosDisp.replace(',', '').replace('.', '')) + freeCitizens = re.search(r'js_GlobalMenu_citizens">(.*?)', html).group(1) + return int(freeCitizens.replace(',', '').replace('.', '')) -def onSale(html): - """This function is used in the ``getCity`` function to determine the amount of each resource which is on sale in the branch office +def getResourcesListedForSale(html): + """This function is used in the ``getCity`` function to determine the amount of each resource which is listed for sale in the branch office Parameters ---------- html : str @@ -86,8 +86,8 @@ def getCity(html): city = re.search(r'"updateBackgroundData",\s?([\s\S]*?)\],\["updateTemplateData"', html).group(1) city = json.loads(city, strict=False) - city['Id'] = city.pop('ownerId') - city['Name'] = decodeUnicodeEscape(city.pop('ownerName')) + city['ownerId'] = city.pop('ownerId') + city['ownerName'] = decodeUnicodeEscape(city.pop('ownerName')) city['x'] = int(city.pop('islandXCoord')) city['y'] = int(city.pop('islandYCoord')) city['cityName'] = decodeUnicodeEscape(city['name']) @@ -108,14 +108,14 @@ def getCity(html): position['building'] = 'empty' city['id'] = str(city['id']) - city['propia'] = True - city['recursos'] = getAvailableResources(html, num=True) + city['isOwnCity'] = True + city['availableResources'] = getAvailableResources(html, num=True) city['storageCapacity'] = getWarehouseCapacity(html) - city['ciudadanosDisp'] = getFreeCitizens(html) - city['consumo'] = getWineConsumption(html) - city['enventa'] = onSale(html) + city['freeCitizens'] = getFreeCitizens(html) + city['wineConsumptionPerHour'] = getWineConsumptionPerHour(html) + city['resourcesListedForSale'] = getResourcesListedForSale(html) city['freeSpaceForResources'] = [] for i in range(5): - city['freeSpaceForResources'].append(city['storageCapacity'] - city['recursos'][i] - city['enventa'][i]) + city['freeSpaceForResources'].append(city['storageCapacity'] - city['availableResources'][i] - city['resourcesListedForSale'][i]) return city diff --git a/ikabot/helpers/pedirInfo.py b/ikabot/helpers/pedirInfo.py index 308684b9..f701c1b9 100644 --- a/ikabot/helpers/pedirInfo.py +++ b/ikabot/helpers/pedirInfo.py @@ -168,22 +168,14 @@ def chooseForeignCity(session): return chooseCity(session, foreign=True) html = session.get(island_url + island_id) island = getIsland(html) - longest_city_name_length = 0 - for city in island['cities']: - if city['type'] == 'city': - city_name_length = len(city['name']) - if city_name_length > longest_city_name_length: - longest_city_name_length = city_name_length - def pad(name): - return ' ' * (longest_city_name_length - len(name) + 2) i = 0 city_options = [] for city in island['cities']: - if city['type'] == 'city' and city['state'] == '' and city['Name'] != session.username: + if city['type'] == 'city' and city['state'] == '' and city['ownerName'] != session.username: i += 1 num = ' ' + str(i) if i < 10 else str(i) - print('{}: {}{}({})'.format(num, city['name'], pad(city['name']), city['Name'])) + print('{: >2}: {: >{max_city_name_length}} ({})'.format(num, decodeUnicodeEscape(city['name']), decodeUnicodeEscape(city['Name']), max_city_name_length=MAXIMUM_CITY_NAME_LENGTH)) city_options.append(city) if i == 0: print(_('There are no cities where to send resources on this island')) @@ -192,8 +184,8 @@ def pad(name): selected_city_index = read(min=1, max=i) city = city_options[selected_city_index - 1] city['islandId'] = island['id'] - city['cityName'] = city['name'] - city['propia'] = False + city['cityName'] = decodeUnicodeEscape(city['name']) + city['isOwnCity'] = False return city diff --git a/ikabot/helpers/planRoutes.py b/ikabot/helpers/planRoutes.py index fe6bde07..b17fe553 100644 --- a/ikabot/helpers/planRoutes.py +++ b/ikabot/helpers/planRoutes.py @@ -80,7 +80,7 @@ def sendGoods(session, originCityId, destinationCityId, islandId, ships, send): # add amounts of resources to send for i in range(len(send)): - if city['recursos'][i] > 0: + if city['availableResources'][i] > 0: key = 'cargo_resource' if i == 0 else 'cargo_tradegood{:d}'.format(i) data[key] = send[i] @@ -122,10 +122,10 @@ def executeRoutes(session, routes): send = [] for i in range(len(toSend)): if foreign is False: - min_val = min(origin_city['recursos'][i], toSend[i], storageCapacityInShips, + min_val = min(origin_city['availableResources'][i], toSend[i], storageCapacityInShips, storageCapacityInCity[i]) else: - min_val = min(origin_city['recursos'][i], toSend[i], storageCapacityInShips) + min_val = min(origin_city['availableResources'][i], toSend[i], storageCapacityInShips) send.append(min_val) storageCapacityInShips -= send[i] toSend[i] -= send[i] diff --git a/ikabot/helpers/resources.py b/ikabot/helpers/resources.py index 2a1f8017..b78d04c0 100644 --- a/ikabot/helpers/resources.py +++ b/ikabot/helpers/resources.py @@ -39,7 +39,7 @@ def getWarehouseCapacity(html): return int(capacity) -def getWineConsumption(html): +def getWineConsumptionPerHour(html): """ Parameters ---------- diff --git a/tests/function/test_distributeResources.py b/tests/function/test_distributeResources.py index 798eeafe..49498b06 100644 --- a/tests/function/test_distributeResources.py +++ b/tests/function/test_distributeResources.py @@ -31,12 +31,12 @@ def cities(): "y": "1", "cityName": "City with wine", "id": "1", - "propia": True, - "recursos": [100, 800, 300, 400, 500], + "isOwnCity": True, + "availableResources": [100, 800, 300, 400, 500], "storageCapacity": 1000, - "ciudadanosDisp": 10, - "consumo": 10, - "enventa": [0, 0, 0, 0, 0], + "freeCitizens": 10, + "wineConsumptionPerHour": 10, + "resourcesListedForSale": [0, 0, 0, 0, 0], "freeSpaceForResources": [], "islandId": "100", } @@ -47,12 +47,12 @@ def cities(): "y": "2", "cityName": "City #2", "id": "2", - "propia": True, - "recursos": [100, 200, 300, 400, 500], + "isOwnCity": True, + "availableResources": [100, 200, 300, 400, 500], "storageCapacity": 1000, - "ciudadanosDisp": 10, - "consumo": 10, - "enventa": [0, 0, 0, 0, 0], + "freeCitizens": 10, + "wineConsumptionPerHour": 10, + "resourcesListedForSale": [0, 0, 0, 0, 0], "freeSpaceForResources": [], "islandId": "200", } @@ -63,12 +63,12 @@ def cities(): "y": "3", "cityName": "City #3", "id": "3", - "propia": True, - "recursos": [100, 200, 300, 400, 500], + "isOwnCity": True, + "availableResources": [100, 200, 300, 400, 500], "storageCapacity": 1000, - "ciudadanosDisp": 10, - "consumo": 10, - "enventa": [0, 0, 0, 0, 0], + "freeCitizens": 10, + "wineConsumptionPerHour": 10, + "resourcesListedForSale": [0, 0, 0, 0, 0], "freeSpaceForResources": [], "islandId": "300", } @@ -80,7 +80,7 @@ def cities(): ] for city in cities: for i in range(5): - city['freeSpaceForResources'].append(city['storageCapacity'] - city['recursos'][i] - city['enventa'][i]), + city['freeSpaceForResources'].append(city['storageCapacity'] - city['availableResources'][i] - city['resourcesListedForSale'][i]), return cities