Stronghold-AI-Arena / tests /test_engine.py
Mati83moni's picture
Rules v2 (monster raids) and 3D match viewer (#4)
0b21763
Raw History Blame Contribute Delete
37.1 kB
"""Engine tests: determinism, robustness against arbitrary input, and rules."""
from __future__ import annotations
import copy
import json
import random
import pytest
from stronghold import engine as E
from stronghold.engine import config as C
NO_UNITS = {"pikeman": 0, "archer": 0, "knight": 0}
def units(pikeman: int = 0, archer: int = 0, knight: int = 0) -> dict[str, int]:
return {"pikeman": pikeman, "archer": archer, "knight": knight}
def rich_state(seed: int = 0, max_turns: int = 50) -> dict:
"""A state where both players can afford anything."""
s = E.new(seed, max_turns)
for p in s["players"]:
p["resources"] = {r: 5000 for r in C.RESOURCES}
p["pop"] = 10
return s
def instantiate(descriptor: dict, rng: random.Random) -> dict:
"""Turn a legal_actions descriptor into a concrete action."""
if descriptor["type"] == "recruit":
b = descriptor["count"]
return {"type": "recruit", "unit": descriptor["unit"], "count": rng.randint(b["min"], b["max"])}
if descriptor["type"] == "attack":
chosen = {u: rng.randint(b["min"], b["max"]) for u, b in descriptor["units"].items()}
if sum(chosen.values()) == 0:
chosen[rng.choice([u for u, b in descriptor["units"].items() if b["max"] > 0])] = 1
return {"type": "attack", "units": chosen}
return dict(descriptor)
def random_actions(state: dict, player: int, rng: random.Random) -> list[dict]:
legal = E.legal_actions(state, player)
if not legal:
return []
return [instantiate(rng.choice(legal), rng) for _ in range(rng.randint(0, C.MAX_ACTIONS_PER_TURN))]
def play_random(seed: int, max_turns: int = 50) -> tuple[dict, list]:
rng = random.Random(seed)
state = E.new(seed, max_turns)
log = []
while not E.is_over(state):
a0, a1 = random_actions(state, 0, rng), random_actions(state, 1, rng)
log.append((a0, a1))
state = E.apply_turn(state, a0, a1)
E.check_invariants(state)
return state, log
# --------------------------------------------------------------------------
# construction
# --------------------------------------------------------------------------
def test_new_is_symmetric_and_valid():
s = E.new(123)
E.check_invariants(s)
assert s["players"][0] == s["players"][1]
assert s["players"][0] is not s["players"][1]
assert s["players"][0]["resources"] is not s["players"][1]["resources"]
assert s["turn"] == 0 and not E.is_over(s)
assert s["players"][0]["keep_hp"] == C.KEEP_MAX_HP
def test_new_same_seed_same_state_and_seeds_differ():
assert E.new(7) == E.new(7)
starts = {json.dumps(E.new(seed)["players"][0]["resources"], sort_keys=True) for seed in range(50)}
assert len(starts) > 10
@pytest.mark.parametrize("seed", [1.5, "1", None, True])
def test_new_rejects_bad_seed(seed):
with pytest.raises(ValueError):
E.new(seed)
@pytest.mark.parametrize("max_turns", [0, -1, C.MAX_MAX_TURNS + 1, 2.0, True])
def test_new_rejects_bad_max_turns(max_turns):
with pytest.raises(ValueError):
E.new(1, max_turns)
@pytest.mark.parametrize("player", [-1, 2, "0", None, True])
def test_player_index_is_validated(player):
s = E.new(1)
for fn in (E.legal_actions, E.observation, E.score):
with pytest.raises(ValueError):
fn(s, player)
# --------------------------------------------------------------------------
# determinism
# --------------------------------------------------------------------------
@pytest.mark.parametrize("seed", range(20))
def test_replay_is_deterministic(seed):
final, log = play_random(seed)
state = E.new(seed)
for a0, a1 in log:
state = E.apply_turn(state, a0, a1)
assert state == final
assert json.dumps(state, sort_keys=True) == json.dumps(final, sort_keys=True)
def test_json_roundtrip_mid_game_continues_identically():
rng = random.Random(5)
state = E.new(5)
for _ in range(15):
state = E.apply_turn(state, random_actions(state, 0, rng), random_actions(state, 1, rng))
restored = json.loads(json.dumps(state))
assert restored == state
rng_a, rng_b = random.Random(99), random.Random(99)
a, b = state, restored
while not E.is_over(a):
a = E.apply_turn(a, random_actions(a, 0, rng_a), random_actions(a, 1, rng_a))
b = E.apply_turn(b, random_actions(b, 0, rng_b), random_actions(b, 1, rng_b))
assert a == b
def test_determinism_does_not_depend_on_hash_seed():
"""The same game replayed in fresh interpreters with different hash seeds."""
import hashlib
import os
import subprocess
import sys
from pathlib import Path
root = Path(__file__).resolve().parents[1]
script = (
"import hashlib, json, sys; sys.path.insert(0, sys.argv[1]);"
"from stronghold.sim.balance import play_match;"
"blob = json.dumps([play_match(a, b, 7) for a in ('random', 'rush') for b in ('random', 'eco_turtle')], sort_keys=True);"
"print(hashlib.sha256(blob.encode()).hexdigest())"
)
digests = set()
for hash_seed in ("0", "1", "12345"):
env = {**os.environ, "PYTHONHASHSEED": hash_seed}
out = subprocess.run([sys.executable, "-c", script, str(root)], env=env, capture_output=True, text=True, check=True)
digests.add(out.stdout.strip())
assert len(digests) == 1 and len(next(iter(digests))) == hashlib.sha256().digest_size * 2
def test_apply_turn_does_not_mutate_inputs():
rng = random.Random(3)
state = E.new(3)
for _ in range(25):
a0, a1 = random_actions(state, 0, rng), random_actions(state, 1, rng)
before = copy.deepcopy((state, a0, a1))
new_state = E.apply_turn(state, a0, a1)
assert (state, a0, a1) == before
state = new_state
if E.is_over(state):
break
def test_read_only_functions_do_not_mutate_state():
state, _ = play_random(4, max_turns=20)
before = copy.deepcopy(state)
for player in (0, 1):
E.observation(state, player)
E.legal_actions(state, player)
E.score(state, player)
E.is_over(state), E.result(state), E.check_invariants(state)
assert state == before
def test_observation_is_a_copy():
s = E.new(1)
obs = E.observation(s, 0)
obs["you"]["resources"]["gold"] = 10**9
obs["opponent"]["army_scouted"]["knight"] = 10**9
assert E.observation(s, 0)["you"]["resources"]["gold"] != 10**9
E.check_invariants(s)
@pytest.mark.parametrize("seed", range(10))
def test_seat_symmetry(seed):
"""Swapping the two players' actions yields the mirrored game."""
rng = random.Random(seed)
a = E.new(seed)
b = E.new(seed)
while not E.is_over(a):
x, y = random_actions(a, 0, rng), random_actions(a, 1, rng)
a = E.apply_turn(a, x, y)
b = E.apply_turn(b, y, x)
assert a["players"][0] == b["players"][1]
assert a["players"][1] == b["players"][0]
assert a["last_errors"][0] == b["last_errors"][1]
wa, wb = E.winner(a), E.winner(b)
assert (wa is None and wb is None) or wa == 1 - wb
# --------------------------------------------------------------------------
# robustness
# --------------------------------------------------------------------------
@pytest.mark.parametrize("seed", range(200))
def test_random_games_never_crash(seed):
state, _ = play_random(seed)
assert E.is_over(state)
assert state["turn"] <= state["max_turns"]
outcome = E.result(state)
assert outcome["winner"] in (0, 1, None)
assert outcome["reason"] in ("keep_destroyed", "double_ko", "points")
assert E.winner(state) == outcome["winner"]
GARBAGE_VALUES = [
None, True, False, 0, 1, -1, 5, 10**30, -(10**30), 0.5, float("nan"), float("inf"), "", "farm", "pikeman",
"build", "attack", [], [1, 2], {}, {"pikeman": 1}, {"pikeman": -1}, {"pikeman": 10**9}, {"dragon": 1},
{"pikeman": 1.5}, {"pikeman": True}, {"a": {"b": {"c": []}}}, "x" * 5000, b"bytes", (1, 2), {1: 2},
]
GARBAGE_KEYS = ["type", "what", "unit", "count", "units", "sell", "buy", "extra", "reasoning"]
GARBAGE_TYPES = ["build", "recruit", "trade", "repair", "attack", "nuke", "", None, 7]
def garbage_action(rng: random.Random):
roll = rng.random()
if roll < 0.15:
return rng.choice(GARBAGE_VALUES)
action = {"type": rng.choice(GARBAGE_TYPES)}
for key in rng.sample(GARBAGE_KEYS[1:], rng.randint(0, 5)):
pool = GARBAGE_VALUES + list(C.BUILDINGS) + list(C.UNITS) + list(C.RESOURCES)
action[key] = rng.choice(pool)
return action
def garbage_action_list(rng: random.Random):
roll = rng.random()
if roll < 0.05:
return rng.choice([None, "attack", 7, {"type": "build", "what": "farm"}, 3.5, True])
items = [garbage_action(rng) for _ in range(rng.randint(0, 9))]
return tuple(items) if roll < 0.1 else items
@pytest.mark.parametrize("seed", range(100))
def test_garbage_actions_never_crash_or_corrupt(seed):
rng = random.Random(1000 + seed)
state = E.new(seed)
while not E.is_over(state):
if rng.random() < 0.5:
acts = [garbage_action_list(rng), random_actions(state, 1, rng)]
else:
acts = [random_actions(state, 0, rng), garbage_action_list(rng)]
state = E.apply_turn(state, acts[0], acts[1])
E.check_invariants(state)
for player in (0, 1):
json.dumps(E.observation(state, player), allow_nan=False)
for err in state["last_errors"][player]:
assert set(err) == {"index", "action", "error"}
assert isinstance(err["error"], str) and err["error"]
def test_every_legal_action_applies_without_error():
rng = random.Random(11)
state = E.new(11)
checked = set()
while not E.is_over(state):
for player in (0, 1):
for descriptor in E.legal_actions(state, player):
variants = [instantiate(descriptor, rng)]
if descriptor["type"] == "recruit":
variants.append({**variants[0], "count": descriptor["count"]["max"]})
if descriptor["type"] == "attack":
variants.append({"type": "attack", "units": {u: b["max"] for u, b in descriptor["units"].items()}})
for action in variants:
acts = [None, None]
acts[player] = [action]
out = E.apply_turn(state, acts[0], acts[1])
assert out["last_errors"][player] == [], (action, out["last_errors"][player])
checked.add(action["type"])
state = E.apply_turn(state, random_actions(state, 0, rng), random_actions(state, 1, rng))
assert checked == {"build", "recruit", "trade", "repair", "attack"}
def test_legal_actions_empty_when_over_and_apply_turn_raises():
state, _ = play_random(2, max_turns=5)
assert E.legal_actions(state, 0) == [] and E.legal_actions(state, 1) == []
with pytest.raises(ValueError):
E.apply_turn(state, [], [])
def test_winner_raises_while_running():
s = E.new(1)
with pytest.raises(ValueError):
E.winner(s)
assert E.result(s) == {"over": False, "winner": None, "reason": None, "scores": [E.score(s, 0), E.score(s, 1)]}
# --------------------------------------------------------------------------
# rules: actions
# --------------------------------------------------------------------------
def test_action_limit_per_turn():
s = rich_state()
acts = [{"type": "build", "what": "farm"}] * 7
out = E.apply_turn(s, acts, [])
assert out["players"][0]["buildings"]["farm"] == s["players"][0]["buildings"]["farm"] + C.MAX_ACTIONS_PER_TURN
assert [e["index"] for e in out["last_errors"][0]] == [5, 6]
assert out["last_errors"][1] == []
@pytest.mark.parametrize("building", list(C.BUILDINGS))
def test_build_costs_and_caps(building):
s = rich_state()
spec = C.BUILDINGS[building]
out = E.apply_turn(s, [{"type": "build", "what": building}], [])
assert out["players"][0]["buildings"][building] == s["players"][0]["buildings"][building] + 1
assert out["last_errors"][0] == []
s["players"][0]["buildings"][building] = spec["cap"]
out = E.apply_turn(s, [{"type": "build", "what": building}], [])
assert out["players"][0]["buildings"][building] == spec["cap"]
assert "limit" in out["last_errors"][0][0]["error"]
def test_build_spends_exact_cost_and_fails_when_poor():
s = E.new(0)
p = s["players"][0]
p["resources"] = {"wood": 60, "stone": 40, "food": 100, "gold": 0}
p["pop"] = 0 # no production, no tax, no consumption
p["buildings"]["farm"] = p["buildings"]["woodcutter"] = 0
out = E.apply_turn(s, [{"type": "build", "what": "barracks"}, {"type": "build", "what": "farm"}], [])
q = out["players"][0]
assert q["buildings"]["barracks"] == 1 and q["buildings"]["farm"] == 0
assert q["resources"]["wood"] == 0 and q["resources"]["stone"] == 0
assert len(out["last_errors"][0]) == 1 and out["last_errors"][0][0]["index"] == 1
def test_recruit_requires_barracks_pop_and_capacity():
s = rich_state()
out = E.apply_turn(s, [{"type": "recruit", "unit": "pikeman", "count": 1}], [])
assert "barracks" in out["last_errors"][0][0]["error"]
s["players"][0]["buildings"]["barracks"] = 1
acts = [
{"type": "recruit", "unit": "pikeman", "count": 2},
{"type": "recruit", "unit": "archer", "count": 2}, # exceeds 3 per barracks
{"type": "recruit", "unit": "knight", "count": 1},
]
out = E.apply_turn(s, acts, [])
assert out["players"][0]["army"] == units(pikeman=2, knight=1)
assert [e["index"] for e in out["last_errors"][0]] == [1]
s["players"][0]["pop"] = 1
out = E.apply_turn(s, [{"type": "recruit", "unit": "pikeman", "count": 2}], [])
assert "population" in out["last_errors"][0][0]["error"]
assert out["players"][0]["army"] == NO_UNITS
def test_recruit_converts_population_and_costs_resources():
s = rich_state()
p = s["players"][0]
p["buildings"]["barracks"] = 1
p["buildings"]["house"] = 0
p["pop"] = 10 # at cap, so no growth hides the conversion... cap is 10
out = E.apply_turn(s, [{"type": "recruit", "unit": "knight", "count": 2}], [])
q = out["players"][0]
assert q["army"]["knight"] == 2
assert q["pop"] == 10 # 10 - 2 recruited + 2 growth (well fed)
cost = C.UNIT_STATS["knight"]["cost"]
assert q["resources"]["stone"] == 5000 - 2 * cost["stone"]
def test_units_recruited_this_turn_are_in_training():
"""Fresh recruits neither attack nor defend until the next turn."""
s = rich_state()
s["players"][0]["buildings"]["barracks"] = 1
acts = [{"type": "recruit", "unit": "pikeman", "count": 3}, {"type": "attack", "units": {"pikeman": 1}}]
out = E.apply_turn(s, acts, [])
assert out["players"][0]["army"]["pikeman"] == 3
assert "training" in out["last_errors"][0][0]["error"]
assert not any(e["type"] == "battle" for e in out["last_events"])
s["players"][1]["army"] = units(knight=1)
out = E.apply_turn(s, [acts[0]], [{"type": "attack", "units": {"knight": 1}}])
battle = next(e for e in out["last_events"] if e["type"] == "battle")
assert battle["garrison"] == NO_UNITS and battle["attacker_won"]
assert out["players"][0]["army"]["pikeman"] == 3 # trainees are not casualties
# One turn later the same recruits can attack and do defend.
nxt = E.apply_turn(out, [{"type": "attack", "units": {"pikeman": 2}}], [{"type": "attack", "units": {"knight": 1}}])
assert nxt["last_errors"] == [[], []]
defence = next(e for e in nxt["last_events"] if e["type"] == "battle" and e["attacker"] == 1)
assert defence["garrison"] == units(pikeman=1) and not defence["attacker_won"]
def test_only_one_attack_and_one_repair_per_turn():
s = rich_state()
s["players"][0]["army"] = units(pikeman=4)
s["players"][0]["keep_hp"] = 50
acts = [
{"type": "attack", "units": {"pikeman": 2}},
{"type": "attack", "units": {"pikeman": 2}},
{"type": "repair"},
{"type": "repair"},
]
out = E.apply_turn(s, acts, [])
assert [e["index"] for e in out["last_errors"][0]] == [1, 3]
assert out["players"][0]["keep_hp"] == 50 + C.REPAIR_HP
assert sum(e["type"] == "battle" for e in out["last_events"]) == 1
def test_repair_never_exceeds_max_and_is_illegal_at_full_hp():
s = rich_state()
s["players"][0]["keep_hp"] = C.KEEP_MAX_HP - 1
out = E.apply_turn(s, [{"type": "repair"}], [{"type": "repair"}])
assert out["players"][0]["keep_hp"] == C.KEEP_MAX_HP
assert "full" in out["last_errors"][1][0]["error"]
def test_trade_rules():
s = rich_state()
out = E.apply_turn(s, [{"type": "trade", "sell": "wood"}], [])
assert "market" in out["last_errors"][0][0]["error"]
s["players"][0]["buildings"]["market"] = 1
s["players"][0]["pop"] = 0
acts = [
{"type": "trade", "sell": "stone"},
{"type": "trade", "buy": "food"},
{"type": "trade", "sell": "wood"}, # third trade with one market
{"type": "trade", "sell": "gold"},
{"type": "trade", "sell": "wood", "buy": "food"},
]
out = E.apply_turn(s, acts, [])
q = out["players"][0]["resources"]
assert q["stone"] == 5000 - C.TRADE_LOT
assert q["food"] == 5000 + C.TRADE_LOT
assert q["gold"] == 5000 + C.TRADE_SELL_GOLD["stone"] - C.TRADE_BUY_GOLD["food"]
assert q["wood"] == 5000
assert [e["index"] for e in out["last_errors"][0]] == [2, 3, 4]
def test_trading_is_never_profitable_in_a_loop():
for resource in C.TRADE_SELL_GOLD:
assert C.TRADE_SELL_GOLD[resource] < C.TRADE_BUY_GOLD[resource]
# --------------------------------------------------------------------------
# rules: economy
# --------------------------------------------------------------------------
def test_production_matches_spec_numbers():
assert C.PRODUCTION["woodcutter"] == ("wood", 8)
assert C.PRODUCTION["quarry"] == ("stone", 6)
assert C.PRODUCTION["farm"] == ("food", 10)
assert C.HOUSE_POP_CAP == 5
def test_production_tax_and_food_upkeep():
s = E.new(0)
p = s["players"][0]
p["resources"] = {"wood": 0, "stone": 0, "food": 100, "gold": 0}
p["pop"] = 10
p["buildings"].update({"farm": 2, "woodcutter": 3, "quarry": 1, "market": 1})
out = E.apply_turn(s, [], [])
q = out["players"][0]["resources"]
assert q == {"wood": 24, "stone": 6, "food": 100 + 20 - 10, "gold": 5 + 6}
assert E.observation(s, 0)["you"]["income_per_turn"] == {"wood": 24, "stone": 6, "food": 10, "gold": 11}
def test_unstaffed_buildings_do_not_produce():
s = E.new(0)
p = s["players"][0]
p["resources"] = {"wood": 0, "stone": 0, "food": 100, "gold": 0}
p["pop"] = 3
p["buildings"].update({"farm": 2, "woodcutter": 2, "quarry": 2, "market": 2})
assert E.observation(s, 0)["you"]["staffed"] == {"farm": 2, "woodcutter": 1, "quarry": 0, "market": 0}
out = E.apply_turn(s, [], [])
assert out["players"][0]["resources"] == {"wood": 8, "stone": 0, "food": 100 + 20 - 3, "gold": 1}
def test_starvation_reduces_population():
s = E.new(0)
p = s["players"][0]
p["resources"]["food"] = 0
p["buildings"]["farm"] = 0
p["pop"] = 9
out = E.apply_turn(s, [], [])
assert out["players"][0]["pop"] == 9 - 5 # deficit 9 -> lose ceil(9/2)
assert out["players"][0]["resources"]["food"] == 0
assert {"type": "starvation", "player": 0, "pop_lost": 5} in out["last_events"]
obs_events = E.observation(out, 1)["last_turn"]["events"]
assert {"type": "starvation", "who": "opponent", "pop_lost": 5} in obs_events
def test_population_growth_respects_cap():
s = E.new(0)
p = s["players"][0]
p["resources"]["food"] = 1000
p["pop"] = 9
out = E.apply_turn(s, [], [])
assert out["players"][0]["pop"] == C.BASE_POP_CAP
out = E.apply_turn(out, [], [])
assert out["players"][0]["pop"] == C.BASE_POP_CAP
out = E.apply_turn(out, [{"type": "build", "what": "house"}], [])
assert out["players"][0]["pop"] == C.BASE_POP_CAP + 2
def test_gold_upkeep_and_desertion():
s = E.new(0)
p = s["players"][0]
p["pop"] = 0
p["resources"]["gold"] = 4
p["army"] = units(pikeman=2, archer=1, knight=3) # upkeep 2 + 1 + 6 = 9
out = E.apply_turn(s, [], [])
q = out["players"][0]
assert q["resources"]["gold"] == 0
assert q["army"] == units(pikeman=0, archer=0, knight=2) # unpaid 5: 2 pikemen, 1 archer, 1 knight
event = next(e for e in out["last_events"] if e["type"] == "desertion")
assert event == {"type": "desertion", "player": 0, "units_lost": units(pikeman=2, archer=1, knight=1)}
p["resources"]["gold"] = 9
out = E.apply_turn(s, [], [])
assert out["players"][0]["army"] == p["army"] and out["players"][0]["resources"]["gold"] == 0
# --------------------------------------------------------------------------
# rules: combat
# --------------------------------------------------------------------------
def test_unit_triangle():
equal = {"pikeman": units(pikeman=20), "archer": units(archer=20), "knight": units(knight=10)}
for hunter, prey in C.COUNTERS.items():
strong = E.estimate_battle(equal[hunter], equal[prey])
weak = E.estimate_battle(equal[prey], equal[hunter])
assert strong["attacker_strength"] > weak["attacker_strength"]
assert not weak["attacker_won"]
assert E.estimate_battle(equal["pikeman"], equal["knight"])["attacker_won"]
assert E.estimate_battle(equal["knight"], equal["archer"])["attacker_won"]
def test_towers_and_walls_help_the_defender():
att, dfn = units(pikeman=10), units(pikeman=8)
base = E.estimate_battle(att, dfn)
towers = E.estimate_battle(att, dfn, towers=3)
walls = E.estimate_battle(att, dfn, walls=3)
assert base["attacker_won"] and not towers["attacker_won"]
assert towers["defender_strength"] > base["defender_strength"]
assert walls["attacker_won"] and 0 < walls["keep_damage"] < base["keep_damage"]
alone = E.estimate_battle(units(pikeman=1), NO_UNITS, towers=3)
assert not alone["attacker_won"] # towers defend even an empty keep
def test_attack_on_empty_keep_deals_siege_damage_without_losses():
s = E.new(0)
s["players"][0]["army"] = units(pikeman=4, knight=2)
s["players"][0]["resources"]["gold"] = 100
out = E.apply_turn(s, [{"type": "attack", "units": {"pikeman": 4, "knight": 2}}], [])
battle = out["last_events"][0]
assert battle["attacker_won"] and battle["attacker_losses"] == NO_UNITS
assert battle["keep_damage"] == 4 * 3 + 2 * 5
assert out["players"][1]["keep_hp"] == C.KEEP_MAX_HP - 22
assert out["players"][0]["army"] == units(pikeman=4, knight=2)
def test_failed_attack_costs_units_and_does_no_damage():
s = E.new(0)
s["players"][0]["army"] = units(knight=4)
s["players"][1]["army"] = units(pikeman=10)
for p in s["players"]:
p["resources"]["gold"] = 500
out = E.apply_turn(s, [{"type": "attack", "units": {"knight": 4}}], [])
battle = out["last_events"][0]
assert not battle["attacker_won"] and battle["keep_damage"] == 0
assert out["players"][1]["keep_hp"] == C.KEEP_MAX_HP
assert out["players"][0]["army"]["knight"] < 4
assert out["players"][1]["army"]["pikeman"] >= 8
def test_units_sent_to_attack_do_not_defend():
s = E.new(0)
for p in s["players"]:
p["army"] = units(pikeman=5)
p["resources"]["gold"] = 500
all_in = [{"type": "attack", "units": {"pikeman": 5}}]
out = E.apply_turn(s, all_in, all_in)
battles = [e for e in out["last_events"] if e["type"] == "battle"]
assert len(battles) == 2
assert all(b["garrison"] == NO_UNITS and b["attacker_won"] for b in battles)
assert out["players"][0]["keep_hp"] == out["players"][1]["keep_hp"] == C.KEEP_MAX_HP - 15
def test_combat_noise_is_bounded_and_seeded():
outcomes = set()
for seed in range(40):
s = E.new(seed)
s["players"][0]["army"] = units(pikeman=10)
s["players"][1]["army"] = units(pikeman=10)
for p in s["players"]:
p["resources"]["gold"] = 500
out = E.apply_turn(s, [{"type": "attack", "units": {"pikeman": 10}}], [])
battle = out["last_events"][0]
assert 100 * (1 - C.COMBAT_NOISE) <= battle["attacker_strength"] <= 100 * (1 + C.COMBAT_NOISE)
assert 100 * (1 - C.COMBAT_NOISE) <= battle["defender_strength"] <= 100 * (1 + C.COMBAT_NOISE)
outcomes.add(battle["attacker_won"])
again = E.apply_turn(s, [{"type": "attack", "units": {"pikeman": 10}}], [])
assert again == out
assert outcomes == {True, False}
def test_estimate_battle_validates_input():
for bad in (None, {"dragon": 1}, {"pikeman": -1}, {"pikeman": 1.0}, NO_UNITS):
with pytest.raises(ValueError):
E.estimate_battle(bad, NO_UNITS)
with pytest.raises(ValueError):
E.estimate_battle(units(pikeman=1), NO_UNITS, towers=-1)
# --------------------------------------------------------------------------
# rules: end of game
# --------------------------------------------------------------------------
def test_keep_destruction_ends_the_game():
s = E.new(0)
s["players"][0]["army"] = units(knight=40)
s["players"][0]["resources"]["gold"] = 1000
out = E.apply_turn(s, [{"type": "attack", "units": {"knight": 40}}], [])
assert out["players"][1]["keep_hp"] == 0
assert E.is_over(out) and E.winner(out) == 0
assert E.result(out)["reason"] == "keep_destroyed"
def test_double_ko_is_decided_on_points():
s = E.new(0)
for p in s["players"]:
p["army"] = units(knight=40)
p["resources"]["gold"] = 1000
s["players"][1]["resources"]["wood"] += 500
all_in = [{"type": "attack", "units": {"knight": 40}}]
out = E.apply_turn(s, all_in, all_in)
outcome = E.result(out)
assert outcome["reason"] == "double_ko" and outcome["winner"] == 1
s["players"][1]["resources"]["wood"] -= 500
assert E.result(E.apply_turn(s, all_in, all_in))["winner"] is None
def test_turn_limit_and_points_victory():
s = E.new(0, max_turns=3)
for _ in range(3):
assert not E.is_over(s)
s = E.apply_turn(s, [{"type": "build", "what": "farm"}], [])
assert E.is_over(s) and s["turn"] == 3
outcome = E.result(s)
assert outcome["reason"] == "points"
assert outcome["scores"] == [E.score(s, 0), E.score(s, 1)]
assert outcome["winner"] == (0 if outcome["scores"][0] > outcome["scores"][1] else 1)
def test_identical_play_is_a_draw():
s = E.new(9, max_turns=10)
while not E.is_over(s):
s = E.apply_turn(s, [{"type": "build", "what": "house"}], [{"type": "build", "what": "house"}])
assert E.winner(s) is None and E.result(s)["reason"] == "points"
# --------------------------------------------------------------------------
# observation
# --------------------------------------------------------------------------
def test_observation_hides_opponent_economy_and_is_json():
state, _ = play_random(6, max_turns=30)
for player in (0, 1):
obs = E.observation(state, player)
json.dumps(obs, allow_nan=False)
assert obs["player"] == player
assert "resources" not in obs["opponent"] and "income_per_turn" not in obs["opponent"]
assert obs["you"]["resources"] == state["players"][player]["resources"]
assert "army" not in obs["opponent"]
assert obs["opponent"]["army_scouted"] == state["scouted_army"][1 - player]
assert obs["opponent"]["army_scouted_turn"] == state["turn"] - 1
assert obs["you"]["army"] == state["players"][player]["army"]
assert obs["last_turn"]["your_errors"] == state["last_errors"][player]
assert obs["turns_left"] == state["max_turns"] - state["turn"]
def test_observation_reports_battles_from_own_perspective():
s = E.new(0)
s["players"][0]["army"] = units(pikeman=3)
s["players"][0]["resources"]["gold"] = 100
out = E.apply_turn(s, [{"type": "attack", "units": {"pikeman": 3}}], [])
mine = E.observation(out, 0)["last_turn"]["events"][0]
theirs = E.observation(out, 1)["last_turn"]["events"][0]
assert mine["you_attacked"] is True and theirs["you_attacked"] is False
assert "attacker" not in mine and mine["sent"] == units(pikeman=3)
def test_enemy_army_is_scouted_one_turn_late():
s = rich_state()
s["players"][1]["buildings"]["barracks"] = 2
assert E.observation(s, 0)["opponent"]["army_scouted"] == NO_UNITS
s1 = E.apply_turn(s, [], [{"type": "recruit", "unit": "archer", "count": 4}])
assert s1["players"][1]["army"] == units(archer=4)
assert E.observation(s1, 0)["opponent"]["army_scouted"] == NO_UNITS # hired during turn 0
assert E.observation(s1, 1)["you"]["army"] == units(archer=4)
s2 = E.apply_turn(s1, [], [{"type": "recruit", "unit": "knight", "count": 1}])
seen = E.observation(s2, 0)["opponent"]
assert seen["army_scouted"] == units(archer=4) and seen["army_scouted_turn"] == 1
assert s2["players"][1]["army"] == units(archer=4, knight=1)
def test_errors_are_reported_only_for_the_turn_they_happened():
s = E.new(0)
out = E.apply_turn(s, [{"type": "build", "what": "castle"}], [])
assert len(E.observation(out, 0)["last_turn"]["your_errors"]) == 1
assert E.observation(out, 1)["last_turn"]["your_errors"] == []
out = E.apply_turn(out, [], [])
assert E.observation(out, 0)["last_turn"]["your_errors"] == []
def test_check_invariants_detects_corruption():
for mutate in (
lambda s: s["players"][0]["resources"].__setitem__("gold", -1),
lambda s: s["players"][1].__setitem__("pop", 10**6),
lambda s: s["players"][0]["army"].__setitem__("knight", 1.5),
lambda s: s["players"][0]["buildings"].__setitem__("tower", 99),
lambda s: s["players"][0].__setitem__("keep_hp", C.KEEP_MAX_HP + 1),
lambda s: s.__setitem__("turn", -1),
):
s = E.new(0)
mutate(s)
with pytest.raises(ValueError):
E.check_invariants(s)
# --------------------------------------------------------------------------
# monster raids
# --------------------------------------------------------------------------
NO_MONSTERS = {m: 0 for m in C.MONSTERS}
def horde(**kw):
return {**NO_MONSTERS, **kw}
def raid_state(monsters, turn=10, seed=0):
"""A state whose next turn (turn+1) is a raid with `monsters`."""
s = E.new(seed)
s["turn"] = turn
s["raids"] = [{"turn": turn + 1, "monsters": dict(monsters)}]
for p in s["players"]:
p["resources"] = {r: 1000 for r in C.RESOURCES}
E.check_invariants(s)
return s
def test_raid_schedule_is_seeded_ordered_and_grows():
for seed in range(30):
raids = E.new(seed)["raids"]
assert raids == E.new(seed)["raids"]
turns = [r["turn"] for r in raids]
assert C.RAID_FIRST_TURN[0] <= turns[0] <= C.RAID_FIRST_TURN[1]
assert all(C.RAID_GAP[0] <= b - a <= C.RAID_GAP[1] for a, b in zip(turns, turns[1:]))
assert turns[-1] <= C.DEFAULT_MAX_TURNS
power = [sum(n * C.MONSTERS[m]["power"] for m, n in r["monsters"].items()) for r in raids]
assert power == sorted(power) or power[-1] > power[0]
dragons = [r for r in raids if r["monsters"]["dragon"]]
assert len(dragons) <= 1 and all(r["turn"] >= C.DRAGON_FROM_TURN for r in dragons)
for r in raids:
pool = next(p for start, p in reversed(C.RAID_POOLS) if r["turn"] >= start)
assert all(n == 0 or m in pool or m == "dragon" for m, n in r["monsters"].items())
assert len({json.dumps(E.new(seed)["raids"]) for seed in range(30)}) > 20
assert all(r["turn"] <= 20 for r in E.new(1, max_turns=20)["raids"])
def test_raid_hits_both_players_identically_and_pays_bounty():
s = raid_state(horde(wolf=3, goblin=2))
s["players"][0]["army"] = units(pikeman=8) # strong home defence
out = E.apply_turn(s, [], [])
raids = {e["player"]: e for e in out["last_events"] if e["type"] == "raid"}
assert set(raids) == {0, 1}
assert raids[0]["monsters"] == raids[1]["monsters"] == horde(wolf=3, goblin=2)
assert raids[0]["repelled"] and not raids[1]["repelled"]
assert raids[0]["bounty"] == sum(raids[0]["monsters_killed"][m] * C.MONSTERS[m]["bounty"] for m in C.MONSTERS) > 0
assert raids[1]["keep_damage"] > 0 and raids[1]["bounty"] == 0
assert out["players"][1]["keep_hp"] == C.KEEP_MAX_HP - raids[1]["keep_damage"]
assert out["players"][0]["keep_hp"] == C.KEEP_MAX_HP
gold_without = E.apply_turn(raid_state(horde(wolf=1)) | {"raids": []}, [], [])["players"][0]["resources"]["gold"]
assert out["players"][0]["resources"]["gold"] > gold_without - 10
assert E.observation(out, 1)["last_turn"]["events"][0]["who"] in ("you", "opponent")
def test_only_units_at_home_fight_monsters():
s = raid_state(horde(orc=2))
s["players"][0]["army"] = units(knight=6)
out = E.apply_turn(s, [{"type": "attack", "units": {"knight": 6}}], [])
raid = next(e for e in out["last_events"] if e["type"] == "raid" and e["player"] == 0)
assert raid["garrison"] == NO_UNITS and not raid["repelled"]
stay = E.apply_turn(s, [], [])
raid = next(e for e in stay["last_events"] if e["type"] == "raid" and e["player"] == 0)
assert raid["garrison"] == units(knight=6) and raid["repelled"]
# recruits in training do not fight either
s["players"][0]["army"] = NO_UNITS.copy()
s["players"][0]["buildings"]["barracks"] = 2
s["players"][0]["pop"] = 10
hired = E.apply_turn(s, [{"type": "recruit", "unit": "knight", "count": 6}], [])
raid = next(e for e in hired["last_events"] if e["type"] == "raid" and e["player"] == 0)
assert raid["garrison"] == NO_UNITS and hired["players"][0]["army"]["knight"] == 6
def test_defenders_lost_in_a_battle_do_not_fight_the_raid():
s = raid_state(horde(wolf=2))
s["players"][0]["army"] = units(pikeman=4)
s["players"][1]["army"] = units(knight=10)
out = E.apply_turn(s, [], [{"type": "attack", "units": {"knight": 10}}])
battle = next(e for e in out["last_events"] if e["type"] == "battle")
raid = next(e for e in out["last_events"] if e["type"] == "raid" and e["player"] == 0)
expected = {u: 4 * (u == "pikeman") - battle["defender_losses"][u] for u in C.UNITS}
assert raid["garrison"] == expected
def test_counters_and_flying_dragon():
weak = E.estimate_raid(units(archer=10), horde(troll=1))
strong = E.estimate_raid(units(pikeman=10), horde(troll=1))
assert strong["defender_strength"] > weak["defender_strength"] / C.ARCHER_DEFENSE_MULT
assert E.estimate_raid(units(archer=10), horde(dragon=1))["defender_strength"] > E.estimate_raid(units(archer=10), horde(orc=7))["defender_strength"]
ground = E.estimate_raid(NO_UNITS, horde(troll=2), walls=0)["keep_damage"]
walled = E.estimate_raid(NO_UNITS, horde(troll=2), walls=5)["keep_damage"]
assert walled < ground
sky = E.estimate_raid(NO_UNITS, horde(dragon=1), walls=0)["keep_damage"]
assert E.estimate_raid(NO_UNITS, horde(dragon=1), walls=5)["keep_damage"] == sky == C.MONSTERS["dragon"]["siege"]
for bad in ({"dragon": -1}, {"kraken": 1}, NO_MONSTERS, None):
with pytest.raises(ValueError):
E.estimate_raid(NO_UNITS, bad)
def test_monsters_can_destroy_a_keep_and_decide_the_game():
s = raid_state(horde(dragon=1, troll=3))
s["players"][0]["keep_hp"] = 20
s["players"][1]["army"] = units(archer=30)
out = E.apply_turn(s, [], [])
assert out["players"][0]["keep_hp"] == 0 and out["players"][1]["keep_hp"] > 0
assert E.is_over(out) and E.winner(out) == 1 and E.result(out)["reason"] == "keep_destroyed"
def test_breached_garrison_loses_only_part_of_its_units():
out = E.estimate_raid(units(pikeman=4), horde(orc=5)) # 40 vs 80: breached
assert not out["repelled"] and 0 < out["defender_losses"]["pikeman"] < 4
assert out["keep_damage"] > 0
def test_observation_announces_the_next_raid():
s = E.new(4)
first = s["raids"][0]
obs = E.observation(s, 0)["monster_raids"]
assert obs == {"next": {"turn": first["turn"], "turns_until": first["turn"], "monsters": first["monsters"]}, "remaining": len(s["raids"])}
assert E.observation(s, 1)["monster_raids"] == obs
s["turn"] = s["raids"][-1]["turn"]
assert E.observation(s, 0)["monster_raids"] == {"next": None, "remaining": 0}
def test_invariants_reject_a_bad_raid_schedule():
for mutate in (
lambda s: s["raids"].append({"turn": 1, "monsters": horde(wolf=1)}),
lambda s: s["raids"][0]["monsters"].__setitem__("wolf", -1),
lambda s: s["raids"][0].__setitem__("monsters", NO_MONSTERS.copy()),
lambda s: s["raids"][0]["monsters"].__setitem__("kraken", 1),
):
s = E.new(0)
mutate(s)
with pytest.raises(ValueError):
E.check_invariants(s)