Compare commits

...

23 Commits

Author SHA1 Message Date
Nate Bowman
80ebc655de Add non-AI MIT license 2026-11-21 13:55:29 -05:00
Nate Bowman
3f183cdbd5 Fix adding task to work queue 2026-11-17 19:48:47 -05:00
Nate Bowman
dba4974e9f Add tests 2026-11-16 20:11:05 -05:00
Nate Bowman
0780fec1fb Fix bug in housing check and add test 2026-11-16 19:19:26 -05:00
Nate Bowman
1b9266ff09 Allow queuing villagers via task list
This is helpful for testing build orders.
2026-11-15 20:17:31 -05:00
Nate Bowman
3b07e6b3c5 Allow queuing villagers with more complex tasks
For instance, queuing a villager to build several buildings in a row is
now possible. Also adds a task queue for villagers. Any idle villager
will automatically grab the first task in the queue. The task queue is
used to implement the more complex initial villager tasks, so it is
possible that a different villager will do later tasks in the queued
villager's chain of tasks, but only if there are already idle villagers.
As long as the user does not wish to leave villagers idle for a long
time, this should not affect accuracy too badly.
2026-11-15 20:11:07 -05:00
Nate Bowman
2fc6b76db4 Fix floating-point problem
Shame on me for trying to compare floats directly.  I hoped I could get
away with it this once, but I should know better.
2026-11-15 20:11:07 -05:00
Nate Bowman
24a0e9e16b Allow hunting and building as initial tasks in a better way 2026-11-15 17:11:27 -05:00
Nate Bowman
7ce4b4a150 Revert "Allow hunting and building as initial villager tasks"
This reverts commit 8a8effe3d1.
I did not like adding kwargs in so many places, so there will be an
upcoming commit that implements the same change in a different way.
2026-11-15 16:58:49 -05:00
Nate Bowman
8a8effe3d1 Allow hunting and building as initial villager tasks 2026-11-15 16:53:13 -05:00
Nate Bowman
e4aaba0320 Add routine to play until last action 2026-11-15 16:18:29 -05:00
Nate Bowman
e8c6e8eff8 Fix typo in test 2026-11-12 00:55:04 -05:00
Nate Bowman
8865950678 Allow user to choose whether getting housed is an error
Previously, the simulation would automatically end whenever it
determined you were housed.  That is still the default, but the user can
now choose to have the simulation continue instead.  Also, this likely
fixes a bug whereby an error could have been thrown for an unavailable
production building when searching the production queue.
2026-11-12 00:51:32 -05:00
Nate Bowman
20d4f5bd6c Generate better error messages 2026-11-11 23:57:14 -05:00
Nate Bowman
5a5c6e1d3a Add README 2026-11-08 21:32:07 -05:00
Nate Bowman
6680433770 Remove old info from description 2026-11-08 21:19:12 -05:00
Nate Bowman
9ccf25f0ab Require a market to use buying and selling 2026-11-08 21:06:48 -05:00
Nate Bowman
e94af31828 Remove old comments 2026-11-08 21:01:38 -05:00
Nate Bowman
ec8b33ac00 Add ability to automatically queue villagers 2026-11-08 21:00:32 -05:00
Nate Bowman
c02aa3f736 Add warning about builders 2026-11-08 20:55:00 -05:00
Nate Bowman
e03911b78a Modify farm and fishtrap code slightly 2026-11-08 20:51:38 -05:00
Nate Bowman
c6254e6d1e Add fish traps
Also likely fixes bugs in farming and fishing, which were not tested
before
2026-11-08 20:26:38 -05:00
Nate Bowman
5f1999caac Add market transactions 2026-11-07 20:00:07 -05:00
13 changed files with 1304 additions and 145 deletions

31
LICENSE.txt Normal file
View File

@@ -0,0 +1,31 @@
MIT NON-AI License
Copyright (c) 2026, Nathaniel Bowman
Permission is hereby granted, free of charge, to any person obtaining a copy of the software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
In addition, the following restrictions apply:
1. The Software and any modifications made to it may not be used for the purpose of training or improving machine learning algorithms,
including but not limited to artificial intelligence, natural language processing, or data mining. This condition applies to any derivatives,
modifications, or updates based on the Software code. Any usage of the Software in an AI-training dataset is considered a breach of this License.
2. The Software may not be included in any dataset used for training or improving machine learning algorithms,
including but not limited to artificial intelligence, natural language processing, or data mining.
3. Any person or organization found to be in violation of these restrictions will be subject to legal action and may be held liable
for any damages resulting from such use.
4. This software repository contains open-source software licenses that can be modified and used to derive other software licenses.
However, no derivative, modification or update is allowed to remove the licensing conditions that forbid the use of that derivative
for the purpose of training, or improving machine learning algorithms, including but not limited to artificial intelligence,
natural language processing, or data mining.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

28
README.md Normal file
View File

@@ -0,0 +1,28 @@
This is a simulator that produces a timeline of villager production and
resource gathering for Age of Empires 2.
You can see the `tests/test.py` file for examples of how to use it.
The sofware has been lightly verified (i.e., I ran some tests), but it has not
been validated (i.e., I didn't check that it actually matches AoE2 results).
The code tries to keep you from shooting yourself in the foot. It checks
whether you are housed, do not have enough resource to build what you are
trying to build, etc. There are various known limitations, such as the fact
that farming produces food constantly in the simulator, and there are
undoubtably more checks that I forgot to include.
Why would you need this? Well, say you were trying to develop a new build
order. You could play variations out in the game for maximum accuracy. You
could do simple math by hand or in a spreadsheet to quickly get approximate
answers. Or, you could use a Python library you found online that is probably
clunkier and less accurate than both other options! What's not to love?
With a nice GUI, the software might be somewhat usable, but I doubt I will get
around to that.
Enjoy!
# Data source
My thanks to https://ageofempires.fandom.com/wiki

View File

@@ -9,6 +9,26 @@ class Costs():
return self.costs[purchase] return self.costs[purchase]
def compute_market_price(self, resource, buy=True):
rate = self.market_rates[resource]
if buy:
cost = rate*(1 + self.market_fee)
else:
cost = rate*(1 - self.market_fee)
return cost
def adjust_market_price(self, resource, buy=True):
rate = self.market_rates[resource]
if buy:
new_rate = min(self.maximum_market_rate,
rate + self.market_increment_amount)
else:
new_rate = max(self.minimum_market_rate,
rate - self.market_increment_amount)
self.market_rates[resource] = new_rate
def __init__(self): def __init__(self):
self.costs = { self.costs = {
Ages.DARK: (0, 0, 0, 0), Ages.DARK: (0, 0, 0, 0),
@@ -142,3 +162,13 @@ class Costs():
Units.FISHINGSHIP: (0, 75, 0, 0), Units.FISHINGSHIP: (0, 75, 0, 0),
Units.TRADECOG: (0, 100, 50, 0), Units.TRADECOG: (0, 100, 50, 0),
} }
self.market_rates = {
Resources.FOOD: 115,
Resources.WOOD: 100,
Resources.STONE: 130,
}
self.market_fee = 0.3
self.minimum_market_rate = 20
self.maximum_market_rate = 9999
self.market_increment_amount = 2
self.market_transaction_amount = 100

View File

@@ -270,6 +270,6 @@ class Dependencies():
Units.SKIRMISHER: [Ages.FEUDAL, Buildings.ARCHERYRANGE], Units.SKIRMISHER: [Ages.FEUDAL, Buildings.ARCHERYRANGE],
Units.ARCHER: [Ages.FEUDAL, Buildings.ARCHERYRANGE], Units.ARCHER: [Ages.FEUDAL, Buildings.ARCHERYRANGE],
Units.MONK: [Ages.CASTLE, Buildings.MONASTERY], Units.MONK: [Ages.CASTLE, Buildings.MONASTERY],
Units.FISHINGSHIP: [Ages.FEUDAL, Buildings.DOCK], Units.FISHINGSHIP: [Ages.DARK, Buildings.DOCK],
Units.TRADECOG: [Ages.FEUDAL, Buildings.DOCK], Units.TRADECOG: [Ages.FEUDAL, Buildings.DOCK],
} }

View File

