Files
aoe2-resource-simulator/aoe/world.py
2026-11-15 16:53:13 -05:00

639 lines
22 KiB
Python

from collections import defaultdict, Counter
from aoe.exceptions import *
from aoe.costs import *
from aoe.dependencies import *
from aoe.gather import *
from aoe.housing import *
from aoe.production import *
from aoe.research import *
from aoe.times import *
from aoe.types import *
class World():
# Creating a unit is split into three stages:
# queuing the unit
# building the unit
# adding the unit to the world
#
# Before queuing a thing, we:
# check its dependencies (research, age, etc.)
# pay its cost
# Once a thing is queued, it waits to be built.
#
# Before building a thing, we
# check for housing capacity
# check for available production buildings
# Once a thing is building, it waits to be added.
#
# We assume for now that anything that has built can be added.
#
# Note: queuing a unit is itself an event that gets added to the queue,
# and, if executed successfully, it adds another event to the queue that
# actually adds the unit to the world
# For now, we assume just 1 villager can work a farm at a time.
# This shouldn't be a huge deal to change later.
# We also assume that a player makes optimal choices about farms --
# villagers are removed from farms with the lowest capacity first and added
# to farms with the highest capacity.
# We keep track of only the closest upcoming farm deletion.
# Note: If you move away a builder while building is in progress, it will
# not slow down or stop the building. I do not plan to change this, so
# don't manually move workers away from build tasks if you want accurate
# results. Similarly, adding builders in the middle of building something
# is not supported
# TODO allow automation:
# reseeding of farms
# possibly other things
MAX_WORLD_TIME = 3*60*60 # 3 hours
POPULATION_CAP = 200
def pay_cost(self, thing):
cost = self.costs.compute_cost(thing)
self.gather.spend_resources(cost)
def market_buy(self, resource, amount):
self._use_market(resource, amount, buy=True)
def market_sell(self, resource, amount):
self._use_market(resource, amount, buy=False)
def _use_market(self, resource, amount, buy=True):
if Buildings.MARKET not in self.buildings:
raise MissingDependencyException
if amount % self.costs.market_transaction_amount != 0:
raise InvalidMarketAmountException
for i in range(amount//self.costs.market_transaction_amount):
cost = self.costs.compute_market_price(resource, buy=buy)
gold_amount = [0, 0, cost, 0]
resource_amount = [0, 0, 0, 0]
resource_amount[int(resource)] = self.costs.market_transaction_amount
if buy:
self.gather.spend_resources(gold_amount)
self.gather.acquire_resources_without_gather(resource_amount)
else:
self.gather.spend_resources(resource_amount)
self.gather.acquire_resources_without_gather(gold_amount)
self.costs.adjust_market_price(resource, buy=buy)
def has_building(self, building):
return building in self.buildings
def _remove_event_at_time(self, removed_event, scheduled_time):
if not scheduled_time:
return
for i, event in enumerate(self.events[scheduled_time]):
if event[0] == removed_event:
del self.events[scheduled_time][i]
break
def _schedule_next_gather_rate_decrease(self, task):
if task in [Tasks.IDLE,
Tasks.BUILD,
Tasks.LURE,
Tasks.FISH_SHIP_IDLE,
Tasks.FISH_SHIP_BUILD]:
return
# remove old decrease
self._remove_event_at_time(self._decrease_gather_rate_by_overuse,
self.rate_decrease_event_times[task])
next_decrease = self.gather.compute_next_gather_rate_decrease(task,
self.villager_tasks[task])
if next_decrease is not None:
next_decrease += self.current_time
if task in Gather.FARM_LIKE_TASKS:
self.events[next_decrease].append((self._remove_consumable_building,
(task,),
{}))
else:
self.events[next_decrease].append((self._decrease_gather_rate_by_overuse,
(task,),
{}))
self.rate_decrease_event_times[task] = next_decrease
def _decrease_gather_rate_by_overuse(self, task):
new_rate = self.gather.decrease_gather_rate_by_overuse(task)
if new_rate > 0:
self._schedule_next_gather_rate_decrease(task)
else:
self.assign_villager(task, Tasks.IDLE, self.villager_tasks[task])
def _improve_gather_rate_by_building(self, building, tasks):
tasks_improved = self.gather.improve_gather_rate_by_building(building,
tasks)
for task in tasks_improved:
self._schedule_next_gather_rate_decrease(task)
def permanently_modify_gather_rate(self, task, multiplier):
self.gather.permanently_modify_gather_rate(task, multiplier)
self._schedule_next_gather_rate_decrease(task)
def permanently_modify_farm_capacity(self, increase):
self._permanently_modify_consumable_capacity(Buildings.FARM,
Tasks.FARM,
increase)
def _permanently_modify_consumable_capacity(self, building, task, increase):
self.gather.permanently_modify_consumable_capacity(building, increase)
self._schedule_next_gather_rate_decrease(task)
def lure_huntable_with_villager(self, previous_task, walking_time=30):
update_time = self.current_time + walking_time
self.events[update_time].append((self._add_huntable, (), {}))
self.assign_villager(previous_task, Tasks.LURE)
def _add_huntable(self):
self.gather.add_huntable()
self.assign_villager(Tasks.LURE, Tasks.BOAR)
def assign_villager(self, previous_task, new_task, count=1):
# new_task of None means kill the villager
# villager_tasks must be modified only in this function
# if it is changed elsewhere, the rate-decrease schedule will be wrong
if self.villager_tasks[previous_task] < count:
raise IllegalVillagerMoveException
self._check_single_villager_move(previous_task, new_task)
if new_task:
self.gather.check_gather(self, new_task, count)
self.villager_tasks[new_task] += count
else:
self.villagers -= 1
self.villager_tasks[previous_task] -= count
if previous_task in Gather.FARM_LIKE_TASKS:
self.gather.stop_using_consumable_buildings(previous_task, count)
if new_task in Gather.FARM_LIKE_TASKS:
self.gather.start_using_consumable_buildings(new_task, count)
self._schedule_next_gather_rate_decrease(previous_task)
if new_task:
self._schedule_next_gather_rate_decrease(new_task)
def _check_valid_builders(self, villagers_from, building):
# If building a fishtrap, at least one builder needs to be a fishing
# ship. If building anything else, no builders can be fishing ships
fish_builder = any([v in Gather.FISHING_TASKS for v in villagers_from])
building_fishtrap = (building == Buildings.FISHTRAP)
if fish_builder != building_fishtrap:
raise IllegalVillagerMoveException
def _check_single_villager_move(self, villager_from, villager_to):
for v in [villager_from, villager_to]:
if v in Gather.NON_ASSIGNABLE_TASKS:
raise IllegalVillagerMoveException
from_fishing = (villager_from in Gather.FISHING_TASKS)
to_fishing = (villager_to in Gather.FISHING_TASKS)
if from_fishing != to_fishing:
raise IllegalVillagerMoveException
def _check_villager_move(self,
villagers_from_count,
villagers_from,
villagers_to):
for task, count in villagers_from_count.items():
if self.villager_tasks[task] < count:
raise IllegalVillagerMoveException
for v_from, v_to in zip(villagers_from, villagers_to):
self._check_single_villager_move(v_from, v_to)
def _move_villagers_to_build(self, villagers_from_count):
for task, count in villagers_from_count.items():
build_task = self._get_build_task_from_task(task)
self.assign_villager(task, build_task, count)
def _get_house_check_function(self):
if self.housed_is_error:
house_check = self.housing.check_housing
else:
house_check = self.housing.check_housing_safe
return house_check
def _get_build_task_from_task(self, task):
if task in Gather.FISHING_TASKS:
return Tasks.FISH_SHIP_BUILD
else:
return Tasks.BUILD
def get_relic(self, walking_time=60):
if self.villager_tasks[Tasks.MONK_IDLE] < 1:
self.relics_waiting_for_monk.append(walking_time)
return
self.villager_tasks[Tasks.MONK_IDLE] -= 1
self.villager_tasks[Tasks.MONK_GET_RELIC] += 1
update_time = self.current_time + walking_time
self.events[update_time].append((self._add_relic, (), {}))
def _add_relic(self):
self.villager_tasks[Tasks.MONK_IDLE] += 1
self.villager_tasks[Tasks.MONK_GET_RELIC] -= 1
self.villager_tasks[Tasks.RELIC] += 1
self._get_next_waiting_relic()
def _get_next_waiting_relic(self):
if len(self.relics_waiting_for_monk) > 0:
walking_time = self.relics_waiting_for_monk.pop()
self.get_relic(walking_time)
def build(self, building, villagers_from, villagers_to, building_tasks=None):
if type(villagers_from) == Tasks:
villagers_from = [villagers_from]
if type(villagers_to) == Tasks:
villagers_to = [villagers_to]
if len(villagers_from) != len(villagers_to):
raise ConservationOfVillagersException
villagers_from_count = Counter(villagers_from)
self._check_villager_move(villagers_from_count,
villagers_from,
villagers_to)
self._check_valid_builders(villagers_from, building)
self.dependencies.check_dependencies(self, building)
self.pay_cost(building)
self._move_villagers_to_build(villagers_from_count)
villagers_to_count = Counter(villagers_to)
num_builders = len(villagers_from)
build_time = self.build_times.compute_build_time(building, num_builders)
update_time = self.current_time + build_time
self.events[update_time].append((self._add_building,
(building,
villagers_to_count,
building_tasks,),
{}))
def _add_building(self, building, villagers_to, tasks_improved):
self.buildings.append(building)
self._free_production_building(building)
if building == Buildings.HOUSE:
self._free_housing()
if building in Gather.FARM_LIKE_BUILDINGS:
self.gather.add_consumable_building(building)
else:
self._improve_gather_rate_by_building(building, tasks_improved)
for task, count in villagers_to.items():
build_task = self._get_build_task_from_task(task)
self.assign_villager(build_task, task, count)
def _remove_consumable_building(self, task):
match task:
case Tasks.FARM:
building = Buildings.FARM
next_task = Tasks.IDLE
case Tasks.FISH_SHIP_TRAP:
building = Buildings.FISHTRAP
next_task = Tasks.FISH_SHIP_DEEP
case _:
raise NotFarmEquivalentException
self.buildings.remove(building)
self.gather.remove_consumable_building(building)
num_working_buildings = self.gather.get_num_working_consumable_buildings(task)
if self.villager_tasks[task] > num_working_buildings:
self.assign_villager(task, next_task)
def advance_by_time(self, duration):
self._run_clock_until_time(self.time + duration)
def advance_until_time(self, end_time):
self._run_clock_until_time(end_time)
def _get_next_event_time(self):
try:
next_event_time = min(self.events.keys())
except ValueError:
next_event_time = World.MAX_WORLD_TIME
return next_event_time
def _run_clock_without_events(self, end_time):
duration = end_time - self.current_time
gathered = self.gather.gather_resources_for_duration(self.villager_tasks,
duration)
self.current_time = end_time
def _run_clock_until_time(self, end_time):
while self.current_time < end_time:
next_event_time = self._get_next_event_time()
self._run_clock_without_events(min(next_event_time, end_time))
self._handle_events()
def set_housed_is_error(self, is_error=True):
self.housed_is_error = is_error
def get_population_space(self):
space = sum([self.housing.space[building] for building in self.buildings])
return min(space, World.POPULATION_CAP)
def get_effective_population(self):
return self.population + self.units_being_built
def _free_housing(self):
pop_space = self.get_population_space()
house_check = self._get_house_check_function()
i = 0
while (self.get_effective_population() < pop_space and
i < len(self.production_queue)):
thing, task = self.production_queue[i]
if house_check(self, thing) and \
self.production.check_production_safe(self, thing):
self._start_producing(thing, task)
del self.production_queue[i]
else:
i += 1
def _free_production_building_of_thing(self, thing, **kwargs):
building = self.production.building[thing]
self._free_production_building(building)
def _free_production_building(self, building, **kwargs):
# This will not respect the order of a queue in a particular building.
# For example, if there is a TC with the queue [villager, loom] and
# there is no available housing, the TC will research loom. In the
# actual game, the villager would block the researching of loom.
# There is no easy way around this as long as we are treating the
# production queue as a shared pool, and I don't really care.
self.production_available[building] += 1
house_check = self._get_house_check_function()
i = 0
while i < len(self.production_queue):
thing, task, kwargs = self.production_queue[i]
if self.production.building[thing] == building and \
house_check(self, thing):
self._start_producing(thing, task, **kwargs)
del self.production_queue[i]
break
i += 1
def _use_housing_and_production(self, thing):
self.production.check_production(self, thing)
self.housing.check_housing(self, thing)
building = self.production.building[thing]
if building is not None:
self.production_available[building] -= 1
self.units_being_built += self.housing.required[thing]
def _kill_unit(self, unit, task=None):
if unit == Units.VILLAGER and not task:
raise IllegalVillagerMoveException
self.population -= self.housing.required[unit]
if unit == Units.VILLAGER:
self.assign_villager(task, None)
self._free_housing()
def _add_thing(self, thing, initial_task, **kwargs):
self.units_being_built -= self.housing.required[thing]
self.population += self.housing.required[thing]
if thing in Research:
self.research.append(thing)
ResearchEffects.complete_research(self, thing)
self._free_production_building_of_thing(thing)
if thing == Units.VILLAGER:
self.villagers += 1
self.villager_tasks[Tasks.IDLE] += 1
if not initial_task:
initial_task = Tasks.IDLE
if initial_task == Tasks.LURE:
self.lure_huntable_with_villager(Tasks.IDLE, **kwargs)
elif initial_task == Tasks.BUILD:
if 'building_task' not in kwargs.keys():
kwargs['building_task'] = None
self.build(kwargs['building'],
Tasks.IDLE,
kwargs['villagers_to'],
kwargs['building_task'])
else:
self.assign_villager(Tasks.IDLE, initial_task)
elif thing == Units.MONK:
self.villager_tasks[Tasks.MONK_IDLE] += 1
self._get_next_waiting_relic()
elif thing == Units.FISHINGSHIP:
if not initial_task:
initial_task = Tasks.FISH_SHIP_IDLE
self.villager_tasks[initial_task] += 1
elif thing == Units.TRADECOG:
self.villager_tasks[Tasks.TRADECOG] += 1
elif thing == Units.TRADECART:
self.villager_tasks[Tasks.TRADECART] += 1
def _start_producing(self, thing, initial_task, **kwargs):
try:
self._use_housing_and_production(thing)
except Exception as e:
is_prod = isinstance(e, ProductionBuildingNotAvailableException)
is_housing = isinstance(e, YallGotHousedException)
if is_prod or (is_housing and not self.housed_is_error):
self.production_queue.append((thing, initial_task, kwargs))
else:
raise(e)
else:
update_time = self.current_time + self.build_times.build_times[thing]
self.events[update_time].append((self._add_thing,
(thing, initial_task,),
kwargs))
def _queue_thing(self, thing, initial_task=None, **kwargs):
self.dependencies.check_dependencies(self, thing)
self.costs.compute_cost(thing)
self.pay_cost(thing)
self._start_producing(thing, initial_task, **kwargs)
def queue_research(self, research):
self._queue_thing(research)
def queue_unit(self, unit):
self._queue_thing(unit)
def queue_villager(self, initial_task, **kwargs):
self._queue_thing(Units.VILLAGER, initial_task, **kwargs)
def queue_fishing_ship(self, initial_task=Tasks.FISH_SHIP_DEEP):
self._queue_thing(Units.FISHINGSHIP, initial_task)
def queue_trade_cog(self):
self._queue_thing(Units.TRADECOG)
def queue_trade_cart(self):
self._queue_thing(Units.TRADECART)
def _handle_events(self):
for func, args, kwargs in self.events[self.current_time]:
try:
func(*args, **kwargs)
except Exception as e:
raise type(e)(
f'Error in {func.__name__}{args}'
f' with keyword arguments {kwargs}'
f' at time {self.current_time}.'
f' Note that the actual gameplay command that caused'
f' the error may not have been issued at'
f' {self.current_time} -- the action may have been'
f' delayed until that time while'
f' waiting in a queue') from e
del self.events[self.current_time]
def _update_age(self, new_age):
self.age = new_age
def increase_age(self):
if self.age == Ages.IMPERIAL:
raise Exception("no.")
new_age = Ages(self.age + 1)
self.dependencies.check_dependencies(self, new_age)
self.pay_cost(new_age)
update_time = self.current_time + self.build_times.build_times[new_age]
self.events[update_time].append((self._update_age, (new_age,), {}))
def _deal_with_civ(self):
pass # deal with any civ-specific changes
def __init__(self, civ=None):
self.civ = civ
self.age = Ages.DARK
self.villagers = 3
self.population = 4
self.research = []
self.buildings = [Buildings.TOWNCENTER]
self.villager_tasks = {t: 0 for t in Tasks}
self.villager_tasks[Tasks.IDLE] = self.villagers
self.rate_decrease_event_times = {t: None for t in Tasks}
self.units_being_built = 0
self.production_available = {b: 0 for b in Buildings}
self.production_available[Buildings.TOWNCENTER] = 1
self.production_queue = []
self.relics_waiting_for_monk = []
self.current_time = 0
self.events = defaultdict(list)
self.build_times = Times()
self.costs = Costs()
self.dependencies = Dependencies()
self.housing = Housing()
self.production = Production()
self.gather = Gather()
self.housed_is_error = True
self._deal_with_civ()