Files
tidewall/test/bots/test_bot_brain.gd
T
claudeandClaude Opus 5.5 4db605c33d M5: Bot looting, combat and tide awareness
BotBrain plays a match with the commands a player sends: it picks a landing
marker near the barge's route, loots points of interest (following their own
walking routes into huts, lofts and piers), fights opponents it can see,
bandages itself, and gets to ground the coming tide will leave dry. BotWorld
is the map every bot shares: loot markers, routes, and each tide phase's safe
ground, which is the dry land joined to the island's highest walkable ground.

Three difficulties (Tuning.BOT_DIFFICULTIES) set reaction time, sight range
and aim error. The server mixes them unless --bot-difficulty says otherwise.

NavGrid labels connected regions when it is built, so a goal that is cut off
is turned down without a search of the whole island (about 70 ms each).

make bot-matches plays 20 bot-only matches and checks winners, drownings and
difficulty. Seeds 101 to 120: 20 of 20 with a winner, 7 of 460 deaths were
drownings (1.5%), easy bots placed worst (13.7 against 11.8 and 12.0) and
hard bots took the most eliminations (186 against 137 and 132).

Closes #28

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 02:42:10 -05:00

325 lines
14 KiB
GDScript

extends TestCase
## Bot brains from issue M5: bots loot, fight, heal and keep ahead of the tide, using
## only what a player would know, and difficulty changes how well they do it. Bots only
## ever send PlayerCommands.
const FLOOR: float = 20.0
const HOME: Vector3 = Vector3(200.0, FLOOR, 200.0)
const TICKS: int = Tuning.TICK_RATE_HZ
## Yaw steps facing +x.
const FACING_X: int = PlayerCommand.YAW_STEPS / 4
var sim: Simulation
var grid: NavGrid
var world: BotWorld
var brains: Array[BotBrain] = []
var shots_by: Dictionary = {}
var first_shot: Dictionary = {}
func _setup(seed_value: int = 7, ground: SimGround = null) -> void:
sim = Simulation.new(seed_value, ground if ground != null else SimGround.flat(FLOOR))
brains.clear()
shots_by.clear()
first_shot.clear()
func _player(at: Vector3, yaw: int = 0) -> SimEntity:
var player: SimEntity = sim.entities.find(sim.add_player())
player.position = at
player.on_ground = true
player.yaw = yaw
return player
func _bot(at: Vector3, level: int = BotBrain.NORMAL, yaw: int = 0) -> BotBrain:
var brain: BotBrain = BotBrain.new(_player(at, yaw).id, level)
brains.append(brain)
return brain
func _arm(player: SimEntity, weapon: String = "dock_carbine", ammo: String = "cartridges", rounds: int = 150) -> void:
assert_eq(Inventory.give(player, ItemCatalog.code_of(weapon), 1), 0)
Inventory.give(player, ItemCatalog.code_of(ammo), rounds)
## Builds the grid and the bots' map. Call after the world and players are in place.
func _ready_world() -> void:
grid = NavGrid.build(sim)
world = BotWorld.build(sim, grid)
for entity: SimEntity in sim.entities.entities():
if entity.archetype == SimEntity.ARCHETYPE_PLAYER:
world.player_ids.append(entity.id)
## Steps the match `ticks` times, or until `until` returns true.
func _run(ticks: int, until: Callable = Callable()) -> void:
for _index: int in ticks:
grid.sync(sim)
world.observe(sim)
for brain: BotBrain in brains:
var command: PlayerCommand = brain.think(sim, grid, world)
assert_true(command is PlayerCommand)
sim.submit_command(brain.player_id, command)
sim.step()
for event: Dictionary in sim.events:
if event["type"] == "shot":
shots_by[event["player"]] = int(shots_by.get(event["player"], 0)) + 1
if not first_shot.has(event["player"]):
first_shot[event["player"]] = sim.tick
if until.is_valid() and until.call():
return
func _holds(player: SimEntity, item: String) -> bool:
return player.slot_items.has(ItemCatalog.code_of(item))
func test_a_bot_picks_up_a_weapon_and_its_ammunition() -> void:
_setup()
var brain: BotBrain = _bot(HOME)
var me: SimEntity = sim.entities.find(brain.player_id)
Inventory.spawn_pickup(sim, HOME + Vector3(7.0, 0.0, 0.0), ItemCatalog.code_of("dock_carbine"), 1)
Inventory.spawn_pickup(sim, HOME + Vector3(7.7, 0.0, 0.5), ItemCatalog.code_of("cartridges"), 30)
_ready_world()
_run(15 * TICKS, func() -> bool: return sim.pickups.is_empty())
assert_true(_holds(me, "dock_carbine"), "picked up the carbine")
assert_eq(Inventory.count_of(me, ItemCatalog.code_of("cartridges")), 30)
assert_true(sim.pickups.is_empty(), "nothing left lying there")
func test_a_bot_with_full_slots_never_swaps() -> void:
_setup()
var brain: BotBrain = _bot(HOME)
var me: SimEntity = sim.entities.find(brain.player_id)
for item: String in ["dock_carbine", "signal_revolver", "fowling_piece", "sailcloth_bandage", "tar_patch"]:
Inventory.give(me, ItemCatalog.code_of(item), 1)
me.armor = Tuning.PLAYER_MAX_ARMOR
var before: PackedInt32Array = me.slot_items.duplicate()
var pickup_id: int = Inventory.spawn_pickup(sim, HOME + Vector3(3.0, 0.0, 0.0), ItemCatalog.code_of("harpoon_gun"), 1)
_ready_world()
assert_false(brain.wants(me, sim.entities.find(pickup_id)))
_run(6 * TICKS)
assert_eq(me.slot_items, before)
assert_true(sim.pickups.has(pickup_id), "the harpoon gun is still on the ground")
func test_bots_leave_thrown_weapons_and_tools_that_do_no_damage() -> void:
_setup()
var brain: BotBrain = _bot(HOME)
var me: SimEntity = sim.entities.find(brain.player_id)
var keg: int = Inventory.spawn_pickup(sim, HOME + Vector3(3.0, 0.0, 0.0), ItemCatalog.code_of("powder_keg"), 2)
var line: int = Inventory.spawn_pickup(sim, HOME + Vector3(3.0, 0.0, 1.0), ItemCatalog.code_of("line_thrower"), 1)
assert_false(brain.wants(me, sim.entities.find(keg)))
assert_false(brain.wants(me, sim.entities.find(line)))
func test_a_bot_walks_to_a_marker_and_opens_its_chest() -> void:
_setup()
var brain: BotBrain = _bot(HOME)
var me: SimEntity = sim.entities.find(brain.player_id)
var spot: Vector3 = HOME + Vector3(0.0, 0.0, 30.0)
sim.loot.chest_positions.append(spot)
sim.loot.chest_sources.append("hamlet")
sim.loot.chest_contents.append([
PackedInt32Array([ItemCatalog.code_of("signal_revolver"), 1, -1, 1]),
PackedInt32Array([ItemCatalog.code_of("cartridges"), 30, 0, 0]),
PackedInt32Array([ItemCatalog.code_of("sailcloth_bandage"), 3, 0, 0]),
])
sim.loot.chest_opened.append(0)
_ready_world()
world.markers.append(spot)
world.routes.append([])
_run(40 * TICKS, func() -> bool: return sim.loot.chest_opened[0] == 1 and sim.pickups.is_empty())
assert_eq(sim.loot.chest_opened[0], 1, "opened the chest")
assert_true(_holds(me, "signal_revolver"), "took the revolver")
assert_true(_holds(me, "sailcloth_bandage"), "took the bandages")
assert_eq(Inventory.count_of(me, ItemCatalog.code_of("cartridges")), 30)
func test_an_armed_bot_eliminates_an_opponent_it_can_see() -> void:
_setup()
var brain: BotBrain = _bot(HOME, BotBrain.HARD, FACING_X)
_arm(sim.entities.find(brain.player_id))
var victim: SimEntity = _player(HOME + Vector3(25.0, 0.0, 0.0))
_ready_world()
_run(30 * TICKS, func() -> bool: return victim.eliminated)
assert_true(victim.eliminated, "the opponent fell (health %d)" % victim.health)
assert_eq(victim.last_attacker, brain.player_id)
assert_eq(victim.last_cause, SimEntity.CAUSE_WEAPON)
func test_a_wall_in_the_way_hides_an_opponent() -> void:
_setup()
var brain: BotBrain = _bot(HOME, BotBrain.HARD, FACING_X)
_arm(sim.entities.find(brain.player_id))
_player(HOME + Vector3(25.0, 0.0, 0.0))
sim.ground.add_solid(AABB(HOME + Vector3(12.0, 0.0, -150.0), Vector3(1.0, 6.0, 300.0)))
_ready_world()
_run(4 * TICKS)
assert_eq(brain.target_id, 0, "nobody to see")
assert_true(shots_by.is_empty(), "no shots fired")
func test_an_opponent_behind_the_bot_goes_unseen_until_it_shoots() -> void:
_setup()
# Facing -x, away from the opponent 30 m off, further than a bot hears.
var brain: BotBrain = _bot(HOME, BotBrain.HARD, FACING_X * 3)
var me: SimEntity = sim.entities.find(brain.player_id)
_arm(me)
var other: SimEntity = _player(HOME + Vector3(30.0, 0.0, 0.0))
_ready_world()
# Send it walking straight on, so that wandering doesn't turn it round.
brain._hunt_goal = HOME - Vector3(150.0, 0.0, 0.0)
brain._hunt_until = 100 * TICKS
brain._go(brain._hunt_goal, 4.0)
_run(2 * TICKS)
assert_eq(brain.target_id, 0, "it hasn't seen who is behind it")
Weapons.damage_player(sim, me, 10, other.id)
_run(1)
assert_eq(brain.target_id, other.id, "a hit tells it who is there")
_run(3 * TICKS)
assert_true(int(shots_by.get(me.id, 0)) > 0, "and it fires back")
func test_bots_wait_out_their_reaction_time() -> void:
var firsts: Array[int] = []
for level: int in [BotBrain.EASY, BotBrain.HARD]:
_setup()
var brain: BotBrain = _bot(HOME, level, FACING_X)
_arm(sim.entities.find(brain.player_id))
_player(HOME + Vector3(20.0, 0.0, 0.0))
_ready_world()
_run(4 * TICKS, func() -> bool: return not first_shot.is_empty())
assert_true(first_shot.has(brain.player_id), "%s fired" % brain.difficulty_name())
var reaction: int = roundi(float(Tuning.BOT_DIFFICULTIES[level]["reaction"]) * TICKS)
firsts.append(int(first_shot.get(brain.player_id, 0)))
assert_true(firsts[-1] > reaction, "%s first fired on tick %d, after its %d-tick reaction" % [brain.difficulty_name(), firsts[-1], reaction])
assert_true(firsts[1] < firsts[0], "hard fires sooner than easy (%s)" % [firsts])
func test_harder_bots_win_most_duels_against_easier_ones() -> void:
var hard_wins: int = 0
var easy_wins: int = 0
var duels: int = 20
for duel: int in duels:
_setup(1000 + duel)
# Swap sides and entity order every other duel, so neither gets an edge from it.
var levels: Array[int] = [BotBrain.HARD, BotBrain.EASY]
if duel % 2 == 1:
levels.reverse()
var a: BotBrain = _bot(HOME, levels[0], FACING_X)
var b: BotBrain = _bot(HOME + Vector3(28.0, 0.0, 0.0), levels[1], FACING_X * 3)
_arm(sim.entities.find(a.player_id))
_arm(sim.entities.find(b.player_id))
_ready_world()
# Each has just spotted the other, so no duel is lost to a turned back.
a.target_id = b.player_id
b.target_id = a.player_id
var first: SimEntity = sim.entities.find(a.player_id)
var second: SimEntity = sim.entities.find(b.player_id)
_run(90 * TICKS, func() -> bool: return first.eliminated or second.eliminated)
if first.eliminated == second.eliminated:
print(" duel %d undecided: health %d/%d, rounds %s/%s, %.0f m apart, %s/%s, targets %d/%d visible %s/%s" % [duel, first.health, second.health, first.ammo, second.ammo, first.position.distance_to(second.position), a.state, b.state, a.target_id, b.target_id, a.target_visible, b.target_visible])
continue
var winner: BotBrain = b if first.eliminated else a
if winner.difficulty == BotBrain.HARD:
hard_wins += 1
else:
easy_wins += 1
print(" duels: hard won %d, easy won %d of %d" % [hard_wins, easy_wins, duels])
assert_true(hard_wins >= 15, "hard won %d of %d duels against easy" % [hard_wins, duels])
func test_a_hurt_bot_bandages_itself_when_nobody_is_about() -> void:
_setup()
var brain: BotBrain = _bot(HOME)
var me: SimEntity = sim.entities.find(brain.player_id)
me.health = 30
Inventory.give(me, ItemCatalog.code_of("sailcloth_bandage"), 3)
_ready_world()
_run(12 * TICKS, func() -> bool: return me.health >= 75)
assert_eq(me.health, 75, "bandaged up to the bandage's cap")
assert_eq(Inventory.count_of(me, ItemCatalog.code_of("sailcloth_bandage")), 1)
_run(5 * TICKS)
assert_eq(Inventory.count_of(me, ItemCatalog.code_of("sailcloth_bandage")), 1, "and doesn't waste the last one")
## Ground that climbs steadily along x: 0 m at the west edge, about 51 m at the east.
func _slope() -> SimGround:
var side: int = roundi(Tuning.WORLD_SIZE_METRES / 2.0) + 1
var values: PackedFloat32Array = PackedFloat32Array()
values.resize(side * side)
for z: int in side:
for x: int in side:
values[z * side + x] = x * 2.0 * 0.05
return SimGround.from_heights(values, side, 2.0)
func test_a_bot_on_low_ground_climbs_out_before_the_tide_arrives() -> void:
_setup(7, _slope())
# 3 m up: dry now, under the first tide level.
var brain: BotBrain = _bot(Vector3(60.0, 3.0, 500.0))
var me: SimEntity = sim.entities.find(brain.player_id)
sim.start_tide()
_ready_world()
var first_level: float = sim.tide.levels[0]
assert_false(world.is_safe(me.position, 0))
var rise_ends: int = roundi((float(Tuning.TIDE_PHASES[0]["hold"]) + float(Tuning.TIDE_PHASES[0]["rise"])) * TICKS)
var wet_ticks: Array[int] = [0]
_run(rise_ends + TICKS, func() -> bool:
if me.swimming or sim.sea_level > me.position.y + Tuning.WADE_DEPTH:
wet_ticks[0] += 1
return false)
assert_eq(wet_ticks[0], 0, "the water never caught it")
assert_near(sim.sea_level, first_level, 0.01)
assert_true(me.position.y > first_level + Tuning.BOT_SAFE_MARGIN_METRES, "standing at %.1f m, above the %.1f m tide" % [me.position.y, first_level])
assert_true(world.is_safe(me.position, 0))
assert_eq(me.health, Tuning.PLAYER_MAX_HEALTH)
func test_sight_lines_stop_at_terrain_and_solids() -> void:
_setup(7, _slope())
_ready_world()
var ground: SimGround = sim.ground
# Along the slope, eye height above it: clear. Through the hillside: not.
assert_true(world.clear_line(ground, Vector3(100.0, 6.6, 500.0), Vector3(160.0, 9.6, 500.0)))
assert_false(world.clear_line(ground, Vector3(100.0, 6.6, 500.0), Vector3(200.0, 6.6, 500.0)))
ground.add_solid(AABB(Vector3(129.0, 0.0, 490.0), Vector3(1.0, 30.0, 20.0)))
assert_false(world.clear_line(ground, Vector3(100.0, 6.6, 500.0), Vector3(160.0, 9.6, 500.0)))
func test_safe_ground_is_above_each_phase_with_room_to_spare() -> void:
_setup(7, _slope())
sim.start_tide()
_ready_world()
var rng: RandomNumberGenerator = RandomNumberGenerator.new()
rng.seed = 5
for phase: int in world.phase_count():
var from: Vector3 = Vector3(20.0, 1.0, 300.0)
var near: Vector3 = world.nearest_safe(from, phase)
var anywhere: Vector3 = world.random_safe(rng, phase)
if world.phase_cells[phase] == 0:
# The last phase covers everything: the goal is the top of the last dry ground.
assert_eq(near, world.phase_tops[phase])
assert_near(near.x, Tuning.WORLD_SIZE_METRES, 0.01)
continue
for point: Vector3 in [near, anywhere]:
assert_true(point.y > world.levels[phase] + Tuning.BOT_SAFE_MARGIN_METRES, "phase %d: %s is above %.1f" % [phase, point, world.levels[phase]])
assert_true(world.is_safe(point, phase))
# On a plain slope the nearest safe ground is straight uphill.
assert_near(near.z, from.z, SafeGround.STRIDE_METRES)
assert_eq(world.phase_cells[world.phase_count() - 1], 0)
func test_a_bot_only_match_ends_with_a_winner_and_replays_exactly() -> void:
var result: Dictionary = BotBatch.run_match(20261112, 10)
print(" 10 bots, seed %d: %d ticks, causes %s, %d shots, p99 %d us" % [result["seed"], result["ticks"], result["causes"], result["shots"], result["timing"]["p99_us"]])
assert_true(result["finished"], "the match reached its results")
assert_ne(result["winner"], 0, "somebody won")
assert_true(result["shots"] > 0, "bots found weapons and used them")
var again: Dictionary = BotBatch.run_match(20261112, 10)
assert_eq(again["state_hash"], result["state_hash"], "the same seed plays the same match")
assert_eq(again["ticks"], result["ticks"])