@@ -18,6 +18,11 @@ class IllegalVillagerMoveException(Exception):
class InvalidMarketAmountException(Exception):
pass
class MissingDependencyException(Exception): class MissingDependencyException(Exception):
pass pass
@@ -28,6 +33,11 @@ class NotEnoughResourcesException(Exception):
class NotFarmEquivalentException(Exception):
pass
class ProductionBuildingNotAvailableException(Exception): class ProductionBuildingNotAvailableException(Exception):
pass pass

View File

@@ -37,14 +37,53 @@ class Gameplay():
villagers_to,))) villagers_to,)))
def market_buy(self, action_time, resource, amount):
self._check_time(action_time)
self.actions[action_time].append((self.world.market_buy,
(resource, amount)))
def market_sell(self, action_time, resource, amount):
self._check_time(action_time)
self.actions[action_time].append((self.world.market_sell,
(resource, amount)))
def queue_research(self, action_time, research): def queue_research(self, action_time, research):
self._check_time(action_time) self._check_time(action_time)
self.actions[action_time].append((self.world.queue_research, self.actions[action_time].append((self.world.queue_research,
(research,))) (research,)))
def queue_villager(self, action_time, initial_task): def queue_villagers_by_task_list(self, from_time, initial_tasks):
train_time = self.world.build_times.build_times[Units.VILLAGER]
if not isinstance(initial_tasks, list):
initial_tasks = [initial_tasks]
for i in range(len(initial_tasks)):
self.queue_villager(from_time + i*train_time, initial_tasks[i])
def queue_villagers_over_time(self, from_time, until_time, initial_task):
train_time = self.world.build_times.build_times[Units.VILLAGER]
duration = max(0, until_time - from_time)
for i in range(duration//train_time + 1):
self.queue_villager(from_time + i*train_time, initial_task)
def queue_villager(self, action_time, initial_task, **kwargs):
'''
initial_task can be instance of one of the following:
Tasks -- assign this task along with any keyword arguments
(Tasks, dict) -- assume the dict contains the keyword arguments
List of (Tasks, dict) -- several tasks to complete in order, each with
its own keyword arguments
'''
self._check_time(action_time) self._check_time(action_time)
if isinstance(initial_task, Tasks):
initial_task = (initial_task, kwargs)
self.actions[action_time].append((self.world.queue_villager, self.actions[action_time].append((self.world.queue_villager,
(initial_task,))) (initial_task,)))
@@ -76,12 +115,25 @@ class Gameplay():
(old_task, new_task, count,))) (old_task, new_task, count,)))
def add_task_to_work_queue(self, action_time, task, **kwargs):
self._check_time(action_time)
task = (task, kwargs)
self.actions[action_time].append((self.world.add_task_to_work_queue,
(task,)))
def get_relic(self, action_time, walking_time=60): def get_relic(self, action_time, walking_time=60):
self._check_time(action_time) self._check_time(action_time)
self.actions[action_time].append((self.world.get_relic, self.actions[action_time].append((self.world.get_relic,
(walking_time,))) (walking_time,)))
def set_housed_is_error(self, action_time, is_error=True):
self._check_time(action_time)
self.actions[action_time].append((self.world.set_housed_is_error,
(is_error,)))
def lure_huntable_with_villager(self, def lure_huntable_with_villager(self,
action_time, action_time,
previous_task, previous_task,
@@ -97,11 +149,19 @@ class Gameplay():
def _check_time(self, action_time): def _check_time(self, action_time):
# TODO will it work if we do something at current time?
if self.world.current_time > action_time: if self.world.current_time > action_time:
raise CannotChangeThePastException raise CannotChangeThePastException
def _get_last_action_time(self):
try:
last_action_time = max(self.actions.keys())
except ValueError:
last_action_time = self.world.current_time
return last_action_time
def _get_next_action_time(self): def _get_next_action_time(self):
try: try:
next_action_time = min(self.actions.keys()) next_action_time = min(self.actions.keys())
@@ -117,7 +177,12 @@ class Gameplay():
def _handle_actions(self): def _handle_actions(self):
for func, args in self.actions[self.world.current_time]: for func, args in self.actions[self.world.current_time]:
try:
func(*args) func(*args)
except Exception as e:
raise type(e)(
f'Error in {func.__name__}{args}'
f' at time {self.world.current_time}.') from e
del self.actions[self.world.current_time] del self.actions[self.world.current_time]
@@ -129,6 +194,11 @@ class Gameplay():
self._handle_actions() self._handle_actions()
def play_until_last_action(self, extra_time=0):
last_action_time = self._get_last_action_time()
self.play_until(last_action_time + extra_time)
def __init__(self): def __init__(self):
self.world = World() self.world = World()
self.actions = defaultdict(list) self.actions = defaultdict(list)

View File

@@ -139,6 +139,32 @@ class Gather():
BIG_NUMBER = 1e6 BIG_NUMBER = 1e6
NON_ASSIGNABLE_TASKS = [
Tasks.MONK_GET_RELIC,
Tasks.MONK_IDLE,
Tasks.RELIC,
Tasks.TRADECART,
Tasks.TRADECOG,
]
FISHING_TASKS = [
Tasks.FISH_SHIP_IDLE,
Tasks.FISH_SHIP_SHORE,
Tasks.FISH_SHIP_DEEP,
Tasks.FISH_SHIP_BUILD,
Tasks.FISH_SHIP_TRAP,
]
FARM_LIKE_TASKS = [
Tasks.FARM,
Tasks.FISH_SHIP_TRAP,
]
FARM_LIKE_BUILDINGS = [
Buildings.FARM,
Buildings.FISHTRAP,
]
def check_gather(self, world, task, count=1): def check_gather(self, world, task, count=1):
if task in [ if task in [
@@ -146,6 +172,8 @@ class Gather():
Tasks.BUILD, Tasks.BUILD,
Tasks.MONK_IDLE, Tasks.MONK_IDLE,
Tasks.LURE, Tasks.LURE,
Tasks.FISH_SHIP_IDLE,
Tasks.FISH_SHIP_BUILD,
]: ]:
return return
@@ -157,9 +185,10 @@ class Gather():
if not match: if not match:
raise GatherBuildingNotAvailableException raise GatherBuildingNotAvailableException
if task == task.FARM: if task in Gather.FARM_LIKE_TASKS:
if world.villager_tasks[task] + count > len(self.unused_farms): self._check_consumable_gather_building_available(world,
raise GatherBuildingNotAvailableException task,
count)
def spend_resources(self, cost): def spend_resources(self, cost):
@@ -171,6 +200,11 @@ class Gather():
self.resources[i] -= cost[i] self.resources[i] -= cost[i]
def acquire_resources_without_gather(self, gained):
for i in range(len(self.resources)):
self.resources[i] += gained[i]
def permanently_modify_gather_rate(self, task, rate_multiplier): def permanently_modify_gather_rate(self, task, rate_multiplier):
self.gather_rates[task] *= rate_multiplier self.gather_rates[task] *= rate_multiplier
self.original_gather_rates[task] *= rate_multiplier self.original_gather_rates[task] *= rate_multiplier
@@ -188,13 +222,19 @@ class Gather():
rate = self.gather_rates[task] rate = self.gather_rates[task]
decay = self.decay_rates[task] decay = self.decay_rates[task]
if task == Tasks.FARM: if task in Gather.FARM_LIKE_TASKS:
available = self.farms[0] used = self.consumable_buildings[task]['used']
try:
available = used[0]
except IndexError:
# this routine may be called even when there are no active farms
available = 0
villagers = min(villagers, 1) villagers = min(villagers, 1)
else: else:
available = self.gatherable_amounts[task] available = self.gatherable_amounts[task]
if rate == 0 or (villagers == 0 and decay == 0): SMALL_FLOAT = 1e-8
if rate < SMALL_FLOAT or (villagers == 0 and decay == 0):
next_decrease = None next_decrease = None
else: else:
next_decrease = available/(villagers*rate + decay) next_decrease = available/(villagers*rate + decay)
@@ -205,7 +245,7 @@ class Gather():
def improve_gather_rate_by_building(self, building, tasks): def improve_gather_rate_by_building(self, building, tasks):
if building == Buildings.FARM: if building in Gather.FARM_LIKE_TASKS:
raise ValueError('Do not call this routine with a farm') raise ValueError('Do not call this routine with a farm')
if building not in self.buildings_gather_increase.keys(): if building not in self.buildings_gather_increase.keys():
@@ -228,46 +268,74 @@ class Gather():
def permanently_modify_consumable_capacity(self, building, increase): def permanently_modify_consumable_capacity(self, building, increase):
task = self._get_task_from_consumable_building(building)
used, unused = self.consumable_buildings[task].values()
current_initial_capacity = self.buildings_gather_increase[building] current_initial_capacity = self.buildings_gather_increase[building]
self.buildings_gather_increase[building] += increase self.buildings_gather_increase[building] += increase
modifier = increase/current_initial_capacity modifier = increase/current_initial_capacity
if building == Buildings.FARM: for consumable_list in [used, unused]:
used = self.farms for i in range(len(consumable_list)):
unused = self.unused_farms conusmable_list[i] += conusmable_list[i]*multiplier
for i in range(len(used)):
used[i] += used[i]*multiplier
for i in range(len(unused)):
unused[i] += unused[i]*multiplier
def stop_using_farms(self, count): def stop_using_consumable_buildings(self, task, count):
used, unused = self.consumable_buildings[task].values()
# remove villagers from farms with lowest remaining capacity # remove villagers from farms with lowest remaining capacity
try:
for i in range(count): for i in range(count):
heapq.heappush_max(self.unused_farms, heapq.heappush_max(unused, heapq.heappop(used))
heapq.heappop(self.farms)) except IndexError:
# if we are stopping because a building has been used up,
# the building will no longer be in `used`, which is correct
pass
def start_using_farms(self, count): def start_using_consumable_buildings(self, task, count):
used, unused = self.consumable_buildings[task].values()
# add villagers to farms with highest remaining capacity # add villagers to farms with highest remaining capacity
for i in range(count): for i in range(count):
heapq.heappush(self.farms, heapq.heappush(used, heapq.heappop_max(unused))
heapq.heappop_max(self.unused_farms))
def add_farm(self): def _get_task_from_consumable_building(self, building):
new_farm_value = self.buildings_gather_increase[Buildings.FARM][Tasks.FARM] match building:
heapq.heappush(self.unused_farms, new_farm_value) case Buildings.FARM:
task = Tasks.FARM
case Buildings.FISHTRAP:
task = Tasks.FISH_SHIP_TRAP
case _:
raise NotFarmEquivalentException
return task
def remove_farm(self): def add_consumable_building(self, building):
heapq.heappop(self.farms) task = self._get_task_from_consumable_building(building)
unused = self.consumable_buildings[task]['unused']
new_value = self.buildings_gather_increase[building][task]
heapq.heappush(unused, new_value)
def get_num_working_farms(self): def remove_consumable_building(self, building):
return len(self.farms) task = self._get_task_from_consumable_building(building)
used = self.consumable_buildings[task]['used']
heapq.heappop(used)
def _check_consumable_gather_building_available(self, world, task, count):
unused = self.consumable_buildings[task]['unused']
if world.villager_tasks[task] + count > len(unused):
raise GatherBuildingNotAvailableException
def get_num_working_consumable_buildings(self, task):
working = len(self.consumable_buildings[task]['used'])
return working
def add_huntable(self): def add_huntable(self):
@@ -284,14 +352,16 @@ class Gather():
Tasks.MONK_IDLE, Tasks.MONK_IDLE,
Tasks.MONK_GET_RELIC, Tasks.MONK_GET_RELIC,
Tasks.FISH_SHIP_IDLE, Tasks.FISH_SHIP_IDLE,
Tasks.FISH_SHIP_BUILD,
]: ]:
continue continue
rate = self.gather_rates[task] rate = self.gather_rates[task]
if task == Tasks.FARM: if task in Gather.FARM_LIKE_TASKS:
for i in range(len(self.farms)): used, unused = self.consumable_buildings[task].values()
self.farms[i] -= rate*duration for i in range(len(used)):
used[i] -= rate*duration
else: else:
self.gatherable_amounts[task] -= count*rate*duration self.gatherable_amounts[task] -= count*rate*duration
@@ -308,8 +378,8 @@ class Gather():
def __init__(self): def __init__(self):
self.resources = [200, 200, 100, 200] self.resources = [200, 200, 100, 200]
self.farms = [] self.consumable_buildings = {t: {'used': [], 'unused': []}
self.unused_farms = [] for t in Gather.FARM_LIKE_TASKS}
self.gather_rates = { self.gather_rates = {
Tasks.BERRIES: 18.6/60, Tasks.BERRIES: 18.6/60,
@@ -320,7 +390,8 @@ class Gather():
Tasks.FISH_VILLAGER: 25.8/60, Tasks.FISH_VILLAGER: 25.8/60,
Tasks.FISH_SHIP_SHORE: 16.8/60, Tasks.FISH_SHIP_SHORE: 16.8/60,
Tasks.FISH_SHIP_DEEP: 29.4/60, Tasks.FISH_SHIP_DEEP: 29.4/60,
Tasks.FISHTRAP: 21/60, Tasks.FISH_SHIP_BUILD: 0,
Tasks.FISH_SHIP_TRAP: 21/60,
Tasks.WOOD: 23.4/60, Tasks.WOOD: 23.4/60,
Tasks.GOLD: 22.8/60, Tasks.GOLD: 22.8/60,
Tasks.TRADECART: 25.9/60, Tasks.TRADECART: 25.9/60,
@@ -348,7 +419,7 @@ class Gather():
Tasks.FISH_VILLAGER: {Resources.FOOD: 1}, Tasks.FISH_VILLAGER: {Resources.FOOD: 1},
Tasks.FISH_SHIP_SHORE: {Resources.FOOD: 1}, Tasks.FISH_SHIP_SHORE: {Resources.FOOD: 1},
Tasks.FISH_SHIP_DEEP: {Resources.FOOD: 1}, Tasks.FISH_SHIP_DEEP: {Resources.FOOD: 1},
Tasks.FISHTRAP: {Resources.FOOD: 1}, Tasks.FISH_SHIP_TRAP: {Resources.FOOD: 1},
Tasks.WOOD: {Resources.WOOD: 1}, Tasks.WOOD: {Resources.WOOD: 1},
Tasks.GOLD: {Resources.GOLD: 1}, Tasks.GOLD: {Resources.GOLD: 1},
Tasks.TRADECART: {Resources.GOLD: 1}, Tasks.TRADECART: {Resources.GOLD: 1},
@@ -375,7 +446,7 @@ class Gather():
set([Buildings.TOWNCENTER])], set([Buildings.TOWNCENTER])],
Tasks.FISH_SHIP_SHORE: [set([Buildings.DOCK])], Tasks.FISH_SHIP_SHORE: [set([Buildings.DOCK])],
Tasks.FISH_SHIP_DEEP: [set([Buildings.DOCK])], Tasks.FISH_SHIP_DEEP: [set([Buildings.DOCK])],
Tasks.FISHTRAP: [set([Buildings.DOCK, Buildings.FISHTRAP])], Tasks.FISH_SHIP_TRAP: [set([Buildings.DOCK, Buildings.FISHTRAP])],
Tasks.WOOD: [set([Buildings.LUMBERCAMP]), Tasks.WOOD: [set([Buildings.LUMBERCAMP]),
set([Buildings.TOWNCENTER])], set([Buildings.TOWNCENTER])],
Tasks.GOLD: [set([Buildings.MININGCAMP]), Tasks.GOLD: [set([Buildings.MININGCAMP]),
@@ -405,7 +476,7 @@ class Gather():
Tasks.FISH_VILLAGER: 0, Tasks.FISH_VILLAGER: 0,
Tasks.FISH_SHIP_SHORE: 0, Tasks.FISH_SHIP_SHORE: 0,
Tasks.FISH_SHIP_DEEP: 0, Tasks.FISH_SHIP_DEEP: 0,
Tasks.FISHTRAP: 0, Tasks.FISH_SHIP_TRAP: 0,
Tasks.WOOD: 0, Tasks.WOOD: 0,
Tasks.GOLD: 0, Tasks.GOLD: 0,
Tasks.TRADECART: Gather.BIG_NUMBER, Tasks.TRADECART: Gather.BIG_NUMBER,
@@ -429,7 +500,7 @@ class Gather():
Tasks.STONE: 4*350, Tasks.STONE: 4*350,
Tasks.BERRIES: 6*125, Tasks.BERRIES: 6*125,
Tasks.HUNT: 4*140}, Tasks.HUNT: 4*140},
#Buildings.FISHTRAP: {Tasks.WOOD: 100}, Buildings.FISHTRAP: {Tasks.FISH_SHIP_TRAP: 715},
Tasks.LURE: {Tasks.BOAR: 340}, Tasks.LURE: {Tasks.BOAR: 340},
} }
@@ -443,7 +514,7 @@ class Gather():
Tasks.FISH_VILLAGER: 0, Tasks.FISH_VILLAGER: 0,
Tasks.FISH_SHIP_SHORE: 0, Tasks.FISH_SHIP_SHORE: 0,
Tasks.FISH_SHIP_DEEP: 0.5, Tasks.FISH_SHIP_DEEP: 0.5,
Tasks.FISHTRAP: 0, Tasks.FISH_SHIP_TRAP: 0,
Tasks.WOOD: 0.85, Tasks.WOOD: 0.85,
Tasks.GOLD: 0, Tasks.GOLD: 0,
Tasks.TRADECART: 1, Tasks.TRADECART: 1,

