Skip to content

Commit

Permalink
Rename getCity properties to be in English with more descriptive word…
Browse files Browse the repository at this point in the history
…ing (#194)
  • Loading branch information
pecataToshev authored Dec 22, 2023
1 parent 717e1fe commit 8a0ede1
Show file tree
Hide file tree
Showing 18 changed files with 73 additions and 79 deletions.
3 changes: 3 additions & 0 deletions ikabot/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 3 additions & 4 deletions ikabot/function/alertLowWine.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,20 +84,19 @@ 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:
was_alerted[cityId] = False
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:
Expand Down
8 changes: 4 additions & 4 deletions ikabot/function/constructionList.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
12 changes: 6 additions & 6 deletions ikabot/function/distributeResources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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']
Expand Down
2 changes: 1 addition & 1 deletion ikabot/function/donate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion ikabot/function/donationBot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions ikabot/function/dumpWorld.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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()


Expand Down
4 changes: 2 additions & 2 deletions ikabot/function/getStatus.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)):
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion ikabot/function/investigate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ):
Expand Down
8 changes: 4 additions & 4 deletions ikabot/function/searchForIslandSpaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions ikabot/function/sellResources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions ikabot/function/sendResources.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,21 +54,21 @@ 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']:
for i in range(len(materials_names)):
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]:
Expand Down
8 changes: 4 additions & 4 deletions ikabot/function/trainArmy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
24 changes: 12 additions & 12 deletions ikabot/helpers/getJson.py
Original file line number Diff line number Diff line change
Expand Up @@ -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">(.*?)</span>', html).group(1)
return int(ciudadanosDisp.replace(',', '').replace('.', ''))
freeCitizens = re.search(r'js_GlobalMenu_citizens">(.*?)</span>', 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
Expand Down Expand Up @@ -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'])
Expand All @@ -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
16 changes: 4 additions & 12 deletions ikabot/helpers/pedirInfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand All @@ -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


Expand Down
Loading

0 comments on commit 8a0ede1

Please sign in to comment.