diff --git a/CLAUDE.md b/CLAUDE.md index c1bed02..bb35429 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,6 +25,7 @@ continuity. | `tools/godot.sh ...` | Runs the pinned engine. Headless by default. | | `tools/capture.sh ` | Renders the real client offscreen in a throwaway `tidewall-capture-*` Docker container (Xvfb, Mesa software rendering) and saves a PNG. Fails on a blank frame or a renderer fallback. | | `tools/godot.sh --script res://tools/island_map.gd -- --seed=N --out=res://captures/island.png` | Draws a top-down map of a seed's island, with a contour at each tide level. | +| `make bot-matches` | Plays 20 bot-only matches (several minutes, under `nice`) and checks every one has a winner, under a tenth of deaths are drownings, easy bots place worst and hard bots take the most eliminations. `BOT_MATCH_SEEDS=5 BOT_MATCH_FIRST=40` changes the seeds. | | `make terrain-capture` | Renders the terrain crack check and a skirtless control in the capture container. The control must crack and the real terrain must not. Needs Docker. | | `make capture-test` | Proves the capture harness works and rejects a blank frame. Needs Docker, so it isn't part of `make check`. | diff --git a/Makefile b/Makefile index 901567a..a53393e 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ # Tidewall build entry points. Everything runs headless with the repo-local engine. GODOT := tools/godot.sh -.PHONY: check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine +.PHONY: check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine bot-matches ## Everything that must pass before a push. check: verify-engine binaries parse test test-selfcheck smoke @@ -30,6 +30,12 @@ test-selfcheck: import smoke: import @tools/smoke.sh +## Plays 20 bot-only matches and checks each has a winner, few bots drown and +## difficulty shows. Takes several minutes, so it isn't part of `check`. +## BOT_MATCH_SEEDS and BOT_MATCH_FIRST change how many seeds and where they start. +bot-matches: import + @tools/bot_matches.sh + ## Renders the capture test scenes in the offscreen container. Needs Docker. capture-test: import @tools/capture_selfcheck.sh diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8f14231..c6ab2b5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -139,8 +139,30 @@ per server tick across all bots; others wait their turn. `NavBot` follows a path: it steers at the next waypoint, sprints on long dry stretches, jumps when it stops making progress, and after a few tries marks the point blocked and -plans around it. The brains in M5 choose its goals; until then the server's bots roam -between random reachable places. +plans around it. A goal the grid's regions show to be cut off (inside a ring of rock, +behind a hut's walls) is turned down without a search, which would otherwise cover the +whole island before giving up. + +`BotBrain` decides where a bot goes and what it presses, and gives `NavBot` its goals. +It knows what a player would: the map (`BotWorld`: loot markers at the points of +interest and the ground each tide level will leave dry), the tide forecast, items +within a few metres, opponents in view with a clear line to them, and who just hit it. +Each tick, in order of urgency, it gets to ground the coming tide won't reach, fights a +visible opponent if it is armed, bandages itself when nobody is in view, picks up +useful items and opens chests, walks to the next loot marker, and otherwise wanders the +safe ground. Difficulty (`Tuning.BOT_DIFFICULTIES`) sets its reaction time, how far it +sees and how far its aim wanders. + +Two things the brain handles itself, because the grid is flat terrain only: +- Huts, lofts and piers. Their doors and steps are finer than the grid, so a bot walks + to the foot of the point of interest's own walking route and follows its points in, + then back out the same way, before anything else, even if it must flee. +- Safe ground. For each tide phase it is the dry land joined to the island's highest + walkable ground, so it only shrinks, each phase's inside the last. A bot off it + leaves when the time before the next rise only just covers the walk. + +`tools/bot_matches.gd` (`make bot-matches`) plays whole bot-only matches on a run of +seeds and reports winners, causes of death and how each difficulty placed. ## Terrain diff --git a/docs/GDD.md b/docs/GDD.md index fc7f12f..d66e0e2 100644 --- a/docs/GDD.md +++ b/docs/GDD.md @@ -57,8 +57,12 @@ during a match waits in the lobby for the next one. Every timer can be changed p server through `MatchRules`. Match 0 uses the server's seed; later matches derive theirs from it, so a whole session can be replayed from one seed. -Bots fill empty slots. Offline play is a local server filled with bots, the same game -code as online play. A downed duo partner can be revived, within `REVIVE_SECONDS`. +Bots fill empty slots. They pick a landing spot, loot, fight, bandage themselves and keep +ahead of the tide, knowing only what a player would. They come in three difficulties, +easy, normal and hard, which differ in reaction time, sight range and aim; a server +mixes them unless told otherwise. Bots don't build yet, don't break crates, and don't +use powder kegs or the line thrower. Offline play is a local server filled with bots, +the same game code as online play. A downed duo partner can be revived, within `REVIVE_SECONDS`. ## The island diff --git a/src/bots/bot_brain.gd b/src/bots/bot_brain.gd new file mode 100644 index 0000000..39ad6d2 --- /dev/null +++ b/src/bots/bot_brain.gd @@ -0,0 +1,765 @@ +## A bot that plays a match: it picks a landing spot, loots points of interest, fights +## who it sees, patches itself up and keeps ahead of the tide. It decides where to go +## and what to press; NavBot does the walking. Like a player, it only sends +## PlayerCommands. +## +## What it knows is what a player would: the map (BotWorld's loot markers and safe +## ground), the tide forecast, items lying close by, opponents in view with a clear line +## to them, and who just hit it. Difficulty (Tuning.BOT_DIFFICULTIES) sets how quickly +## it reacts, how far it sees and how steady its aim is. +## +## Each tick, in order of urgency: get to ground the coming tide will leave dry; fight +## a visible opponent if armed; use a bandage or armor when nobody is in view; pick up +## useful items and open chests; walk to the next loot marker; otherwise wander the safe +## ground, which is where everyone ends up. +class_name BotBrain +extends RefCounted + +const EASY: int = 0 +const NORMAL: int = 1 +const HARD: int = 2 +const TICKS: int = Tuning.TICK_RATE_HZ +## Where a bot is on the way into a hut, loft or pier along its walking route. +const OUTSIDE: int = 0 +const ENTERING: int = 1 +const INSIDE: int = 2 +const LEAVING: int = 3 + +var player_id: int = 0 +var difficulty: int = NORMAL +var nav: NavBot +## What the bot is doing, for logs and tests: "drop", "flee", "fight", "chase", "heal", +## "loot", "hunt" or "idle". +var state: String = "idle" +## The opponent the bot is fighting or looking for, or 0. +var target_id: int = 0 +var target_visible: bool = false + +var _reaction_ticks: int = 0 +var _aim_error_degrees: float = 0.0 +var _sight: float = 0.0 +var _lead: float = 0.0 + +var _acquired_tick: int = 0 +var _last_seen_tick: int = -100000 +var _last_seen: Vector3 = Vector3.ZERO +var _aim_error: Vector2 = Vector2.ZERO +var _aim_error_goal: Vector2 = Vector2.ZERO +var _strafe: float = 1.0 +var _strafe_until: int = 0 +var _weapon_slot: int = -1 +var _weapon_checked: int = -100000 + +var _fleeing: bool = false +var _flee_goal: Vector3 = Vector3.ZERO +var _tide_checked: int = -100000 + +var _landing: int = -1 +var _marker: int = -1 +var _marker_since: int = 0 +var _visited: Dictionary = {} +var _pickup_id: int = 0 +var _pickup_since: int = 0 +var _skipped_pickups: Dictionary = {} +var _skipped_chests: Dictionary = {} +var _loot_checked: int = -100000 +var _interact_last: bool = false +var _hunt_goal: Vector3 = Vector3.ZERO +var _hunt_until: int = 0 +var _goal_set: bool = false +## Walking a point of interest's route: the stage, the route, the next point on it and +## when the stage began. +var _stage: int = OUTSIDE +var _route: Array = [] +var _route_index: int = 0 +var _stage_since: int = 0 +## Walking straight at a point, without the path follower: the point, whether it's in +## use this tick, and how long the bot has gone without getting closer. +var _direct: Vector3 = Vector3.ZERO +var _direct_goal: Vector3 = Vector3.ZERO +var _direct_on: bool = false +var _leave_tries: int = 0 +var _direct_best: float = INF +var _direct_stalled: int = 0 + + +func _init(id: int, level: int = NORMAL) -> void: + player_id = id + difficulty = clampi(level, 0, Tuning.BOT_DIFFICULTIES.size() - 1) + nav = NavBot.new(id) + var stats: Dictionary = Tuning.BOT_DIFFICULTIES[difficulty] + _reaction_ticks = roundi(float(stats["reaction"]) * TICKS) + _aim_error_degrees = float(stats["aim_error"]) + _sight = float(stats["sight"]) + _lead = float(stats["lead"]) + + +func difficulty_name() -> String: + return Tuning.BOT_DIFFICULTIES[difficulty]["name"] + + +## Returns this bot's command for `sim.tick`. The grid must be synced and the world +## must have observed this tick. +func think(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand: + var me: SimEntity = sim.entities.find(player_id) + if me == null or me.eliminated: + return PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0) + if me.drop_state != Drop.NONE: + return _drop(sim, grid, world) + _sense(sim, world, me) + _check_tide(sim, world, me) + _update_aim_error(sim) + var target: SimEntity = sim.entities.find(target_id) if target_id != 0 else null + var distance: float = me.position.distance_to(target.position) if target != null else 30.0 + _choose_weapon(sim, me, distance) + var armed: bool = _weapon_slot >= 0 + var selection: int = _weapon_slot + 1 if armed else Simulation.BOATHOOK_SLOT + var buttons: int = 0 + var fighting: bool = target != null and target_visible and armed and not me.swimming + var interact: bool = false + var walk: bool = true + + # Where to go. + _direct_on = false + var urgent: bool = _fleeing or (target != null and armed) + if _stage != OUTSIDE: + # Inside a hut or up a loft: loot, or walk back out first if something's up. + if urgent and _stage != LEAVING: + _set_stage(sim, LEAVING, maxi(_route_index - 1, 0) if _stage == ENTERING else _route.size() - 2) + state = "flee" if _fleeing else "loot" + interact = _walk_route(sim, me) + elif _fleeing: + state = "flee" + _go(_flee_goal, 3.0) + elif fighting: + state = "fight" + _stop() + elif target != null and armed: + state = "chase" + _go(_last_seen, 3.0) + if nav.status == NavBot.ARRIVED or nav.status == NavBot.UNREACHABLE: + _forget_target() + else: + var heal_slot: int = _heal_slot(me) + if heal_slot >= 0: + state = "heal" + selection = heal_slot + 1 + buttons |= PlayerCommand.BUTTON_FIRE + walk = _goal_set + else: + interact = _loot(sim, grid, world, me) + if state != "loot": + _hunt(sim, world) + + # Walking, from the path follower. + var direction: Vector2 = Vector2.ZERO + var yaw: float = float(me.yaw) / PlayerCommand.YAW_STEPS * TAU + var pitch: float = 0.0 + if _direct_on: + var to: Vector2 = Vector2(_direct.x - me.position.x, _direct.z - me.position.z) + if to.length() > 0.05: + direction = to.normalized() + yaw = atan2(to.x, to.y) + if _direct_stalled > 0 and _direct_stalled % 15 == 0: + buttons |= PlayerCommand.BUTTON_JUMP + elif _goal_set and walk: + var step: PlayerCommand = nav.think(sim, grid) + if nav.status == NavBot.UNREACHABLE and _fleeing: + # No route the grid knows: head straight for it and swim if need be. + var to: Vector2 = Vector2(_flee_goal.x - me.position.x, _flee_goal.z - me.position.z) + direction = to.normalized() + yaw = atan2(to.x, to.y) + buttons |= PlayerCommand.BUTTON_SPRINT + elif step.move_y != 0: + yaw = step.yaw_radians() + direction = Vector2(sin(yaw), cos(yaw)) + buttons |= step.buttons & (PlayerCommand.BUTTON_SPRINT | PlayerCommand.BUTTON_JUMP) + if state == "heal": + buttons &= ~PlayerCommand.BUTTON_SPRINT + + # Fighting: face the target and fire, whatever the feet are doing. + if target != null and target_visible and armed and not me.swimming: + var def: ItemDef = ItemCatalog.get_def(me.slot_items[_weapon_slot]) + var aim: Vector2 = _aim_at(me, target, def) + yaw = aim.x + pitch = aim.y + if not _fleeing and _stage == OUTSIDE: + direction = _combat_move(sim, grid, me, target, def) + buttons &= ~PlayerCommand.BUTTON_SPRINT + var in_range: bool = distance <= _fire_range(def) + if in_range and sim.tick - _acquired_tick >= _reaction_ticks and me.bloom < Tuning.BOT_BLOOM_PAUSE_DEGREES: + buttons |= PlayerCommand.BUTTON_FIRE + if distance > 10.0: + buttons |= PlayerCommand.BUTTON_AIM + elif armed and state != "heal" and me.reload_ticks == 0: + # Nobody in view: top up the magazine. + var def: ItemDef = ItemCatalog.get_def(me.slot_items[_weapon_slot]) + if me.slot_rounds[_weapon_slot] < def.magazine and me.ammo[Inventory.ammo_index(def.ammo_code)] > 0: + buttons |= PlayerCommand.BUTTON_RELOAD + + if interact and not _interact_last: + buttons |= PlayerCommand.BUTTON_INTERACT + _interact_last = true + else: + _interact_last = false + var forward: Vector2 = Vector2(sin(yaw), cos(yaw)) + var right: Vector2 = Vector2(-cos(yaw), sin(yaw)) + var move: Vector2 = Vector2(direction.dot(right), direction.dot(forward)) + return PlayerCommand.from_input(sim.tick, move, yaw, pitch, buttons, selection) + + +# Movement goals + +func _go(goal: Vector3, radius: float) -> void: + if not _goal_set or nav.goal.distance_to(goal) > 1.0: + nav.arrive_radius = radius + nav.set_goal(goal) + _goal_set = true + + +func _stop() -> void: + if _goal_set: + nav.clear_goal() + _goal_set = false + + +# The drop + +## Rides the barge to within reach of a loot marker near its route, then glides to it. +func _drop(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand: + state = "drop" + if _landing < 0 and not world.markers.is_empty() and sim.drop != null: + var rng: RandomNumberGenerator = sim.rng.stream("bots") + var a: Vector2 = Vector2(sim.drop.start.x, sim.drop.start.z) + var b: Vector2 = Vector2(sim.drop.finish.x, sim.drop.finish.z) + var near: Array[int] = [] + for index: int in world.markers.size(): + var at: Vector2 = Vector2(world.markers[index].x, world.markers[index].z) + var closest: Vector2 = Geometry2D.get_closest_point_to_segment(at, a, b) + if at.distance_to(closest) <= 120.0 and world.markers[index].y > sim.sea_level + 1.0: + near.append(index) + _landing = near[rng.randi_range(0, near.size() - 1)] if not near.is_empty() else rng.randi_range(0, world.markers.size() - 1) + _marker = _landing + _marker_since = sim.tick + _go(world.markers[_landing], 2.0) + return nav.think(sim, grid) + + +# Senses + +func _sense(sim: Simulation, world: BotWorld, me: SimEntity) -> void: + var tick: int = sim.tick + var target: SimEntity = sim.entities.find(target_id) if target_id != 0 else null + if target != null and (target.eliminated or target.archetype != SimEntity.ARCHETYPE_PLAYER): + target = null + if target == null and target_id != 0: + _forget_target() + # Being hit tells a player roughly where it came from. + var attacker_id: int = int(world.attackers.get(player_id, 0)) + if attacker_id != 0 and attacker_id != player_id and not target_visible: + var attacker: SimEntity = sim.entities.find(attacker_id) + if attacker != null and not attacker.eliminated: + if target_id != attacker_id: + _acquired_tick = tick + target_id = attacker_id + target = attacker + _last_seen = attacker.position + _last_seen_tick = tick + if (tick + player_id) % Tuning.BOT_SENSE_TICKS != 0: + return + if target != null: + var seen: bool = _can_see(sim, world, me, target, true) + if seen and not target_visible and tick - _last_seen_tick > TICKS: + _acquired_tick = tick + target_visible = seen + if seen: + _last_seen = target.position + _last_seen_tick = tick + elif tick - _last_seen_tick > roundi(Tuning.BOT_MEMORY_SECONDS * TICKS): + _forget_target() + target = null + if target != null and target_visible: + return + # Look for someone new, nearest first, with a few sight lines at most. + var candidates: Array[Vector2] = [] + for other_id: int in world.player_ids: + if other_id == player_id or other_id == target_id: + continue + var other: SimEntity = sim.entities.find(other_id) + if other == null or other.eliminated or other.drop_state != Drop.NONE: + continue + var gap: float = me.position.distance_squared_to(other.position) + if gap <= _sight * _sight: + candidates.append(Vector2(gap, other_id)) + candidates.sort() + for index: int in mini(candidates.size(), 3): + var other: SimEntity = sim.entities.find(int(candidates[index].y)) + if _can_see(sim, world, me, other, false): + target_id = other.id + target_visible = true + _acquired_tick = tick + _last_seen = other.position + _last_seen_tick = tick + return + + +## True if `other` is within sight range, in view (or close enough to hear, or already +## being watched) and nothing solid is in the way. +func _can_see(sim: Simulation, world: BotWorld, me: SimEntity, other: SimEntity, watching: bool) -> bool: + if other.eliminated or other.drop_state != Drop.NONE: + return false + var to: Vector3 = other.position - me.position + var gap: float = to.length() + if gap > _sight: + return false + if not watching and gap > Tuning.BOT_HEARING_METRES: + var facing: float = float(me.yaw) / PlayerCommand.YAW_STEPS * TAU + var flat: Vector2 = Vector2(to.x, to.z).normalized() + if flat.dot(Vector2(sin(facing), cos(facing))) < cos(deg_to_rad(Tuning.BOT_VIEW_HALF_ANGLE_DEGREES)): + return false + var chest: Vector3 = other.position + Vector3(0.0, Movement.body_height(other) * 0.62, 0.0) + return world.clear_line(sim.ground, Harvest.eye(me), chest) + + +func _forget_target() -> void: + target_id = 0 + target_visible = false + + +# Fighting + +## The slot of the best weapon for a target `distance` away, kept for a second at a time +## so the bot doesn't keep swapping. +func _choose_weapon(sim: Simulation, me: SimEntity, distance: float) -> void: + var usable: bool = _weapon_slot >= 0 and _weapon_score(me, _weapon_slot, distance) > 0.0 + if usable and sim.tick - _weapon_checked < TICKS: + return + _weapon_checked = sim.tick + var best: int = -1 + var best_score: float = 0.0 + for slot: int in Inventory.slot_count(): + var score: float = _weapon_score(me, slot, distance) + # Stay with the held weapon unless another is clearly better. + if slot == _weapon_slot: + score *= 1.25 + if score > best_score: + best = slot + best_score = score + _weapon_slot = best + + +## How good the weapon in `slot` is at `distance`: 0 if it can't be fired. +static func _weapon_score(me: SimEntity, slot: int, distance: float) -> float: + var def: ItemDef = ItemCatalog.get_def(me.slot_items[slot]) + if def == null or not def.is_weapon() or def.thrown or def.damage <= 0: + return 0.0 + if me.slot_rounds[slot] <= 0 and (def.ammo_code < 0 or me.ammo[Inventory.ammo_index(def.ammo_code)] <= 0): + return 0.0 + var score: float = def.damage_at(distance) * def.pellets * def.fire_rate + if distance > def.range_max: + score *= 0.05 + # A wide cone wastes most of its shot at range. + var cone: float = distance * tan(deg_to_rad(def.spread_degrees * def.aim_spread_factor + 0.5)) + return score * clampf(0.5 / maxf(cone, 0.01), 0.1, 1.0) + + +func _update_aim_error(sim: Simulation) -> void: + if (sim.tick + player_id) % Tuning.BOT_AIM_WANDER_TICKS == 0: + var rng: RandomNumberGenerator = sim.rng.stream("bots") + _aim_error_goal = Vector2(rng.randf_range(-1.0, 1.0), rng.randf_range(-0.5, 0.5)) * _aim_error_degrees + _aim_error = _aim_error.lerp(_aim_error_goal, 0.25) + + +## Yaw and pitch, in radians, to hit `target` with `def`, off by the bot's aim error. +func _aim_at(me: SimEntity, target: SimEntity, def: ItemDef) -> Vector2: + var eye: Vector3 = Harvest.eye(me) + var point: Vector3 = target.position + Vector3(0.0, Movement.body_height(target) * 0.62, 0.0) + if def.projectile_speed > 0.0: + var flight: float = eye.distance_to(point) / def.projectile_speed + point += target.velocity * flight * _lead + point.y += 0.5 * def.projectile_gravity * flight * flight + var to: Vector3 = point - eye + var flat: float = Vector2(to.x, to.z).length() + return Vector2(atan2(to.x, to.z) + deg_to_rad(_aim_error.x), atan2(to.y, flat) + deg_to_rad(_aim_error.y)) + + +## How far off the bot opens fire with `def`: about where the weapon still hits, and +## nearer for a bot whose aim wanders, so it doesn't empty its magazine at the horizon. +func _fire_range(def: ItemDef) -> float: + var reach: float = minf(maxf(def.range_full * 1.5, 12.0), def.range_max) + return reach * clampf(3.0 / _aim_error_degrees, 0.45, 1.0) + + +## Which way to step while fighting: closer when out of the weapon's good range, else +## side to side. Never into deep water or off a cliff. +func _combat_move(sim: Simulation, grid: NavGrid, me: SimEntity, target: SimEntity, def: ItemDef) -> Vector2: + var to: Vector2 = Vector2(target.position.x - me.position.x, target.position.z - me.position.z) + var gap: float = to.length() + if gap < 0.01: + return Vector2.ZERO + to /= gap + var wanted: float = minf(clampf(def.range_full * 0.8, 5.0, 30.0), _fire_range(def) * 0.8) + if sim.tick >= _strafe_until: + var rng: RandomNumberGenerator = sim.rng.stream("bots") + _strafe = -_strafe + _strafe_until = sim.tick + rng.randi_range(TICKS / 2, TICKS * 2) + var side: Vector2 = Vector2(-to.y, to.x) * _strafe + var step: Vector2 = side + if gap > wanted * 1.3: + step = (to + side * 0.4).normalized() + elif gap < wanted * 0.4: + step = (-to + side * 0.6).normalized() + if _can_step(grid, me, step): + return step + if _can_step(grid, me, -side): + _strafe = -_strafe + return -side + return Vector2.ZERO + + +## True if the ground a couple of metres along `step` is open, dry and near level. +static func _can_step(grid: NavGrid, me: SimEntity, step: Vector2) -> bool: + var ahead: Vector3 = me.position + Vector3(step.x, 0.0, step.y) * 2.5 + var point: Vector2i = grid.point_of(ahead) + if not grid.is_open(point) or grid.wet[grid.index_of(point)] != 0: + return false + return absf(grid.heights[grid.index_of(point)] - me.position.y) <= Tuning.BOT_NAV_MAX_RISE + + +# Healing + +## The slot of a consumable worth using now, or -1. Healing comes before armor. +static func _heal_slot(me: SimEntity) -> int: + if me.swimming: + return -1 + var armor_slot: int = -1 + for slot: int in Inventory.slot_count(): + var def: ItemDef = ItemCatalog.get_def(me.slot_items[slot]) + if def == null or def.kind != ItemDef.CONSUMABLE or not Consumables.would_help(me, def): + continue + if def.heal > 0: + var cap: int = mini(def.heal_cap, Tuning.PLAYER_MAX_HEALTH) + # Not wasteful: most of the heal lands, or the bot is badly hurt. + if me.health + def.heal / 2 <= cap or me.health < 40: + return slot + elif def.armor > 0 and me.armor + def.armor / 2 <= Tuning.PLAYER_MAX_ARMOR: + armor_slot = slot + return armor_slot + + +# The tide + +## Decides whether to leave for safe ground: at once if the water is rising or already +## round the bot's legs, otherwise when the time left only just covers the walk. +func _check_tide(sim: Simulation, world: BotWorld, me: SimEntity) -> void: + if sim.tide == null: + _fleeing = false + return + if sim.tick - _tide_checked < TICKS / 2 and not me.swimming: + return + _tide_checked = sim.tick + var phase: int = sim.tide.phase_at(sim.tick) + if world.is_safe(me.position, phase) and not me.swimming: + _fleeing = false + return + var goal: Vector3 = world.nearest_safe(me.position, phase) + if _fleeing and _goal_set and nav.status == NavBot.ARRIVED: + # At the edge of safe ground but not on it: make for its top instead. + goal = world.phase_tops[phase] + var gap: float = Vector2(goal.x - me.position.x, goal.z - me.position.z).length() + var left: float = float(sim.tide.ticks_until_rise(sim.tick)) / TICKS + var wet: bool = me.swimming or sim.water_level_at(me.position) > me.position.y + 0.2 + if _fleeing or wet or sim.tide.stage_at(sim.tick) != Tide.HOLD or left < gap / Tuning.BOT_FLEE_SPEED + Tuning.BOT_FLEE_BUFFER_SECONDS: + _fleeing = true + _flee_goal = goal + + +## True if a bot may go to `spot` for loot: it's above the water, and either there's +## time before the next rise or the spot is on ground that rise will leave dry. +func _spot_allowed(sim: Simulation, world: BotWorld, spot: Vector3) -> bool: + if spot.y < sim.sea_level + 0.5: + return false + if sim.tide == null: + return true + var phase: int = sim.tide.phase_at(sim.tick) + if world.is_safe(spot, phase): + return true + return sim.tide.stage_at(sim.tick) == Tide.HOLD and float(sim.tide.ticks_until_rise(sim.tick)) / TICKS > Tuning.BOT_LOOT_TIDE_SECONDS + + +# Looting + +## True if the bot has room for the pickup and a use for it. A bot never swaps. +func wants(me: SimEntity, pickup: SimEntity) -> bool: + if pickup == null or pickup.archetype != SimEntity.ARCHETYPE_PICKUP: + return false + var def: ItemDef = ItemCatalog.get_def(pickup.item) + if def == null: + return false + if def.kind == ItemDef.AMMO: + return me.ammo[Inventory.ammo_index(def.code)] < def.cap + var free: int = 0 + var weapons: int = 0 + var others: int = 0 + var stackable: bool = false + var same: bool = false + for slot: int in Inventory.slot_count(): + var held: ItemDef = ItemCatalog.get_def(me.slot_items[slot]) + if held == null: + free += 1 + continue + if held.code == def.code: + same = true + if def.stack > 1 and me.slot_tiers[slot] == pickup.item_tier and me.slot_counts[slot] < def.stack: + stackable = true + if held.is_weapon(): + weapons += 1 + else: + others += 1 + if def.kind == ItemDef.WEAPON: + # Thrown weapons and tools that do no damage are no use to a bot yet. + if def.thrown or def.damage <= 0 or same: + return false + return free > 0 and weapons < Tuning.BOT_MAX_WEAPONS + return stackable or (free > 0 and others < Inventory.slot_count() - Tuning.BOT_MAX_WEAPONS) + + +## Goes after useful items in view, then a chest in reach, then the next loot marker. +## Sets `state` to "loot" when there's something to do. Returns true to press interact. +func _loot(sim: Simulation, grid: NavGrid, world: BotWorld, me: SimEntity) -> bool: + var tick: int = sim.tick + state = "loot" + # An item worth having. + var pickup: SimEntity = sim.entities.find(_pickup_id) if _pickup_id != 0 else null + if pickup != null and (not wants(me, pickup) or tick - _pickup_since > roundi(Tuning.BOT_PICKUP_TIMEOUT_SECONDS * TICKS)): + if wants(me, pickup): + _skipped_pickups[_pickup_id] = true + pickup = null + if pickup == null: + _pickup_id = 0 + if tick - _loot_checked >= TICKS / 2: + _loot_checked = tick + _pickup_id = _find_pickup(sim, world, me) + _pickup_since = tick + pickup = sim.entities.find(_pickup_id) if _pickup_id != 0 else null + if pickup != null: + _go(pickup.position, 0.6) + if me.position.distance_to(pickup.position) <= Tuning.PICKUP_RANGE - 0.3 and Harvest.can_swing(me): + var nearest: int = Inventory.nearest_pickup(sim, me) + if nearest == _pickup_id or wants(me, sim.entities.find(nearest)): + return true + if nav.status != NavBot.MOVING: + _skipped_pickups[_pickup_id] = true + _pickup_id = 0 + elif nav.status == NavBot.UNREACHABLE: + _skipped_pickups[_pickup_id] = true + _pickup_id = 0 + return false + # A chest in reach. + var chest: int = _chest_in_reach(sim, me) + if chest >= 0 and world.in_routed_place(sim.loot.chest_positions[chest]): + chest = -1 + if chest >= 0: + var nearest: int = Inventory.nearest_pickup(sim, me) + var blocked: bool = false + if nearest != 0: + var other: SimEntity = sim.entities.find(nearest) + blocked = other.position.distance_to(me.position) < sim.loot.chest_positions[chest].distance_to(me.position) and not wants(me, other) + if not blocked: + _stop() + return Harvest.can_swing(me) + _go(sim.loot.chest_positions[chest], 0.5) + if nav.status != NavBot.MOVING: + _skipped_chests[chest] = true + return false + # The next marker on the map. + if _marker >= 0 and not world.routes[_marker].is_empty(): + # A marker indoors or out on a pier: walk to the foot of its route, then along it. + var foot: Vector3 = world.routes[_marker][0] + var late: bool = tick - _marker_since > roundi(Tuning.BOT_LOOT_TIMEOUT_SECONDS * TICKS) + var gave_up: bool = _goal_set and nav.status == NavBot.UNREACHABLE and nav.goal.distance_to(foot) < 1.0 + if late or gave_up: + _visited[_marker] = true + _marker = -1 + elif not _spot_allowed(sim, world, world.markers[_marker]): + _marker = -1 + elif Vector2(foot.x - me.position.x, foot.z - me.position.z).length() <= 1.2 and absf(foot.y - me.position.y) < 1.5: + _route = world.routes[_marker] + _stop() + _set_stage(sim, ENTERING, mini(1, _route.size() - 1)) + return false + else: + _go(foot, 0.8) + return false + if _marker >= 0: + var spot: Vector3 = world.markers[_marker] + var near: bool = Vector2(spot.x - me.position.x, spot.z - me.position.z).length() <= 2.5 + var late: bool = tick - _marker_since > roundi(Tuning.BOT_LOOT_TIMEOUT_SECONDS * TICKS) + var gave_up: bool = _goal_set and nav.status != NavBot.MOVING and nav.goal.distance_to(spot) < 1.0 + if near or late or gave_up: + _visited[_marker] = true + _marker = -1 + elif not _spot_allowed(sim, world, spot): + _marker = -1 + if _marker < 0 and tick % (TICKS / 2) == player_id % (TICKS / 2): + _marker = _next_marker(sim, world, me) + _marker_since = tick + if _marker >= 0: + _go(world.markers[_marker], 1.5) + return false + state = "idle" + return false + + +## The nearest closed chest in reach that the bot hasn't given up on, or -1. +func _chest_in_reach(sim: Simulation, me: SimEntity) -> int: + var chest: int = sim.loot.nearest_chest(me.position) + if chest >= 0 and _skipped_chests.has(chest): + return -1 + return chest + + +# Routes into huts, lofts and piers + +func _set_stage(sim: Simulation, stage: int, index: int) -> void: + _stage = stage + _route_index = index + _stage_since = sim.tick + _direct_best = INF + _direct_stalled = 0 + + +## Heads for `point`. Returns true once the bot is within `radius` of it. With `from` +## given, the bot keeps to the line from there to the point, steering at a spot on it +## a metre ahead, so it stays on a stair or in a doorway rather than cutting the corner. +func _walk_to(me: SimEntity, point: Vector3, radius: float, from: Vector3 = Vector3.INF) -> bool: + var gap: float = Vector2(point.x - me.position.x, point.z - me.position.z).length() + var aim: Vector3 = point + if from != Vector3.INF: + var a: Vector2 = Vector2(from.x, from.z) + var b: Vector2 = Vector2(point.x, point.z) + var length: float = a.distance_to(b) + if length > 0.01: + var along: float = (Vector2(me.position.x, me.position.z) - a).dot((b - a) / length) + var ahead: Vector2 = a.lerp(b, clampf((along + 1.0) / length, 0.0, 1.0)) + aim = Vector3(ahead.x, point.y, ahead.y) + if point.distance_to(_direct_goal) > 0.01: + _direct_best = INF + _direct_stalled = 0 + _direct_goal = point + _direct = aim + _direct_on = true + if gap < _direct_best - 0.05: + _direct_best = gap + _direct_stalled = 0 + else: + _direct_stalled += 1 + return gap <= radius and absf(point.y - me.position.y) <= 1.2 + + +## One tick on a route: in along its points, loot at the end, and back out the same +## way. Each stage has a time limit, after which the bot turns back or gives up. +## Returns true to press interact. +func _walk_route(sim: Simulation, me: SimEntity) -> bool: + var waited: float = float(sim.tick - _stage_since) / TICKS + match _stage: + ENTERING: + if _walk_to(me, _route[_route_index], 0.5, _route[maxi(_route_index - 1, 0)]): + if _route_index + 1 >= _route.size(): + _set_stage(sim, INSIDE, _route_index) + else: + _route_index += 1 + _stage_since = sim.tick + elif waited > 8.0: + _set_stage(sim, LEAVING, maxi(_route_index - 1, 0)) + INSIDE: + if waited > 15.0 or not Harvest.can_swing(me): + _set_stage(sim, LEAVING, _route.size() - 2) + return false + var nearest: SimEntity = sim.entities.find(Inventory.nearest_pickup(sim, me)) + var chest: int = sim.loot.nearest_chest(me.position) + if chest >= 0: + var nearer: bool = nearest != null and nearest.position.distance_to(me.position) < sim.loot.chest_positions[chest].distance_to(me.position) + if not nearer or wants(me, nearest): + return true + if nearest != null and wants(me, nearest): + return true + # Something useful further in: step over to it. + var end: Vector3 = _route[_route.size() - 1] + for pickup_id: int in sim.pickups: + var pickup: SimEntity = sim.entities.find(pickup_id) + if pickup.position.distance_to(end) < 3.5 and wants(me, pickup) and not _skipped_pickups.has(pickup_id): + if _walk_to(me, pickup.position, 0.4) or _direct_stalled > TICKS: + _skipped_pickups[pickup_id] = true + return false + _set_stage(sim, LEAVING, _route.size() - 2) + LEAVING: + if waited > 8.0 and _route_index >= 0 and _leave_tries < 4: + # Caught on something: start again from the nearest point of the route. + _leave_tries += 1 + var nearest_index: int = 0 + for index: int in _route.size(): + if me.position.distance_to(_route[index]) < me.position.distance_to(_route[nearest_index]): + nearest_index = index + _set_stage(sim, LEAVING, nearest_index) + elif _route_index < 0 or waited > 8.0: + if _marker >= 0: + _visited[_marker] = true + _marker = -1 + _stage = OUTSIDE + _leave_tries = 0 + _goal_set = false + elif _walk_to(me, _route[_route_index], 0.5, _route[mini(_route_index + 1, _route.size() - 1)]): + _route_index -= 1 + _stage_since = sim.tick + return false + + +## The nearest wanted item in view, or 0. +func _find_pickup(sim: Simulation, world: BotWorld, me: SimEntity) -> int: + var best: int = 0 + var best_distance: float = Tuning.BOT_LOOT_SIGHT_METRES * Tuning.BOT_LOOT_SIGHT_METRES + for pickup_id: int in sim.pickups: + var pickup: SimEntity = sim.entities.find(pickup_id) + var gap: float = pickup.position.distance_squared_to(me.position) + if gap >= best_distance or _skipped_pickups.has(pickup_id): + continue + if absf(pickup.position.y - me.position.y) > 3.0 or not wants(me, pickup): + continue + if world.in_routed_place(pickup.position): + continue + if not _spot_allowed(sim, world, pickup.position): + continue + best = pickup_id + best_distance = gap + return best + + +## The nearest marker the bot hasn't been to and may go to. Armed bots don't trek +## across the island for more. +func _next_marker(sim: Simulation, world: BotWorld, me: SimEntity) -> int: + var reach: float = 150.0 if _weapon_slot >= 0 else 400.0 + var best: int = -1 + var best_distance: float = reach * reach + for index: int in world.markers.size(): + if _visited.has(index): + continue + var spot: Vector3 = world.markers[index] + var gap: float = Vector2(spot.x - me.position.x, spot.z - me.position.z).length_squared() + if gap < best_distance and _spot_allowed(sim, world, spot): + best = index + best_distance = gap + return best + + +## Nothing to loot: wander the ground the tide will leave, where the others will be. +func _hunt(sim: Simulation, world: BotWorld) -> void: + state = "hunt" + var arrived: bool = _goal_set and nav.status != NavBot.MOVING + if not _goal_set or arrived or sim.tick >= _hunt_until: + var phase: int = sim.tide.phase_at(sim.tick) if sim.tide != null else 0 + _hunt_goal = world.random_safe(sim.rng.stream("bots"), phase) + _hunt_until = sim.tick + 40 * TICKS + _go(_hunt_goal, 4.0) + else: + _go(_hunt_goal, 4.0) diff --git a/src/bots/bot_brain.gd.uid b/src/bots/bot_brain.gd.uid new file mode 100644 index 0000000..49efe00 --- /dev/null +++ b/src/bots/bot_brain.gd.uid @@ -0,0 +1 @@ +uid://jmh12jrvvnce diff --git a/src/bots/bot_world.gd b/src/bots/bot_world.gd new file mode 100644 index 0000000..376e12b --- /dev/null +++ b/src/bots/bot_world.gd @@ -0,0 +1,251 @@ +## What every bot in a match knows without looking: the map. Where the points of +## interest keep their loot, which ground each tide level will leave dry, and who is in +## the match. It also answers the questions bots share: is there a clear line between two +## points, and where is the nearest ground the coming tide won't reach. +## +## Safe ground for a phase is the land standing Tuning.BOT_SAFE_MARGIN_METRES above that +## phase's level that is joined, on SafeGround's 8 m grid, to the island's highest +## ground, where every match ends. So safe ground only shrinks, each phase's inside the +## last, and a hill that will be cut off doesn't count: bots leave it while they can +## still walk. For the last phase, which covers everything, the goal is the top itself. +## +## Built once per match, while the lobby waits. It only reads the simulation. +class_name BotWorld +extends RefCounted + +const CELL: float = SafeGround.STRIDE_METRES +## Sight lines are checked against the terrain every this many metres. +const SIGHT_STEP_METRES: float = 2.0 +const SIGHT_SEGMENT_METRES: float = 16.0 +## With no safe ground left, within this distance of the last high point counts as there. +const LAST_STAND_RADIUS: float = 10.0 + +## Entity IDs of everyone in the match. +var player_ids: Array[int] = [] +## Loot markers at the points of interest: on every player's map. +var markers: Array[Vector3] = [] +## For each marker, the way in: the points of interest's own walking route from open +## ground to the marker (an Array of Vector3), or an empty Array for a marker that +## stands in the open. Huts, lofts and piers are only reached this way; the navigation +## grid stops at their doors and steps. +var routes: Array[Array] = [] +## A marker counts as on a route if it's within this distance of one of its points. +const ROUTE_REACH: float = 4.5 +var heights: SafeGround +## The tide's level for each phase. +var levels: PackedFloat32Array = PackedFloat32Array() +## Per phase: a mark per grid cell of the safe ground, how many cells it has, and the +## island's highest walkable point. +var phase_marks: Array[PackedByteArray] = [] +var phase_cells: PackedInt32Array = PackedInt32Array() +var phase_tops: Array[Vector3] = [] +## 1 for each grid cell a bot can walk to: open on the navigation grid and joined to the +## rest of the island. Safe ground a bot is sent to is always one of these. +var walkable: PackedByteArray = PackedByteArray() +## Victim entity ID -> attacker entity ID, for hits landed during the last tick. +var attackers: Dictionary = {} + + +## `grid` is the match's navigation grid. Loot markers and safe ground that nothing can +## walk to (inside a ring of rock, say) are left off the bots' map. +static func build(sim: Simulation, grid: NavGrid) -> BotWorld: + var world: BotWorld = BotWorld.new() + world.heights = SafeGround.new(sim.ground) + var side: int = world.heights.side + world.walkable.resize(side * side) + for cell: int in side * side: + var at: Vector3 = Vector3((cell % side) * CELL, 0.0, (cell / side) * CELL) + var point: Vector2i = grid.nearest_open(grid.point_of(at), 1) + world.walkable[cell] = 1 if point.x >= 0 and grid.regions[grid.index_of(point)] == grid.main_region else 0 + if sim.tide != null: + world.levels = sim.tide.levels.duplicate() + elif sim.island != null: + world.levels = world.heights.plan_levels() + else: + for phase: Dictionary in Tuning.TIDE_PHASES: + world.levels.append(float(phase["level"])) + for marker: Dictionary in sim.pois.loot_markers(): + var spot: Vector3 = marker["position"] + var route: Array = _route_to(sim.pois.pois[marker["poi"]], spot) + if route.is_empty() and not (grid.is_open(grid.point_of(spot)) and grid.region_at(spot) == grid.main_region): + continue + if not route.is_empty() and grid.region_at(route[0]) != grid.main_region: + continue + world.markers.append(spot) + world.routes.append(route) + # The island's highest walkable ground is where every match ends. Each phase's safe + # ground is the piece joined to it, so safe ground only ever shrinks towards it. + var anchor: int = world._highest(world.walkable) + if world.walkable[anchor] == 0: + var everything: PackedByteArray = PackedByteArray() + everything.resize(side * side) + everything.fill(1) + anchor = world._highest(everything) + for level: float in world.levels: + var marks: PackedByteArray = world._piece_from(anchor, level + Tuning.BOT_SAFE_MARGIN_METRES) + world.phase_marks.append(marks) + world.phase_cells.append(marks.count(1)) + world.phase_tops.append(world._cell_position(anchor)) + return world + + +## The part of one of `poi`'s walking routes that leads to `spot`, ending at the spot +## itself, or an empty Array if no route passes within ROUTE_REACH of it. +static func _route_to(poi: Poi, spot: Vector3) -> Array: + var best: Array = [] + var best_distance: float = ROUTE_REACH + for route: Array in poi.routes: + for index: int in route.size(): + var point: Vector3 = route[index] + var distance: float = point.distance_to(spot) + if distance < best_distance: + best_distance = distance + best = route.slice(0, index + 1) + if distance > 0.3: + best.append(spot) + return best + + +## True if `position` is inside a place only a route reaches: within a few metres of a +## marker that has one. Bots leave items there alone unless they have walked in. +func in_routed_place(position: Vector3) -> bool: + for index: int in markers.size(): + if routes[index].is_empty(): + continue + var spot: Vector3 = markers[index] + if absf(spot.y - position.y) < 3.0 and Vector2(spot.x - position.x, spot.z - position.z).length() < 4.0: + return true + return false + + +## Notes who hit whom during the last tick. Call once per tick, before bots think. +func observe(sim: Simulation) -> void: + attackers.clear() + for event: Dictionary in sim.events: + if event["type"] == "player_hit" and int(event["player"]) != 0: + attackers[int(event["victim"])] = int(event["player"]) + + +func phase_count() -> int: + return levels.size() + + +## True if `position` is on the ground the tide's phase `phase` will leave dry. +func is_safe(position: Vector3, phase: int) -> bool: + phase = clampi(phase, 0, phase_count() - 1) + if phase_cells[phase] == 0: + var top: Vector3 = phase_tops[phase] + return Vector2(position.x - top.x, position.z - top.z).length() <= LAST_STAND_RADIUS + return phase_marks[phase][_cell_of(position)] != 0 + + +## The nearest point of phase `phase`'s safe ground, or the last high point when the +## phase leaves none. +func nearest_safe(position: Vector3, phase: int) -> Vector3: + phase = clampi(phase, 0, phase_count() - 1) + if phase_cells[phase] == 0: + return phase_tops[phase] + var marks: PackedByteArray = phase_marks[phase] + var side: int = heights.side + var cx: int = clampi(roundi(position.x / CELL), 0, side - 1) + var cz: int = clampi(roundi(position.z / CELL), 0, side - 1) + for ring: int in side: + var best: int = -1 + var best_distance: float = INF + for dz: int in range(-ring, ring + 1): + var z: int = cz + dz + if z < 0 or z >= side: + continue + var stride: int = 1 if absi(dz) == ring else maxi(ring * 2, 1) + for dx: int in range(-ring, ring + 1, stride): + var x: int = cx + dx + if x < 0 or x >= side or marks[z * side + x] == 0: + continue + var distance: float = Vector2(x * CELL - position.x, z * CELL - position.z).length_squared() + if distance < best_distance: + best = z * side + x + best_distance = distance + if best >= 0: + return _cell_position(best) + return phase_tops[phase] + + +## A random point of phase `phase`'s safe ground, for bots with nowhere better to be. +func random_safe(rng: RandomNumberGenerator, phase: int) -> Vector3: + phase = clampi(phase, 0, phase_count() - 1) + if phase_cells[phase] == 0: + return phase_tops[phase] + var marks: PackedByteArray = phase_marks[phase] + for _try: int in 24: + var cell: int = rng.randi_range(0, marks.size() - 1) + if marks[cell] != 0: + return _cell_position(cell) + return phase_tops[phase] + + +## True if nothing solid stands between two points: terrain, checked every couple of +## metres, and solids. Players don't block it. +func clear_line(ground: SimGround, from: Vector3, to: Vector3) -> bool: + var length: float = from.distance_to(to) + var steps: int = maxi(ceili(length / SIGHT_STEP_METRES), 1) + for index: int in range(1, steps): + var point: Vector3 = from.lerp(to, float(index) / steps) + if point.y < ground.terrain_height(point.x, point.z): + return false + var pieces: int = maxi(ceili(length / SIGHT_SEGMENT_METRES), 1) + for index: int in pieces: + var a: Vector3 = from.lerp(to, float(index) / pieces) + var b: Vector3 = from.lerp(to, float(index + 1) / pieces) + for id: int in ground.solids_near(minf(a.x, b.x), minf(a.z, b.z), maxf(a.x, b.x), maxf(a.z, b.z)): + if ground.ray_box(a, b, ground.solids[id]) < 1.0: + return false + return true + + +func _cell_of(position: Vector3) -> int: + var side: int = heights.side + return clampi(roundi(position.z / CELL), 0, side - 1) * side + clampi(roundi(position.x / CELL), 0, side - 1) + + +func _cell_position(cell: int) -> Vector3: + var side: int = heights.side + return Vector3((cell % side) * CELL, heights.heights[cell], (cell / side) * CELL) + + +## The highest marked cell, or cell 0 if nothing is marked. +func _highest(marks: PackedByteArray) -> int: + var best: int = 0 + var top: float = -INF + for cell: int in marks.size(): + if marks[cell] != 0 and heights.heights[cell] > top: + top = heights.heights[cell] + best = cell + return best + + +## A mark for every walkable cell above `level` that joins `from` through such cells. +## Empty if `from` itself isn't above `level`. +func _piece_from(from: int, level: float) -> PackedByteArray: + var side: int = heights.side + var marks: PackedByteArray = PackedByteArray() + marks.resize(side * side) + if heights.heights[from] <= level: + return marks + marks[from] = 1 + var queue: PackedInt32Array = PackedInt32Array([from]) + var head: int = 0 + while head < queue.size(): + var cell: int = queue[head] + head += 1 + var x: int = cell % side + var z: int = cell / side + for step: Vector2i in SafeGround.STEPS: + var nx: int = x + step.x + var nz: int = z + step.y + if nx < 0 or nz < 0 or nx >= side or nz >= side: + continue + var next: int = nz * side + nx + if marks[next] == 0 and walkable[next] != 0 and heights.heights[next] > level: + marks[next] = 1 + queue.append(next) + return marks diff --git a/src/bots/bot_world.gd.uid b/src/bots/bot_world.gd.uid new file mode 100644 index 0000000..d10aff5 --- /dev/null +++ b/src/bots/bot_world.gd.uid @@ -0,0 +1 @@ +uid://vvulplgfes5l diff --git a/src/bots/nav_grid.gd b/src/bots/nav_grid.gd index 9a1c375..01b5a05 100644 --- a/src/bots/nav_grid.gd +++ b/src/bots/nav_grid.gd @@ -27,6 +27,13 @@ var blocked: PackedInt32Array = PackedInt32Array() var wet: PackedByteArray = PackedByteArray() ## The tick each point last changed, or -1. var changed_tick: PackedInt32Array = PackedInt32Array() +## Which connected region each point was in when the grid was built: 0 for points that +## were solid, and the same number for points a walker or swimmer could get between. +## A goal in another region is turned down without a search, which would otherwise +## cover the whole island before giving up. See find_path(). +var regions: PackedInt32Array = PackedInt32Array() +## The biggest region: the island's open ground and the sea around it. +var main_region: int = 0 ## Paths planned so far this tick, for the per-tick limit. var paths_this_tick: int = 0 var astar: AStarGrid2D = AStarGrid2D.new() @@ -85,6 +92,7 @@ func _build(sim: Simulation) -> void: for index: int in count: if steep[index] != 0 or blocked[index] != 0 or wet[index] != 0: _apply(index, -1) + _label_regions() ## Brings the grid up to date with the simulation: new and removed solids and the @@ -146,9 +154,69 @@ func find_path(from: Vector3, to: Vector3, partial: bool = false) -> Array[Vecto var goal: Vector2i = nearest_open(point_of(to)) if start.x < 0 or goal.x < 0: return [] + var from_region: int = regions[index_of(start)] + var to_region: int = regions[index_of(goal)] + if not partial and from_region != 0 and to_region != 0 and from_region != to_region: + return [] return astar.get_id_path(start, goal, partial) +## The region of the open point nearest a world position, or 0 if there is none or it +## has opened up since the grid was built. +func region_at(position: Vector3) -> int: + var point: Vector2i = nearest_open(point_of(position)) + return regions[index_of(point)] if point.x >= 0 else 0 + + +## Labels every open point with its region, joining points side by side. Regions are +## as the island was when the match began: a wall built later can split one, and the +## search still finds that out the slow way; ground that opens later counts as region 0, +## which is never turned down. +func _label_regions() -> void: + var count: int = side * side + regions.resize(count) + regions.fill(0) + var next: int = 0 + var best_size: int = 0 + var stack: PackedInt32Array = PackedInt32Array() + for start: int in count: + if regions[start] != 0 or blocked[start] > 0 or (steep[start] != 0 and wet[start] == 0): + continue + next += 1 + regions[start] = next + stack.append(start) + var size: int = 0 + while not stack.is_empty(): + var index: int = stack[stack.size() - 1] + stack.remove_at(stack.size() - 1) + size += 1 + var x: int = index % side + for step: int in 4: + var other: int = index + match step: + 0: + if x + 1 >= side: + continue + other = index + 1 + 1: + if x == 0: + continue + other = index - 1 + 2: + other = index + side + 3: + other = index - side + if other < 0 or other >= count or regions[other] != 0: + continue + if blocked[other] > 0 or (steep[other] != 0 and wet[other] == 0): + continue + regions[other] = next + stack.append(other) + if size > best_size: + best_size = size + main_region = next + + ## True if no point of `path` from `from_index` on has changed since `since_tick`. func path_still_valid(path: Array[Vector2i], from_index: int, since_tick: int) -> bool: for at: int in range(from_index, path.size()): diff --git a/src/server/headless_server.gd b/src/server/headless_server.gd index fa04fd3..055ce76 100644 --- a/src/server/headless_server.gd +++ b/src/server/headless_server.gd @@ -39,7 +39,7 @@ func _ready() -> void: if not config.has_seed: config.match_seed = _fresh_seed() Engine.max_fps = 0 if config.unthrottled else REALTIME_MAX_FPS - loop = ServerLoop.new(config.match_seed, config.players, config.bots) + loop = ServerLoop.new(config.match_seed, config.players, config.bots, null, config.bot_difficulty) var started: Dictionary = config.to_dictionary() started["engine"] = Engine.get_version_info()["string"] started["tick_rate_hz"] = Tuning.TICK_RATE_HZ diff --git a/src/server/server_config.gd b/src/server/server_config.gd index b85c5bb..fe813a9 100644 --- a/src/server/server_config.gd +++ b/src/server/server_config.gd @@ -1,7 +1,8 @@ ## Command-line configuration for a headless server. ## ## tools/godot.sh -- --server [--seed=N] [--port=N] [--players=N] [--bots=N] -## [--ticks=N] [--unthrottled] [--log-every=N] +## [--bot-difficulty=mixed|easy|normal|hard] [--ticks=N] +## [--unthrottled] [--log-every=N] ## ## Unknown or malformed arguments are errors, so a typo can't silently run the wrong ## match. See `parse()`. @@ -23,6 +24,8 @@ var port: int = DEFAULT_PORT ## Player slots for human clients. Until v0.5 they join as idle players. var players: int = 0 var bots: int = 0 +## Every bot's difficulty, as an index into Tuning.BOT_DIFFICULTIES, or -1 to mix them. +var bot_difficulty: int = -1 ## Ticks to run before exiting. 0 runs until the process is stopped. var ticks: int = 0 ## Runs ticks back to back instead of at the real tick rate. For tests and smoke runs. @@ -59,6 +62,7 @@ func to_dictionary() -> Dictionary: "port": port, "players": players, "bots": bots, + "bot_difficulty": "mixed" if bot_difficulty < 0 else String(Tuning.BOT_DIFFICULTIES[bot_difficulty]["name"]), "ticks": ticks, "unthrottled": unthrottled, } @@ -94,6 +98,14 @@ func _parse_one(arg: String) -> void: "--log-every": if _check_int(key, value): log_every = value.to_int() + "--bot-difficulty": + var found: bool = value == "mixed" + for index: int in Tuning.BOT_DIFFICULTIES.size(): + if Tuning.BOT_DIFFICULTIES[index]["name"] == value: + bot_difficulty = index + found = true + if not found: + errors.append("--bot-difficulty must be mixed, easy, normal or hard, got '%s'" % value) "--fault": fault = value _: diff --git a/src/server/server_loop.gd b/src/server/server_loop.gd index 6d6ec43..d787853 100644 --- a/src/server/server_loop.gd +++ b/src/server/server_loop.gd @@ -14,9 +14,12 @@ var sim: Simulation: return match_flow.sim ## Entity IDs of everyone in the current match, humans first. var player_ids: Array[int] = [] -var bots: Array[NavBot] = [] -## The current or next match's navigation grid, built while the lobby waits. +var bots: Array[BotBrain] = [] +## The current or next match's navigation grid and bot map, built while the lobby waits. var nav: NavGrid = null +var world: BotWorld = null +## Every bot's difficulty, or -1 to mix them: easy, normal, hard, in turn. +var bot_difficulty: int = -1 ## Wall-clock duration of every tick run, in microseconds. var tick_usec: PackedInt64Array = PackedInt64Array() ## Server ticks run, across every match. @@ -26,7 +29,8 @@ var ticks: int = 0 ## `human_players` join as idle participants with handles 1 and up; `bot_count` bots ## fill the rest of every match. With `rules` null the match starts at once, and the ## server goes back to the lobby after each match's results and starts another. -func _init(match_seed: int, human_players: int, bot_count: int, rules: MatchRules = null) -> void: +func _init(match_seed: int, human_players: int, bot_count: int, rules: MatchRules = null, difficulty: int = -1) -> void: + bot_difficulty = difficulty if rules == null: rules = MatchRules.immediate() rules.max_players = maxi(human_players + bot_count, 1) @@ -35,6 +39,7 @@ func _init(match_seed: int, human_players: int, bot_count: int, rules: MatchRule rules.min_players = 0 if human_players == 0 and bot_count > 0 else 1 match_flow = Match.new(match_seed, rules) nav = NavGrid.build(match_flow.sim) + world = BotWorld.build(match_flow.sim, nav) for handle: int in range(1, human_players + 1): match_flow.join(handle) if rules.lobby_ticks == 0 and rules.countdown_ticks == 0: @@ -47,8 +52,9 @@ func run_tick() -> void: var started: int = Time.get_ticks_usec() if match_flow.in_match(): nav.sync(sim) - for bot: NavBot in bots: - sim.submit_command(bot.player_id, bot.think(sim, nav)) + world.observe(sim) + for bot: BotBrain in bots: + sim.submit_command(bot.player_id, bot.think(sim, nav, world)) _advance() ticks += 1 tick_usec.append(Time.get_ticks_usec() - started) @@ -64,6 +70,7 @@ func _advance() -> void: bots.clear() if event["from"] == "results": nav = NavGrid.build(match_flow.sim) + world = BotWorld.build(match_flow.sim, nav) func _track_players() -> void: @@ -73,9 +80,9 @@ func _track_players() -> void: var entity_id: int = match_flow.entity_of[handle] player_ids.append(entity_id) if match_flow.bot_handles.has(handle): - var bot: NavBot = NavBot.new(entity_id) - bot.roam = true - bots.append(bot) + var level: int = bot_difficulty if bot_difficulty >= 0 else bots.size() % Tuning.BOT_DIFFICULTIES.size() + bots.append(BotBrain.new(entity_id, level)) + world.player_ids = player_ids.duplicate() ## Timing statistics over every tick run so far, in microseconds. diff --git a/src/sim/tuning.gd b/src/sim/tuning.gd index a0c5ce2..f635bae 100644 --- a/src/sim/tuning.gd +++ b/src/sim/tuning.gd @@ -223,6 +223,45 @@ const BOT_STUCK_REPATHS: int = 3 ## Each bot re-checks its remaining path against grid changes this often, in ticks. const BOT_PATH_CHECK_TICKS: int = 15 +# Bot brains. Bots loot, fight, heal and keep ahead of the tide with only what a player +# would know: what they can see, the map's points of interest, and the tide forecast. +## Per difficulty: `reaction` is seconds between first seeing an opponent and firing, +## `aim_error` the most their aim wanders off the target in degrees, `sight` how far +## they can pick an opponent out in metres, and `lead` how much of a moving target's +## travel they allow for with slow shots (0 none, 1 all of it). +const BOT_DIFFICULTIES: Array[Dictionary] = [ + {"name": "easy", "reaction": 0.9, "aim_error": 7.0, "sight": 45.0, "lead": 0.0}, + {"name": "normal", "reaction": 0.5, "aim_error": 3.5, "sight": 65.0, "lead": 0.5}, + {"name": "hard", "reaction": 0.25, "aim_error": 1.5, "sight": 90.0, "lead": 1.0}, +] +## Each bot looks around once in this many ticks. +const BOT_SENSE_TICKS: int = 6 +## Bots see this far to either side of where they face, and notice anyone this close +## whichever way they face. +const BOT_VIEW_HALF_ANGLE_DEGREES: float = 100.0 +const BOT_HEARING_METRES: float = 10.0 +## A bot remembers an opponent it has lost sight of for this long. +const BOT_MEMORY_SECONDS: float = 4.0 +## A bot's aim drifts to a new error this often, in ticks. +const BOT_AIM_WANDER_TICKS: int = 12 +## Bots ease off the trigger while bloom is above this, in degrees. +const BOT_BLOOM_PAUSE_DEGREES: float = 3.0 +## Bots notice items lying within this distance. +const BOT_LOOT_SIGHT_METRES: float = 12.0 +## The most weapons a bot carries; its other slots are for consumables. +const BOT_MAX_WEAPONS: int = 3 +## Ground counts as safe from the next tide level when it stands this far above it. +const BOT_SAFE_MARGIN_METRES: float = 1.5 +## A bot off safe ground leaves when the time to the next rise is less than its +## distance to safe ground at this speed, plus the buffer. +const BOT_FLEE_SPEED: float = 1.5 +const BOT_FLEE_BUFFER_SECONDS: float = 20.0 +## With less than this long before the water rises, bots only loot on safe ground. +const BOT_LOOT_TIDE_SECONDS: float = 30.0 +## Bots give up on a loot spot or an item they can't get to after this long. +const BOT_LOOT_TIMEOUT_SECONDS: float = 45.0 +const BOT_PICKUP_TIMEOUT_SECONDS: float = 8.0 + # Building const GRID_CELL_METRES: float = 4.0 ## The most of each material a player can carry. diff --git a/test/bots/bot_batch.gd b/test/bots/bot_batch.gd new file mode 100644 index 0000000..2c79dda --- /dev/null +++ b/test/bots/bot_batch.gd @@ -0,0 +1,96 @@ +## Runs whole bot-only matches and gathers what happened: who won, how everyone fell, +## how each difficulty placed and how long the ticks took. Shared by the tests and +## `make bot-matches`. +class_name BotBatch +extends RefCounted + +## Longest a match can run: the tide's whole schedule, sudden death and a little slack. +static func tick_limit() -> int: + return Tide.new(0).time_limit_offset() + 30 * Tuning.TICK_RATE_HZ + + +## Plays one match of `bots` bots on `seed_value`. `difficulty` -1 mixes the levels. +## Returns {"seed", "finished", "ticks", "winner", "winner_difficulty", "timed_out", +## "causes": {cause: count}, "places": {difficulty name: [place, ...]}, +## "eliminations": {difficulty name: count}, "shots", "slow_ticks", "timing", +## "state_hash"}. +static func run_match(seed_value: int, bots: int = Tuning.SOLO_PLAYERS, difficulty: int = -1) -> Dictionary: + var loop: ServerLoop = ServerLoop.new(seed_value, 0, bots, null, difficulty) + var flow: Match = loop.match_flow + var level_of: Dictionary = {} + for bot: BotBrain in loop.bots: + level_of[flow.handle_of[bot.player_id]] = bot.difficulty_name() + var result: Dictionary = { + "seed": seed_value, "finished": false, "winner": 0, "winner_difficulty": "", + "timed_out": false, "causes": {}, "places": {}, "eliminations": {}, "shots": 0, + "slow_ticks": [], + } + var limit: int = tick_limit() + while loop.ticks < limit and flow.phase != Match.RESULTS: + var before: int = Time.get_ticks_usec() + loop.run_tick() + if Time.get_ticks_usec() - before > ServerLoop.TICK_BUDGET_USEC: + result["slow_ticks"].append(loop.sim.tick) + for event: Dictionary in loop.sim.events: + if event["type"] == "shot": + result["shots"] += 1 + for event: Dictionary in flow.events: + if event["type"] == "match_ended": + result["timed_out"] = event["timed_out"] + result["ticks"] = loop.sim.tick + result["finished"] = flow.phase == Match.RESULTS + if flow.winners.size() > 0: + result["winner"] = flow.winners[0] + result["winner_difficulty"] = level_of.get(flow.winners[0], "") + for row: Dictionary in flow.summary(): + var level: String = level_of.get(row["handle"], "") + if not result["places"].has(level): + result["places"][level] = [] + result["eliminations"][level] = 0 + result["places"][level].append(row["place"]) + result["eliminations"][level] += row["eliminations"] + if row["place"] != 1: + var cause: String = row["cause"] + result["causes"][cause] = int(result["causes"].get(cause, 0)) + 1 + result["timing"] = loop.timing_stats() + result["state_hash"] = loop.sim.state_hash() + return result + + +## Adds up a list of run_match() results: {"matches", "finished", "with_winner", +## "timed_out", "deaths", "causes", "drown_share", "mean_place": {difficulty: mean}, +## "wins": {difficulty: count}, "eliminations": {difficulty: count}, "mean_ticks", +## "worst_p99_us", "over_budget"}. +static func summarise(results: Array[Dictionary]) -> Dictionary: + var total: Dictionary = { + "matches": results.size(), "finished": 0, "with_winner": 0, "timed_out": 0, "deaths": 0, + "causes": {}, "mean_place": {}, "wins": {}, "eliminations": {}, "worst_p99_us": 0, "over_budget": 0, + } + var places: Dictionary = {} + var ticks: int = 0 + for result: Dictionary in results: + total["finished"] += 1 if result["finished"] else 0 + total["with_winner"] += 1 if result["winner"] != 0 else 0 + total["timed_out"] += 1 if result["timed_out"] else 0 + ticks += result["ticks"] + for cause: String in result["causes"]: + total["causes"][cause] = int(total["causes"].get(cause, 0)) + int(result["causes"][cause]) + total["deaths"] += int(result["causes"][cause]) + for level: String in result["places"]: + if not places.has(level): + places[level] = [] + places[level].append_array(result["places"][level]) + total["eliminations"][level] = int(total["eliminations"].get(level, 0)) + int(result["eliminations"][level]) + var winner: String = result["winner_difficulty"] + if winner != "": + total["wins"][winner] = int(total["wins"].get(winner, 0)) + 1 + total["worst_p99_us"] = maxi(total["worst_p99_us"], int(result["timing"]["p99_us"])) + total["over_budget"] += int(result["timing"]["over_budget"]) + for level: String in places: + var sum: int = 0 + for place: int in places[level]: + sum += place + total["mean_place"][level] = float(sum) / places[level].size() + total["drown_share"] = float(total["causes"].get("drown", 0)) / maxi(total["deaths"], 1) + total["mean_ticks"] = ticks / maxi(results.size(), 1) + return total diff --git a/test/bots/bot_batch.gd.uid b/test/bots/bot_batch.gd.uid new file mode 100644 index 0000000..bf2cf6f --- /dev/null +++ b/test/bots/bot_batch.gd.uid @@ -0,0 +1 @@ +uid://uctfhr5365ql diff --git a/test/bots/test_bot_brain.gd b/test/bots/test_bot_brain.gd new file mode 100644 index 0000000..d29a8ef --- /dev/null +++ b/test/bots/test_bot_brain.gd @@ -0,0 +1,324 @@ +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"]) diff --git a/test/bots/test_bot_brain.gd.uid b/test/bots/test_bot_brain.gd.uid new file mode 100644 index 0000000..18347e5 --- /dev/null +++ b/test/bots/test_bot_brain.gd.uid @@ -0,0 +1 @@ +uid://c6ald8xgw6nsj diff --git a/test/bots/test_nav.gd b/test/bots/test_nav.gd index 14af3d3..db79bfe 100644 --- a/test/bots/test_nav.gd +++ b/test/bots/test_nav.gd @@ -207,8 +207,8 @@ func test_23_bots_stay_within_the_tick_budget_and_get_somewhere() -> void: assert_true(stats["p99_us"] < ServerLoop.TICK_BUDGET_USEC, "p99 tick under budget") assert_true(stats["over_budget"] <= ticks / 200, "at most 0.5% of ticks over budget (a busy shared host)") var walking: int = 0 - for bot: NavBot in loop.bots: - if bot.plans > 0: + for bot: BotBrain in loop.bots: + if bot.nav.plans > 0: walking += 1 assert_true(walking >= 20, "%d of 23 bots planned paths after landing" % walking) assert_eq(loop.bots.size(), 23) diff --git a/test/server/test_server_config.gd b/test/server/test_server_config.gd index aedc890..1afb72d 100644 --- a/test/server/test_server_config.gd +++ b/test/server/test_server_config.gd @@ -25,7 +25,7 @@ func test_defaults() -> void: func test_all_options() -> void: var config: ServerConfig = _parse([ "--path", "/ignored", "--server", "--seed=-17", "--port=4000", "--players=3", - "--bots=20", "--ticks=900", "--unthrottled", "--log-every=30", + "--bots=20", "--ticks=900", "--unthrottled", "--log-every=30", "--bot-difficulty=hard", ]) assert_true(config.is_valid(), str(config.errors)) assert_true(config.has_seed) @@ -36,6 +36,16 @@ func test_all_options() -> void: assert_eq(config.ticks, 900) assert_true(config.unthrottled) assert_eq(config.log_every, 30) + assert_eq(config.bot_difficulty, BotBrain.HARD) + assert_eq(config.to_dictionary()["bot_difficulty"], "hard") + + +func test_bot_difficulty_defaults_to_mixed_and_rejects_unknown_names() -> void: + assert_eq(_parse(["--server"]).bot_difficulty, -1) + assert_eq(_parse(["--server", "--bot-difficulty=mixed"]).bot_difficulty, -1) + assert_eq(_parse(["--server", "--bot-difficulty=easy"]).bot_difficulty, BotBrain.EASY) + var bad: ServerConfig = _parse(["--server", "--bot-difficulty=brutal"]) + assert_false(bad.is_valid()) func test_large_seed_round_trips() -> void: diff --git a/test/server/test_server_loop.gd b/test/server/test_server_loop.gd index e3eaa33..4395fbc 100644 --- a/test/server/test_server_loop.gd +++ b/test/server/test_server_loop.gd @@ -77,7 +77,7 @@ func test_server_returns_to_the_lobby_and_starts_the_next_match() -> void: assert_eq(loop.match_flow.phase, Match.DROP) assert_eq(loop.bots.size(), 3) var first_seed: int = loop.match_flow.current_seed() - for bot: NavBot in loop.bots.slice(1): + for bot: BotBrain in loop.bots.slice(1): loop.sim.entities.find(bot.player_id).health = 0 loop.run_tick() assert_eq(loop.match_flow.phase, Match.RESULTS) diff --git a/tools/bot_matches.gd b/tools/bot_matches.gd new file mode 100644 index 0000000..0f4f6a9 --- /dev/null +++ b/tools/bot_matches.gd @@ -0,0 +1,43 @@ +## Plays bot-only matches on a run of seeds and checks issue M5's acceptance: every +## match ends with a winner, under a tenth of deaths are drownings, and difficulty +## shows: easy bots place worst and hard bots take the most eliminations. +## +## tools/godot.sh --script res://tools/bot_matches.gd -- [--seeds=20] [--first=1] +## +## Prints one JSON line per match and a summary. Exits 1 if a check fails. +extends SceneTree + + +func _init() -> void: + var count: int = 20 + var first: int = 1 + for arg: String in OS.get_cmdline_user_args(): + if arg.begins_with("--seeds="): + count = arg.trim_prefix("--seeds=").to_int() + elif arg.begins_with("--first="): + first = arg.trim_prefix("--first=").to_int() + var results: Array[Dictionary] = [] + for seed_value: int in range(first, first + count): + var result: Dictionary = BotBatch.run_match(seed_value) + results.append(result) + print(JSON.stringify(result)) + var total: Dictionary = BotBatch.summarise(results) + print(JSON.stringify({"summary": total})) + var problems: Array[String] = [] + if total["with_winner"] != count or total["finished"] != count: + problems.append("%d of %d matches finished with a winner" % [total["with_winner"], count]) + if total["drown_share"] >= 0.1: + problems.append("%.1f%% of deaths were drownings" % (total["drown_share"] * 100.0)) + # Placement is noisy between neighbouring levels over 20 matches, so the check is on + # what holds up: easy bots place worst, and hard bots take the most eliminations. + var mean: Dictionary = total["mean_place"] + var kills: Dictionary = total["eliminations"] + if not (mean.get("easy", 0.0) > mean.get("normal", 99.0) and mean.get("easy", 0.0) > mean.get("hard", 99.0)): + problems.append("easy bots didn't place worst: %s" % mean) + if not (kills.get("hard", 0) > kills.get("normal", 0) and kills.get("hard", 0) > kills.get("easy", 0)): + problems.append("hard bots didn't take the most eliminations: %s" % kills) + for problem: String in problems: + print("bot-matches FAIL: %s" % problem) + if problems.is_empty(): + print("bot-matches: ok (%d matches, all with a winner, %.1f%% drowned, mean place %s, eliminations %s)" % [count, total["drown_share"] * 100.0, mean, kills]) + quit(0 if problems.is_empty() else 1) diff --git a/tools/bot_matches.gd.uid b/tools/bot_matches.gd.uid new file mode 100644 index 0000000..efacc80 --- /dev/null +++ b/tools/bot_matches.gd.uid @@ -0,0 +1 @@ +uid://dgpnwi76yahi5 diff --git a/tools/bot_matches.sh b/tools/bot_matches.sh new file mode 100755 index 0000000..607aa2b --- /dev/null +++ b/tools/bot_matches.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Plays bot-only matches on a run of seeds, under nice, and prints one JSON line per +# match, a summary and the verdict. See tools/bot_matches.gd for what is checked. +# +# tools/bot_matches.sh seeds 1 to 20 +# BOT_MATCH_SEEDS=5 BOT_MATCH_FIRST=40 tools/bot_matches.sh +set -uo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +count="${BOT_MATCH_SEEDS:-20}" +first="${BOT_MATCH_FIRST:-1}" +raw="$(nice -n 15 tools/godot.sh --script res://tools/bot_matches.gd -- --seeds="$count" --first="$first" 2>&1)" +code=$? +grep -E '^\{|^bot-matches' <<<"$raw" +if [[ "$code" -ne 0 ]] && ! grep -q '^bot-matches' <<<"$raw"; then + echo "bot-matches FAIL: the run exited $code" + tail -n 15 <<<"$raw" +fi +exit "$code"