View File

@@ -16,6 +16,15 @@ class Housing():
if world.get_effective_population() + required > pop_space: if world.get_effective_population() + required > pop_space:
raise YallGotHousedException raise YallGotHousedException
return True
def check_housing_safe(self, world, thing):
try:
return self.check_housing(world, thing)
except YallGotHousedException:
return False
def __init__(self): def __init__(self):
self.space = defaultdict(int, { self.space = defaultdict(int, {

View File

@@ -14,6 +14,15 @@ class Production():
raise ProductionBuildingNotAvailableException raise ProductionBuildingNotAvailableException
def check_production_safe(self, world, thing):
try:
self.check_production(world, thing)
except ProductionBuildingNotAvailableException:
return False
else:
return True
# assumes for now each unit can be built in only one type of building # assumes for now each unit can be built in only one type of building
def __init__(self): def __init__(self):
self.building = defaultdict(None, { self.building = defaultdict(None, {

View File

@@ -59,7 +59,8 @@ class Tasks(Enum):
FISH_SHIP_IDLE = auto() FISH_SHIP_IDLE = auto()
FISH_SHIP_SHORE = auto() FISH_SHIP_SHORE = auto()
FISH_SHIP_DEEP = auto() FISH_SHIP_DEEP = auto()
FISHTRAP = auto() FISH_SHIP_BUILD = auto()
FISH_SHIP_TRAP = auto()
WOOD = auto() WOOD = auto()
GOLD = auto() GOLD = auto()
MONK_IDLE = auto() MONK_IDLE = auto()

View File

@@ -43,12 +43,15 @@ class World():
# to farms with the highest capacity. # to farms with the highest capacity.
# We keep track of only the closest upcoming farm deletion. # We keep track of only the closest upcoming farm deletion.
# TODO fishtraps # 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: # TODO allow automation:
# reseeding of farms # reseeding of farms
# queuing of villagers
# possibly other things # possibly other things
# TODO use market for buy/sell
MAX_WORLD_TIME = 3*60*60 # 3 hours MAX_WORLD_TIME = 3*60*60 # 3 hours
@@ -60,6 +63,38 @@ class World():
self.gather.spend_resources(cost) 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): def has_building(self, building):
return building in self.buildings return building in self.buildings
@@ -75,7 +110,11 @@ class World():
def _schedule_next_gather_rate_decrease(self, task): def _schedule_next_gather_rate_decrease(self, task):
if task in [Tasks.IDLE, Tasks.BUILD, Tasks.LURE]: if task in [Tasks.IDLE,
Tasks.BUILD,
Tasks.LURE,
Tasks.FISH_SHIP_IDLE,
Tasks.FISH_SHIP_BUILD]:
return return
# remove old decrease # remove old decrease
@@ -87,8 +126,9 @@ class World():
if next_decrease is not None: if next_decrease is not None:
next_decrease += self.current_time next_decrease += self.current_time
if task == Tasks.FARM: if task in Gather.FARM_LIKE_TASKS:
self.events[next_decrease].append((self._remove_farm, ())) self.events[next_decrease].append((self._remove_consumable_building,
(task,)))
else: else:
self.events[next_decrease].append((self._decrease_gather_rate_by_overuse, self.events[next_decrease].append((self._decrease_gather_rate_by_overuse,
(task,))) (task,)))
@@ -140,6 +180,35 @@ class World():
self.assign_villager(Tasks.LURE, Tasks.BOAR) self.assign_villager(Tasks.LURE, Tasks.BOAR)
def add_task_to_work_queue(self, task, **kwargs):
if isinstance(task, Tasks):
task = (task, kwargs)
self.villager_work_queue.append(task)
self._assign_to_villagers_from_work_queue()
def _assign_idle_villager_possibly_compound_task(self, task, **kwargs):
if task == Tasks.LURE:
self.lure_huntable_with_villager(Tasks.IDLE, **kwargs)
elif 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, task)
def _assign_to_villagers_from_work_queue(self):
while (self.villager_tasks[Tasks.IDLE] > 0 and
len(self.villager_work_queue) > 0):
original_task = self.villager_work_queue.pop(0)
task, kwargs = self._parse_task(original_task)
self._assign_idle_villager_possibly_compound_task(task, **kwargs)
def assign_villager(self, previous_task, new_task, count=1): def assign_villager(self, previous_task, new_task, count=1):
# new_task of None means kill the villager # new_task of None means kill the villager
@@ -148,29 +217,7 @@ class World():
if self.villager_tasks[previous_task] < count: if self.villager_tasks[previous_task] < count:
raise IllegalVillagerMoveException raise IllegalVillagerMoveException
non_assignable_tasks = [ self._check_single_villager_move(previous_task, new_task)
Tasks.MONK_GET_RELIC,
Tasks.MONK_IDLE,
Tasks.RELIC,
Tasks.TRADECART,
Tasks.TRADECOG,
]
fishing_tasks = [
Tasks.FISH_SHIP_IDLE,
Tasks.FISH_SHIP_SHORE,
Tasks.FISH_SHIP_DEEP,
Tasks.FISHTRAP,
]
if new_task in non_assignable_tasks or \
previous_task in non_assignable_tasks:
raise IllegalVillagerMoveException
num_fishing_tasks = (int(new_task in non_assignable_tasks) +
int(previous_task in non_assignable_tasks))
if num_fishing_tasks == 1:
raise IllegalVillagerMoveException
if new_task: if new_task:
self.gather.check_gather(self, new_task, count) self.gather.check_gather(self, new_task, count)
@@ -180,26 +227,71 @@ class World():
self.villager_tasks[previous_task] -= count self.villager_tasks[previous_task] -= count
if previous_task == Tasks.FARM: if previous_task in Gather.FARM_LIKE_TASKS:
self.gather.stop_using_farms(count) self.gather.stop_using_consumable_buildings(previous_task, count)
if new_task == Tasks.FARM: if new_task in Gather.FARM_LIKE_TASKS:
self.gather.start_using_farms(count) self.gather.start_using_consumable_buildings(new_task, count)
self._schedule_next_gather_rate_decrease(previous_task) self._schedule_next_gather_rate_decrease(previous_task)
if new_task: if new_task:
self._schedule_next_gather_rate_decrease(new_task) self._schedule_next_gather_rate_decrease(new_task)
self._assign_to_villagers_from_work_queue()
def _check_villager_move(self, villagers_from_count):
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(): for task, count in villagers_from_count.items():
if self.villager_tasks[task] < count: if self.villager_tasks[task] < count:
raise IllegalVillagerMoveException 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): def _move_villagers_to_build(self, villagers_from_count):
for task, count in villagers_from_count.items(): for task, count in villagers_from_count.items():
self.assign_villager(task, Tasks.BUILD, count) 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): def get_relic(self, walking_time=60):
@@ -239,7 +331,11 @@ class World():
villagers_from_count = Counter(villagers_from) villagers_from_count = Counter(villagers_from)
self._check_villager_move(villagers_from_count) 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.dependencies.check_dependencies(self, building)
@@ -265,26 +361,33 @@ class World():
if building == Buildings.HOUSE: if building == Buildings.HOUSE:
self._free_housing() self._free_housing()
if building == Buildings.FARM: if building in Gather.FARM_LIKE_BUILDINGS:
self._add_farm() self.gather.add_consumable_building(building)
else: else:
self._improve_gather_rate_by_building(building, tasks_improved) self._improve_gather_rate_by_building(building, tasks_improved)
for task, count in villagers_to.items(): for task, count in villagers_to.items():
self.assign_villager(Tasks.BUILD, task, count) build_task = self._get_build_task_from_task(task)
self.assign_villager(build_task, task, count)
def _add_farm(self): def _remove_consumable_building(self, task):
self.buildings.append(Buildings.FARM) match task:
self.gather.add_farm() 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)
def _remove_farm(self): num_working_buildings = self.gather.get_num_working_consumable_buildings(task)
self.buildings.remove(Buildings.FARM) if self.villager_tasks[task] > num_working_buildings:
self.gather.remove_farm() self.assign_villager(task, next_task)
if self.villager_tasks[Tasks.FARM] > gather.get_num_working_farms():
self.assign_villager(Tasks.FARM, Tasks.IDLE)
def advance_by_time(self, duration): def advance_by_time(self, duration):
@@ -318,6 +421,10 @@ class World():
self._handle_events() self._handle_events()
def set_housed_is_error(self, is_error=True):
self.housed_is_error = is_error
def get_population_space(self): def get_population_space(self):
space = sum([self.housing.space[building] for building in self.buildings]) space = sum([self.housing.space[building] for building in self.buildings])
return min(space, World.POPULATION_CAP) return min(space, World.POPULATION_CAP)
@@ -330,13 +437,15 @@ class World():
def _free_housing(self): def _free_housing(self):
pop_space = self.get_population_space() pop_space = self.get_population_space()
house_check = self._get_house_check_function()
i = 0 i = 0
while (self.get_effective_population() < pop_space and while (self.get_effective_population() < pop_space and
i < len(self.production_queue)): i < len(self.production_queue)):
thing, task = self.production_queue[i] thing, task = self.production_queue[i]
if self.housing.check_housing(self, thing) and \ if house_check(self, thing) and \
self.production.check_production(self, thing): self.production.check_production_safe(self, thing):
self._start_producing(thing, task) self._start_producing(thing, task)
del self.production_queue[i] del self.production_queue[i]
else: else:
@@ -357,11 +466,13 @@ class World():
# production queue as a shared pool, and I don't really care. # production queue as a shared pool, and I don't really care.
self.production_available[building] += 1 self.production_available[building] += 1
house_check = self._get_house_check_function()
i = 0 i = 0
while i < len(self.production_queue): while i < len(self.production_queue):
thing, task = self.production_queue[i] thing, task = self.production_queue[i]
if self.production.building[thing] == building and \ if self.production.building[thing] == building and \
self.housing.check_housing(self, thing): house_check(self, thing):
self._start_producing(thing, task) self._start_producing(thing, task)
del self.production_queue[i] del self.production_queue[i]
break break
@@ -392,6 +503,11 @@ class World():
def _add_thing(self, thing, initial_task): def _add_thing(self, thing, initial_task):
if (initial_task and
thing != Units.VILLAGER and
not isinstance(initial_task, Tasks)):
raise ValueError('Only villagers can accept compound tasks')
self.units_being_built -= self.housing.required[thing] self.units_being_built -= self.housing.required[thing]
self.population += self.housing.required[thing] self.population += self.housing.required[thing]
@@ -404,9 +520,8 @@ class World():
if thing == Units.VILLAGER: if thing == Units.VILLAGER:
self.villagers += 1 self.villagers += 1
self.villager_tasks[Tasks.IDLE] += 1 self.villager_tasks[Tasks.IDLE] += 1
if not initial_task: task, kwargs = self._parse_task(initial_task)
initial_task = Tasks.IDLE self._assign_idle_villager_possibly_compound_task(task, **kwargs)
self.assign_villager(Tasks.IDLE, initial_task)
elif thing == Units.MONK: elif thing == Units.MONK:
self.villager_tasks[Tasks.MONK_IDLE] += 1 self.villager_tasks[Tasks.MONK_IDLE] += 1
self._get_next_waiting_relic() self._get_next_waiting_relic()
@@ -423,8 +538,14 @@ class World():
def _start_producing(self, thing, initial_task): def _start_producing(self, thing, initial_task):
try: try:
self._use_housing_and_production(thing) self._use_housing_and_production(thing)
except ProductionBuildingNotAvailableException: 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)) self.production_queue.append((thing, initial_task))
else:
raise(e)
else: else:
update_time = self.current_time + self.build_times.build_times[thing] update_time = self.current_time + self.build_times.build_times[thing]
self.events[update_time].append((self._add_thing, (thing, initial_task,))) self.events[update_time].append((self._add_thing, (thing, initial_task,)))
@@ -462,9 +583,45 @@ class World():
self._queue_thing(Units.TRADECART) self._queue_thing(Units.TRADECART)
def _parse_task(self, initial_task):
'''
A single task is either a Task or a tuple of (Tasks, dict) where the
dictionary contains keyword arguments.
If a list is passed, all tasks beyond the first are appended to the
villager work queue.
'''
if isinstance(initial_task, list):
remaining_tasks = initial_task[1:]
self.villager_work_queue.extend(remaining_tasks)
initial_task = initial_task[0]
kwargs = {}
if isinstance(initial_task, tuple):
kwargs = initial_task[1]
initial_task = initial_task[0]
if not initial_task:
initial_task = Tasks.IDLE
return initial_task, kwargs
def _handle_events(self): def _handle_events(self):
for func, args in self.events[self.current_time]: for func, args in self.events[self.current_time]:
try:
func(*args) func(*args)
except Exception as e:
raise type(e)(
f'Error in {func.__name__}{args}'
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] del self.events[self.current_time]
@@ -500,6 +657,7 @@ class World():
self.villager_tasks = {t: 0 for t in Tasks} self.villager_tasks = {t: 0 for t in Tasks}
self.villager_tasks[Tasks.IDLE] = self.villagers self.villager_tasks[Tasks.IDLE] = self.villagers
self.villager_work_queue = []
self.rate_decrease_event_times = {t: None for t in Tasks} self.rate_decrease_event_times = {t: None for t in Tasks}
@@ -519,4 +677,6 @@ class World():
self.production = Production() self.production = Production()
self.gather = Gather() self.gather = Gather()
self.housed_is_error = True
self._deal_with_civ() self._deal_with_civ()

View File

@@ -1,18 +1,3 @@
# TODO
* Get aoe info
* API for it somewhere?
* Write simple code
* Write tests
* Write GUI
Deal with getting housed
Put villagers on resource sources
* what to do about farms?
* one villager per
* run out occaisionally and must be rebuilt
# Outline # Outline
Timeline of villager production Timeline of villager production
@@ -48,30 +33,3 @@ As an aside,
this is similar to what I've seen described as the fundamental difference this is similar to what I've seen described as the fundamental difference
between object-oriented (row-based) and functional (column-based) programming, between object-oriented (row-based) and functional (column-based) programming,
though I'm still using classes and objects. though I'm still using classes and objects.
# Scratch
```
def create(self):
self.
# Assume entries sorted by time
# Not necessarily from user, but from queue_villager and move_villager
```
```
Class Task():
requires = {"wood": "lumber camp"}
# what if more villagers than farms?
```
# Assumptions
* Fixed gather rate for each resource
* what about food -- hunt vs farm?
* At least one TC always exists
* Using no civ bonuses for now

View File

@@ -58,6 +58,17 @@ class TestWorld(unittest.TestCase):
self.assertResourcesMatch([150, 200, 100, 200], game.world) self.assertResourcesMatch([150, 200, 100, 200], game.world)
def test_build_villagers_regularly(self):
game = Gameplay()
game.world._add_building(Buildings.HOUSE, {}, {})
game.queue_villagers_over_time(0, 75, Tasks.IDLE)
game.play_until(100)
self.assertEqual(8, game.world.population)
self.assertResourcesMatch([0, 200, 100, 200], game.world)
def test_build_villager_leave_idle(self): def test_build_villager_leave_idle(self):
game = Gameplay() game = Gameplay()
game.queue_villager(5, Tasks.IDLE) game.queue_villager(5, Tasks.IDLE)
@@ -81,6 +92,39 @@ class TestWorld(unittest.TestCase):
self.assertResourcesMatch([150, new_wood, 100, 200], game.world) self.assertResourcesMatch([150, new_wood, 100, 200], game.world)
def test_wood_stale_camp(self):
game = Gameplay()
wood_amount_per_camp = 1000
wood_rate_times_60 = 23.4
wood_rate_decrease = 0.85
slow_wood_rate_times_60 = wood_rate_times_60*wood_rate_decrease
game.world._add_building(Buildings.LUMBERCAMP, {}, {})
game.assign_villager(1, Tasks.IDLE, Tasks.WOOD)
game.play_until(60)
new_wood = 200 + wood_rate_times_60
self.assertResourcesMatch([200, new_wood, 100, 200], game.world)
camp_expires = 60*wood_amount_per_camp/wood_rate_times_60
game.play_until(camp_expires)
new_wood = 200 + wood_rate_times_60*(camp_expires/60)
self.assertResourcesMatch([200, new_wood, 100, 200], game.world)
self.assertResourcesMatch([200,
200 + wood_amount_per_camp,
100,
200],
game.world)
game.play_until(camp_expires + 60)
new_wood += slow_wood_rate_times_60
self.assertResourcesMatch([200, new_wood, 100, 200], game.world)
def test_good_villager_task_assign(self): def test_good_villager_task_assign(self):
game = Gameplay() game = Gameplay()
game.assign_villager(5, Tasks.IDLE, Tasks.SHEEP) game.assign_villager(5, Tasks.IDLE, Tasks.SHEEP)
@@ -125,6 +169,18 @@ class TestWorld(unittest.TestCase):
self.assertTrue(Buildings.LUMBERCAMP in game.world.buildings) self.assertTrue(Buildings.LUMBERCAMP in game.world.buildings)
def test_build_lumber_camp_three_villagers(self):
lc_build_time = 35
lc_build_time_three_vils = 3*lc_build_time/(3 + 2)
game = Gameplay()
game.build(0, Buildings.LUMBERCAMP, [Tasks.IDLE]*3, [Tasks.IDLE]*3)
game.play_until(lc_build_time_three_vils - 1)
self.assertTrue(Buildings.LUMBERCAMP not in game.world.buildings)
game.play_until(lc_build_time_three_vils)
self.assertTrue(Buildings.LUMBERCAMP in game.world.buildings)
def test_building_adds_gatherable(self): def test_building_adds_gatherable(self):
lc_build_time = 35 lc_build_time = 35
@@ -191,6 +247,34 @@ class TestWorld(unittest.TestCase):
game.play_until(25) game.play_until(25)
def test_get_housed_no_error(self):
game = Gameplay()
game.queue_villager(0, Tasks.IDLE)
game.queue_villager(0, Tasks.IDLE)
game.queue_villager(0, Tasks.IDLE)
game.set_housed_is_error(24, False)
game.play_until(100)
self.assertEqual(5, game.world.population)
def test_get_housed_toggle_error(self):
game = Gameplay()
game.world.gather.resources = [1000, 1000, 1000, 1000]
game.queue_villager(0, Tasks.IDLE)
game.queue_villager(0, Tasks.IDLE)
game.set_housed_is_error(24, False)
game.play_until(80)
game.set_housed_is_error(81, True)
game.queue_villager(82, Tasks.IDLE)
with self.assertRaises(YallGotHousedException):
game.play_until(85)
def test_gather_boar_without_lure(self): def test_gather_boar_without_lure(self):
game = Gameplay() game = Gameplay()
game.assign_villager(0, Tasks.IDLE, Tasks.BOAR, 1) game.assign_villager(0, Tasks.IDLE, Tasks.BOAR, 1)
@@ -212,6 +296,32 @@ class TestWorld(unittest.TestCase):
self.assertResourcesMatch([200 + gathered, 200, 100, 200], game.world) self.assertResourcesMatch([200 + gathered, 200, 100, 200], game.world)
def test_gather_boar_initial_lure(self):
walking = 30
game = Gameplay()
game.queue_villager(0, Tasks.LURE)
game.play_until(25 + walking + 60)
boar_rate_times_60 = 24.6
gathered = boar_rate_times_60
self.assertResourcesMatch([150 + gathered, 200, 100, 200], game.world)
def test_gather_boar_initial_lure_custom_time(self):
walking = 80
game = Gameplay()
game.queue_villager(0, Tasks.LURE, walking_time=walking)
game.play_until(25 + walking + 60)
boar_rate_times_60 = 24.6
gathered = boar_rate_times_60
self.assertResourcesMatch([150 + gathered, 200, 100, 200], game.world)
def test_gather_boar_limited(self): def test_gather_boar_limited(self):
walking = 20 walking = 20
@@ -256,7 +366,7 @@ class TestWorld(unittest.TestCase):
game = Gameplay() game = Gameplay()
game.world.age = Ages.CASTLE game.world.age = Ages.CASTLE
game.world.resources = [1000, 1000, 1000, 1000] game.world.gather.resources = [1000, 1000, 1000, 1000]
game.world._add_building(Buildings.MONASTERY, {}, {}) game.world._add_building(Buildings.MONASTERY, {}, {})
game.queue_unit(0, Units.MONK) game.queue_unit(0, Units.MONK)
@@ -341,3 +451,675 @@ class TestWorld(unittest.TestCase):
game.play_until(training + 60) game.play_until(training + 60)
self.assertResourcesMatch([500, 400, 450 + gathered, 500], game.world) self.assertResourcesMatch([500, 400, 450 + gathered, 500], game.world)
def test_market_buy_without_market(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
game.world.gather.resources = [500, 500, 1000, 500]
game.market_buy(0, Resources.FOOD, 100)
with self.assertRaises(MissingDependencyException):
game.play_until(1)
def test_market_buy(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
game.world.gather.resources = [500, 500, 1000, 500]
game.world._add_building(Buildings.MARKET, {}, {})
food_rate = 115
wood_rate = 100
new_gold = game.world.gather.resources[2]
fee = 0.3
inc = 2
game.market_buy(0, Resources.FOOD, 100)
new_gold -= food_rate*(1 + fee)
food_rate += 2
game.play_until(1)
self.assertResourcesMatch([600, 500, new_gold, 500], game.world)
game.market_buy(5, Resources.FOOD, 100)
new_gold -= food_rate*(1 + fee)
food_rate += 2
game.play_until(6)
self.assertResourcesMatch([700, 500, new_gold, 500], game.world)
game.market_buy(7, Resources.FOOD, 300)
for i in range(3):
new_gold -= food_rate*(1 + fee)
food_rate += 2
game.play_until(8)
self.assertResourcesMatch([1000, 500, new_gold, 500], game.world)
game.market_buy(9, Resources.WOOD, 100)
new_gold -= wood_rate*(1 + fee)
wood_rate += 2
game.play_until(10)
self.assertResourcesMatch([1000, 600, new_gold, 500], game.world)
def test_market_sell(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
game.world.gather.resources = [500, 500, 1000, 500]
game.world._add_building(Buildings.MARKET, {}, {})
food_rate = 115
wood_rate = 100
new_gold = game.world.gather.resources[2]
fee = 0.3
inc = 2
game.market_sell(0, Resources.FOOD, 100)
new_gold += food_rate*(1 - fee)
food_rate -= 2
game.play_until(1)
self.assertResourcesMatch([400, 500, new_gold, 500], game.world)
game.market_sell(5, Resources.FOOD, 100)
new_gold += food_rate*(1 - fee)
food_rate -= 2
game.play_until(6)
self.assertResourcesMatch([300, 500, new_gold, 500], game.world)
game.market_sell(7, Resources.FOOD, 300)
for i in range(3):
new_gold += food_rate*(1 - fee)
food_rate -= 2
game.play_until(8)
self.assertResourcesMatch([0, 500, new_gold, 500], game.world)
game.market_sell(9, Resources.WOOD, 100)
new_gold += wood_rate*(1 - fee)
wood_rate -= 2
game.play_until(10)
self.assertResourcesMatch([0, 400, new_gold, 500], game.world)
def test_market_buy_too_much(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
game.world.gather.resources = [500, 500, 1000, 500]
game.world._add_building(Buildings.MARKET, {}, {})
with self.assertRaises(NotEnoughResourcesException):
game.market_buy(0, Resources.FOOD, 1000)
game.play_until(1)
def test_market_sell_too_much(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
game.world.gather.resources = [500, 500, 1000, 500]
game.world._add_building(Buildings.MARKET, {}, {})
with self.assertRaises(NotEnoughResourcesException):
game.market_sell(0, Resources.FOOD, 1000)
game.play_until(1)
def test_market_sell_bad_amount(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
game.world.gather.resources = [500, 500, 1000, 500]
game.world._add_building(Buildings.MARKET, {}, {})
with self.assertRaises(InvalidMarketAmountException):
game.market_sell(0, Resources.FOOD, 50)
game.play_until(1)
def test_farm_simple(self):
game = Gameplay()
game.world.age = Ages.DARK
game.world.gather.resources = [500, 500, 500, 500]
game.world._add_building(Buildings.MILL, {}, {})
game.world._add_building(Buildings.FARM, {}, {})
game.assign_villager(0, Tasks.IDLE, Tasks.FARM)
rate_per_60 = 20
game.play_until(60)
new_food = 500 + rate_per_60
self.assertResourcesMatch([new_food, 500, 500, 500], game.world)
def test_farm_build(self):
game = Gameplay()
game.world.age = Ages.DARK
game.world.gather.resources = [500, 500, 500, 500]
game.world._add_building(Buildings.MILL, {}, {})
game.build(0, Buildings.FARM, Tasks.IDLE, Tasks.IDLE)
game.assign_villager(30, Tasks.IDLE, Tasks.FARM)
rate_per_60 = 20
game.play_until(90)
new_food = 500 + rate_per_60
self.assertResourcesMatch([new_food, 440, 500, 500], game.world)
def test_farm_depleted(self):
game = Gameplay()
game.world.age = Ages.DARK
game.world.gather.resources = [500, 500, 500, 500]
game.world._add_building(Buildings.MILL, {}, {})
game.world._add_building(Buildings.FARM, {}, {})
game.assign_villager(0, Tasks.IDLE, Tasks.FARM)
amount_per_farm = 175
game.play_until(1000)
new_food = 500 + amount_per_farm
self.assertResourcesMatch([new_food, 500, 500, 500], game.world)
farms = game.world.gather.consumable_buildings[Tasks.FARM]
self.assertEqual(0, len(farms['used']))
self.assertEqual(0, len(farms['unused']))
def test_farm_too_many_farmers(self):
game = Gameplay()
game.world.age = Ages.DARK
game.world.gather.resources = [500, 500, 500, 500]
game.world._add_building(Buildings.MILL, {}, {})
game.world._add_building(Buildings.FARM, {}, {})
game.assign_villager(0, Tasks.IDLE, Tasks.FARM)
game.assign_villager(0, Tasks.IDLE, Tasks.FARM)
with self.assertRaises(GatherBuildingNotAvailableException):
game.play_until(1)
def test_farm_off_and_on(self):
game = Gameplay()
game.world.age = Ages.DARK
game.world.gather.resources = [500, 500, 500, 500]
game.world._add_building(Buildings.MILL, {}, {})
game.world._add_building(Buildings.FARM, {}, {})
game.assign_villager(0, Tasks.IDLE, Tasks.FARM)
game.assign_villager(30, Tasks.FARM, Tasks.IDLE)
game.assign_villager(60, Tasks.IDLE, Tasks.FARM)
rate_per_60 = 20
game.play_until(90)
new_food = 500 + rate_per_60
self.assertResourcesMatch([new_food, 500, 500, 500], game.world)
def test_fishing_ship(self):
game = Gameplay()
game.world.age = Ages.DARK
game.world.gather.resources = [500, 500, 500, 500]
game.world._add_building(Buildings.DOCK, {}, {})
game.queue_fishing_ship(0)
rate_per_60 = 29.4
ship_training = 40
game.play_until(ship_training - 1)
self.assertResourcesMatch([500, 425, 500, 500], game.world)
game.play_until(ship_training + 60)
new_food = 500 + rate_per_60
self.assertResourcesMatch([new_food, 425, 500, 500], game.world)
def test_fishtrap_simple(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
game.world.gather.resources = [500, 500, 500, 500]
game.world._add_building(Buildings.DOCK, {}, {})
game.world._add_building(Buildings.FISHTRAP, {}, {})
game.world._add_thing(Units.FISHINGSHIP, Tasks.FISH_SHIP_TRAP)
rate_per_60 = 21
game.play_until(60)
new_food = 500 + rate_per_60
self.assertResourcesMatch([new_food, 500, 500, 500], game.world)
def test_fishtrap_build(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
game.world.gather.resources = [500, 500, 500, 500]
game.world._add_building(Buildings.DOCK, {}, {})
game.world._add_thing(Units.FISHINGSHIP, Tasks.FISH_SHIP_IDLE)
game.build(0,
Buildings.FISHTRAP,
Tasks.FISH_SHIP_IDLE,
Tasks.FISH_SHIP_IDLE)
game.play_until(10)
game.assign_villager(50, Tasks.FISH_SHIP_IDLE, Tasks.FISH_SHIP_TRAP)
rate_per_60 = 21
game.play_until(110)
new_food = 500 + rate_per_60
self.assertResourcesMatch([new_food, 400, 500, 500], game.world)
def test_fishtrap_depleted(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
game.world.gather.resources = [500, 500, 500, 500]
game.world._add_building(Buildings.DOCK, {}, {})
game.world._add_building(Buildings.FISHTRAP, {}, {})
game.world._add_thing(Units.FISHINGSHIP, Tasks.FISH_SHIP_IDLE)
game.assign_villager(0, Tasks.FISH_SHIP_IDLE, Tasks.FISH_SHIP_TRAP)
amount_per_fishtrap = 715
rate_per_60 = 21
duration = (amount_per_fishtrap/rate_per_60)*60 + 1
game.play_until(duration)
new_food = 500 + amount_per_fishtrap
self.assertResourcesMatch([new_food, 500, 500, 500], game.world)
traps = game.world.gather.consumable_buildings[Tasks.FISH_SHIP_TRAP]
self.assertEqual(0, len(traps['used']))
self.assertEqual(0, len(traps['unused']))
# fishing ships go back to fishing after trap is depleted
deep_rate_per_60 = 29.4
game.play_until(duration + 60)
new_food += deep_rate_per_60
self.assertResourcesMatch([new_food, 500, 500, 500], game.world)
def test_fishtrap_too_many_fish_ships(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
game.world.gather.resources = [500, 500, 500, 500]
game.world._add_building(Buildings.DOCK, {}, {})
game.world._add_building(Buildings.FISHTRAP, {}, {})
game.world._add_thing(Units.FISHINGSHIP, Tasks.FISH_SHIP_IDLE)
game.world._add_thing(Units.FISHINGSHIP, Tasks.FISH_SHIP_IDLE)
game.assign_villager(0, Tasks.FISH_SHIP_IDLE, Tasks.FISH_SHIP_TRAP)
game.assign_villager(0, Tasks.FISH_SHIP_IDLE, Tasks.FISH_SHIP_TRAP)
with self.assertRaises(GatherBuildingNotAvailableException):
game.play_until(1)
def test_fishtrap_off_and_on(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
game.world.gather.resources = [500, 500, 500, 500]
game.world._add_building(Buildings.DOCK, {}, {})
game.world._add_building(Buildings.FISHTRAP, {}, {})
game.world._add_thing(Units.FISHINGSHIP, Tasks.FISH_SHIP_IDLE)
game.assign_villager(0, Tasks.FISH_SHIP_IDLE, Tasks.FISH_SHIP_TRAP)
game.assign_villager(30, Tasks.FISH_SHIP_TRAP, Tasks.FISH_SHIP_IDLE)
game.assign_villager(60, Tasks.FISH_SHIP_IDLE, Tasks.FISH_SHIP_TRAP)
rate_per_60 = 21
game.play_until(90)
new_food = 500 + rate_per_60
self.assertResourcesMatch([new_food, 500, 500, 500], game.world)
def test_play_until_last_action(self):
game = Gameplay()
game.build(0, Buildings.HOUSE, [Tasks.IDLE]*2, [Tasks.IDLE]*2)
game.build(0, Buildings.HOUSE, Tasks.IDLE, Tasks.IDLE)
game.build(100, Buildings.LUMBERCAMP, Tasks.IDLE, Tasks.IDLE)
game.play_until_last_action()
self.assertEqual(3, len(game.world.buildings))
game.assign_villager(200, Tasks.IDLE, Tasks.SHEEP)
game.assign_villager(200, Tasks.IDLE, Tasks.SHEEP)
game.play_until_last_action(extra_time=60)
sheep_rate_per_60 = 19.8
gathered = sheep_rate_per_60*2
self.assertEqual(4, len(game.world.buildings))
self.assertResourcesMatch([200 + gathered, 50, 100, 200], game.world)
def test_initial_build(self):
game = Gameplay()
game.queue_villager(0,
Tasks.BUILD,
building=Buildings.HOUSE,
villagers_to=Tasks.SHEEP)
game.play_until(10)
self.assertEqual(1, len(game.world.buildings))
self.assertEqual(4, game.world.population)
game.play_until(30)
self.assertEqual(1, len(game.world.buildings))
self.assertEqual(5, game.world.population)
game.play_until(25 + 25 + 60)
self.assertEqual(2, len(game.world.buildings))
self.assertEqual(5, game.world.population)
sheep_rate_per_60 = 19.8
gathered = sheep_rate_per_60
self.assertResourcesMatch([150 + gathered, 175, 100, 200], game.world)
def test_work_queue_adding_villager(self):
game = Gameplay()
build_house = (Tasks.BUILD,
{'building': Buildings.HOUSE,
'villagers_to': Tasks.IDLE})
build_lumber = (Tasks.BUILD,
{'building': Buildings.LUMBERCAMP,
'villagers_to': Tasks.IDLE})
build_house_to_wood = (Tasks.BUILD,
{'building': Buildings.HOUSE,
'villagers_to': Tasks.WOOD})
task_list = [
build_house,
build_house,
build_lumber,
build_house_to_wood,
]
game.assign_villager(0, Tasks.IDLE, Tasks.SHEEP)
game.assign_villager(0, Tasks.IDLE, Tasks.SHEEP)
game.assign_villager(0, Tasks.IDLE, Tasks.SHEEP)
game.queue_villager(0, task_list)
game.play_until(10)
self.assertEqual(1, len(game.world.buildings))
self.assertEqual(4, game.world.population)
game.play_until(30)
self.assertEqual(1, len(game.world.buildings))
self.assertEqual(5, game.world.population)
train_and_build_time = 25 + 25*2 + 35 + 25
duration = train_and_build_time + 60
game.play_until(duration)
self.assertEqual(5, len(game.world.buildings))
self.assertEqual(5, game.world.population)
sheep_rate_per_60 = 19.8
gathered_food = sheep_rate_per_60*(duration/60)*3
wood_rate_per_60 = 23.4
gathered_wood = wood_rate_per_60
self.assertResourcesMatch([150 + gathered_food,
25 + gathered_wood,
100,
200],
game.world)
def test_add_tasks_to_work_queue(self):
game = Gameplay()
task_list = [
Tasks.WOOD,
Tasks.WOOD,
Tasks.SHEEP,
]
game.world._add_building(Buildings.LUMBERCAMP, {}, {})
game.queue_villager(0, Tasks.WOOD)
for t in task_list:
game.add_task_to_work_queue(0, t)
duration = 25 + 60
game.play_until(duration)
sheep_rate_per_60 = 19.8
gathered_food = sheep_rate_per_60*(duration/60)
wood_rate_per_60 = 23.4
gathered_wood = wood_rate_per_60*(duration/60)*2
gathered_wood += wood_rate_per_60
self.assertResourcesMatch([150 + gathered_food,
200 + gathered_wood,
100,
200],
game.world)
def test_queue_with_task_list(self):
game = Gameplay()
task_build_lumber = (Tasks.BUILD,
{'building': Buildings.LUMBERCAMP,
'villagers_to': Tasks.WOOD})
build_order = [
Tasks.SHEEP,
Tasks.SHEEP,
Tasks.SHEEP,
task_build_lumber,
]
game.queue_villagers_by_task_list(0, build_order)
game.assign_villager(0, Tasks.IDLE, Tasks.SHEEP)
game.build(0, Buildings.HOUSE, Tasks.IDLE, Tasks.SHEEP)
game.build(0, Buildings.HOUSE, Tasks.IDLE, Tasks.SHEEP)
game.play_until_last_action(extra_time=(25 + 35 + 60))
self.assertEqual(4, len(game.world.buildings))
train = 25
build_lumber = 35
build_house = 25
duration = 4*train + build_lumber + 60
sheep_rate_per_60 = 19.8
vil0 = sheep_rate_per_60*(duration/60)
vil1 = sheep_rate_per_60*((duration - build_house)/60)
vil2 = vil1
vil3 = sheep_rate_per_60*((duration - train)/60)
vil4 = sheep_rate_per_60*((duration - 2*train)/60)
vil5 = sheep_rate_per_60*((duration - 3*train)/60)
gathered_food = vil0 + vil1 + vil2 + vil3 + vil4 + vil5
wood_rate_per_60 = 23.4
gathered_wood = wood_rate_per_60
self.assertResourcesMatch([gathered_food,
50 + gathered_wood,
100,
200],
game.world)
def test_production_queue_two_units(self):
game = Gameplay()
game.world._add_building(Buildings.BARRACKS, {}, {})
game.world._add_building(Buildings.HOUSE, {}, {})
training = 21
game.queue_unit(0, Units.MILITIA)
game.queue_unit(0, Units.MILITIA)
game.play_until(1)
self.assertEqual(4, game.world.population)
game.play_until(training)
self.assertEqual(5, game.world.population)
game.play_until(training + 10)
self.assertEqual(5, game.world.population)
game.play_until(2*training)
self.assertEqual(6, game.world.population)
def test_production_queue_new_building(self):
game = Gameplay()
game.world._add_building(Buildings.BARRACKS, {}, {})
game.world._add_building(Buildings.HOUSE, {}, {})
training = 21
game.queue_unit(0, Units.MILITIA)
game.queue_unit(0, Units.MILITIA)
game.play_until(10)
game.world._add_building(Buildings.BARRACKS, {}, {})
game.play_until(training)
self.assertEqual(5, game.world.population)
game.play_until(training + 10)
self.assertEqual(6, game.world.population)
def test_production_queue_new_housing(self):
game = Gameplay()
game.world._add_building(Buildings.BARRACKS, {}, {})
game.set_housed_is_error(0, False)
training = 21
game.queue_unit(0, Units.MILITIA)
game.queue_unit(0, Units.MILITIA)
game.play_until(3*training)
self.assertEqual(5, game.world.population)
game.world._add_building(Buildings.HOUSE, {}, {})
game.play_until(4*training)
self.assertEqual(6, game.world.population)
def test_research_bit_axe(self):
game = Gameplay()
game.world.age = Ages.FEUDAL
wood_amount_per_camp = 1000
wood_rate_times_60 = 23.4
bit_axe_mult = 1.2
wood_rate_times_60 *= bit_axe_mult
bit_axe_time = 25
wood_rate_decrease = 0.85
slow_wood_rate_times_60 = wood_rate_times_60*wood_rate_decrease
game.world._add_building(Buildings.LUMBERCAMP, {}, {})
game.queue_research(0, Research.DOUBLEBITAXE)
game.assign_villager(bit_axe_time, Tasks.IDLE, Tasks.WOOD)
game.play_until(bit_axe_time + 60)
new_wood = 150 + wood_rate_times_60
self.assertResourcesMatch([100, new_wood, 100, 200], game.world)
camp_duration = 60*wood_amount_per_camp/wood_rate_times_60
game.play_until(bit_axe_time + camp_duration)
new_wood = 150 + wood_rate_times_60*(camp_duration/60)
self.assertResourcesMatch([100, new_wood, 100, 200], game.world)
self.assertResourcesMatch([100,
150 + wood_amount_per_camp,
100,
200],
game.world)
game.play_until(bit_axe_time + camp_duration + 60)
new_wood += slow_wood_rate_times_60
self.assertResourcesMatch([100, new_wood, 100, 200], game.world)
def test_research_bit_axe_partial_start(self):
game = Gameplay()
wood_rate_times_60 = 23.4
bit_axe_mult = 1.2
bit_axe_time = 25
game.world.age = Ages.FEUDAL
game.world._add_building(Buildings.LUMBERCAMP, {}, {})
game.assign_villager(0, Tasks.IDLE, Tasks.WOOD)
game.queue_research(35, Research.DOUBLEBITAXE)
game.play_until(60)
new_wood = 150 + wood_rate_times_60
self.assertResourcesMatch([100, new_wood, 100, 200], game.world)
game.play_until(120)
new_wood = 150 + wood_rate_times_60*(1 + bit_axe_mult)
self.assertResourcesMatch([100, new_wood, 100, 200], game.world)