## 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, or go for one within Tuning.BOT_BRAWL_METRES with the ## boathook if not; 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. ## ## Bots build too (M6). An armed bot with nothing more pressing, and nobody about, ## gathers materials with the boathook. In a fight it puts a wall between itself and a ## shooter who catches it reloading, from ambush or worn down; walls itself off to heal ## instead of running when badly hurt; and builds ramps up to an opponent on a cliff or ## a steep rise. Late in the match, when the tide would catch it or at the last stand, ## it rings its cell with breakwaters. Every piece goes through the same build command ## a player sends, after the same Building.check the server makes. 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", "hold", "idle", "retreat", "brawl", "gather", "cover", "ramp" or ## "breakwater". 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 ## Health and armor at or under which this bot breaks off a fight, and until when it's ## running from one (H3). var _retreat_health: int = 0 var _retreat_until: int = -100000 var _retreat_goal: Vector3 = Vector3.ZERO ## Who last hit this bot, and when: an unarmed bot only swings back at them. var _hit_by: int = 0 var _hit_tick: int = -100000 var _hunt_goal: Vector3 = Vector3.ZERO var _holding: bool = false 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 ## M6: whether this bot gathers and builds. A batch turns it off for a control group. var builds: bool = true ## M6: what this bot built and how its fights went, for batch measurement. A fight is ## a stretch with an opponent in which shots or swings were traded; it ends after ## Tuning.BOT_FIGHT_GAP_SECONDS with nobody to fight, or with the bot's fall ("lost"). var stats: Dictionary = { "pieces": 0, "walls": 0, "ramps": 0, "breakwaters": 0, "harvested": 0, "fights": 0, "fights_built": 0, "fights_lost": 0, "fights_built_lost": 0, "fights_stocked": 0, "fights_stocked_built": 0, } var _in_fight: bool = false var _fight_traded: bool = false var _fight_built: bool = false var _fight_stocked: bool = false var _fight_seen: int = 0 var _stock_seen: int = 0 ## Gathering: the prop, when to give up on it, when each search radius was last tried ## (near, far), props given up on, and this tick's swing. var _gather_prop: int = -1 var _gather_deadline: int = 0 var _gather_checked: PackedInt32Array = PackedInt32Array([-100000, -100000]) var _gather_skipped: Dictionary = {} var _swing: bool = false var _swing_aim: Vector2 = Vector2.ZERO ## Cover: until when the bot stays behind it, which way the wall goes, whether it's up, ## when the cover began and when cover may be taken again. var _covering_until: int = -100000 var _cover_yaw: float = 0.0 var _cover_walls: int = 0 var _cover_since: int = 0 var _cover_ready: int = 0 ## Ramps placed this fight, until when the bot walks on up them, which way, and the ## slot of the last one, so the next continues from its top. var _ramps: int = 0 var _ramp_until: int = -100000 var _ramp_direction: Vector2 = Vector2.ZERO var _ramp_last: Vector4i = Vector4i.ZERO ## A ring of breakwaters: the cell it's round, its four slots, when it was begun (or ## -1), and the highest forecast level it's worth staying in for. var _ring_cell: Vector2i = Vector2i.ZERO var _ring_slots: Array[Vector4i] = [] var _ring_started: int = -1 var _ring_level: float = 0.0 ## This tick's piece, if any: kind (-1 for none), facing yaw and material. var _piece_kind: int = -1 var _piece_yaw: float = 0.0 var _piece_material: int = 0 ## A stand-in for the bot, posed for Building.target() and Building.check(). var _probe: SimEntity = SimEntity.new(0, SimEntity.ARCHETYPE_PLAYER) 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"]) _retreat_health = int(stats["retreat"]) 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: if _in_fight: _end_fight(true) return PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0) if me.drop_state != Drop.NONE: return _drop(sim, grid, world) if me.downed: return _crawl(sim, world, me) _count_building(world, me) _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 _check_retreat(sim, world, me, target, armed) var retreating: bool = sim.tick < _retreat_until if _fleeing or me.swimming: _covering_until = mini(_covering_until, sim.tick) var covering: bool = sim.tick < _covering_until if covering and target != null and target_visible and distance <= Tuning.BOT_BRAWL_METRES: # They came round the wall: fight. _covering_until = sim.tick covering = false var fighting: bool = target != null and target_visible and armed and not me.swimming and not retreating and not covering # Inside a hut or loft too: someone beating on you there gets a swing back. An # unarmed bot doesn't start a brawl; it keeps looking for a weapon (H3). var provoked: bool = target != null and target.id == _hit_by and sim.tick - _hit_tick <= roundi(Tuning.BOT_MEMORY_SECONDS * TICKS) var brawling: bool = (target != null and target_visible and not armed and not me.swimming and not _fleeing and not retreating and not covering and distance <= Tuning.BOT_BRAWL_METRES and provoked) var interact: bool = false var walk: bool = true var patient: SimEntity = _patient(sim, world, me) if not me.swimming else null var tending: bool = false # Where to go. _direct_on = false _swing = false var urgent: bool = _fleeing or retreating 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 _in_ring(sim, me): state = "breakwater" _stop() elif _fleeing: state = "flee" _go(_flee_goal, 3.0) elif covering: state = "cover" _stop() elif retreating: state = "retreat" _go(_retreat_goal, 3.0) elif fighting: state = "fight" _stop() elif brawling: state = "brawl" _stop() elif patient != null: # A teammate is down (M7): get to them and hold interact until they're up. state = "revive" if me.position.distance_to(patient.position) <= Tuning.REVIVE_RANGE * 0.75: _stop() tending = true else: _go(patient.position, Tuning.REVIVE_RANGE * 0.5) 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 elif not (builds and armed and _gather(sim, world, me, false)): interact = _loot(sim, grid, world, me) if state != "loot" and not (builds and armed and _gather(sim, world, me, true)): _hunt(sim, world) _plan_build(sim, grid, world, me, target, distance, fighting) # 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 if _swing: yaw = _swing_aim.x pitch = _swing_aim.y direction = Vector2.ZERO selection = Simulation.BOATHOOK_SLOT buttons |= PlayerCommand.BUTTON_FIRE # Fighting: face the target and fire, whatever the feet are doing. if fighting or (target != null and target_visible and armed and not me.swimming and _fleeing): 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 and state != "breakwater": 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 brawling: # No gun: walk in and swing the boathook. var aim: Vector2 = _aim_at(me, target, ItemCatalog.boathook()) yaw = aim.x pitch = aim.y var to: Vector2 = Vector2(target.position.x - me.position.x, target.position.z - me.position.z) var gap: float = to.length() if _stage == OUTSIDE: direction = to / gap if gap > Tuning.PLAYER_RADIUS * 2.0 + 0.6 else Vector2.ZERO buttons &= ~PlayerCommand.BUTTON_SPRINT var reach: float = Harvest.eye(me).distance_to(target.position + Vector3(0.0, Movement.body_height(target) * 0.62, 0.0)) if reach <= Tuning.BOT_SWING_METRES and sim.tick - _acquired_tick >= _reaction_ticks: buttons |= PlayerCommand.BUTTON_FIRE elif covering: # Behind the wall: heal, or finish reloading. var heal_slot: int = _heal_slot(me) if heal_slot >= 0: selection = heal_slot + 1 buttons |= PlayerCommand.BUTTON_FIRE elif me.reload_ticks > 0: # Stay behind it until the magazine's full. _covering_until = maxi(_covering_until, sim.tick + 2) elif armed: 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 elif sim.tick - _cover_since > roundi(Tuning.BOT_COVER_HOLD_SECONDS * TICKS): _covering_until = sim.tick elif sim.tick - _cover_since > roundi(Tuning.BOT_COVER_HOLD_SECONDS * TICKS): _covering_until = sim.tick 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 # Up a ramp toward someone above: keep walking, still shooting, until off the top of # the last one. var g: float = StructureSet.cell_size() var on_last: bool = (_ramps > 0 and Vector2i(floori(me.position.x / g), floori(me.position.z / g)) == Vector2i(_ramp_last.x, _ramp_last.z) and me.position.y > _ramp_last.y * Tuning.BUILD_LEVEL_METRES - 0.5) if on_last: _ramp_until = maxi(_ramp_until, sim.tick + TICKS / 2) if sim.tick < _ramp_until and target != null and not _fleeing and not covering and _stage == OUTSIDE: state = "ramp" direction = _ramp_direction if interact and not _interact_last: buttons |= PlayerCommand.BUTTON_INTERACT _interact_last = true else: _interact_last = false var chosen_material: int = 0 if _piece_kind >= 0: # This tick places a piece: build mode, facing where it goes, level. yaw = _piece_yaw pitch = 0.0 var cleared: int = PlayerCommand.BUTTON_AIM | PlayerCommand.BUTTON_RELOAD | PlayerCommand.BUTTON_INTERACT | PlayerCommand.BUTTON_SPRINT buttons = (buttons & ~cleared) | PlayerCommand.BUTTON_BUILD | PlayerCommand.BUTTON_FIRE selection = _piece_kind chosen_material = _piece_material if _piece_kind != StructureSet.RAMP: direction = Vector2.ZERO if tending: var to_patient: Vector2 = Vector2(patient.position.x - me.position.x, patient.position.z - me.position.z) if to_patient.length() > 0.05: yaw = atan2(to_patient.x, to_patient.y) pitch = 0.0 direction = Vector2.ZERO buttons = PlayerCommand.BUTTON_INTERACT chosen_material = 0 _track_fight(sim, world, me, buttons) 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, chosen_material) # Duos (M7) ## The nearest standing teammate, or null. func _standing_teammate(sim: Simulation, world: BotWorld, me: SimEntity) -> SimEntity: if me == null or me.team < 0: return null var best: SimEntity = null var best_gap: float = INF for other_id: int in world.player_ids: var other: SimEntity = sim.entities.find(other_id) if not Simulation.is_standing(other) or not sim.are_teammates(me, other) or other.drop_state != Drop.NONE: continue var gap: float = me.position.distance_squared_to(other.position) if gap < best_gap: best = other best_gap = gap return best ## The nearest downed teammate within Tuning.BOT_REVIVE_METRES, or null. func _patient(sim: Simulation, world: BotWorld, me: SimEntity) -> SimEntity: var best: SimEntity = null var best_gap: float = Tuning.BOT_REVIVE_METRES * Tuning.BOT_REVIVE_METRES for other_id: int in world.player_ids: var other: SimEntity = sim.entities.find(other_id) if other == null or not other.downed or other.eliminated or not sim.are_teammates(me, other): continue var gap: float = me.position.distance_squared_to(other.position) if gap <= best_gap: best = other best_gap = gap return best ## Downed: crawl straight for the nearest standing teammate, and stop beside them. func _crawl(sim: Simulation, world: BotWorld, me: SimEntity) -> PlayerCommand: state = "downed" _stop() _forget_target() var yaw: float = float(me.yaw) / PlayerCommand.YAW_STEPS * TAU var move: Vector2 = Vector2.ZERO var nearest: SimEntity = null var nearest_gap: float = INF for other_id: int in world.player_ids: var other: SimEntity = sim.entities.find(other_id) if not Simulation.is_standing(other) or not sim.are_teammates(me, other): continue var gap: float = me.position.distance_squared_to(other.position) if gap < nearest_gap: nearest = other nearest_gap = gap if nearest != null and nearest_gap > Tuning.REVIVE_RANGE * Tuning.REVIVE_RANGE * 0.25: var to: Vector2 = Vector2(nearest.position.x - me.position.x, nearest.position.z - me.position.z) yaw = atan2(to.x, to.y) move = Vector2(0.0, 1.0) return PlayerCommand.from_input(sim.tick, move, yaw, 0.0) # 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" var rider: SimEntity = sim.entities.find(player_id) if _landing < 0 and rider != null and rider.team >= 0 and world.team_landings.has(rider.team): # Duos (M7): land with the teammate who already chose. _landing = int(world.team_landings[rider.team]) _marker = _landing _marker_since = sim.tick _go(world.markers[_landing], 2.0) if _landing < 0 and not world.markers.is_empty() and sim.drop != null: var rng: RandomNumberGenerator = nav.stream(sim) 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) if near.is_empty(): _landing = rng.randi_range(0, world.markers.size() - 1) else: # Of a few spots, land at the one fewest others have picked nearby (H3). var best_crowd: int = 1 << 30 for _try: int in Tuning.BOT_LANDING_CHOICES: var pick: int = near[rng.randi_range(0, near.size() - 1)] var crowd: int = 0 for other: Vector3 in world.landings: if other.distance_to(world.markers[pick]) <= Tuning.BOT_LANDING_SPREAD_METRES: crowd += 1 if crowd < best_crowd: best_crowd = crowd _landing = pick world.landings.append(world.markers[_landing]) if rider != null and rider.team >= 0: world.team_landings[rider.team] = _landing _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: _hit_by = attacker_id _hit_tick = tick 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.downed and target_visible: # Duos (M7): a downed target can't shoot back, but its teammate can. Turn on the # teammate if they're in view; otherwise finish the job. for other_id: int in world.player_ids: var other: SimEntity = sim.entities.find(other_id) if Simulation.is_standing(other) and other.drop_state == Drop.NONE and sim.are_teammates(target, other) \ and me.position.distance_to(other.position) <= minf(_sight, Tuning.BOT_ENGAGE_METRES) and _can_see(sim, world, me, other, false): target_id = other.id _acquired_tick = tick _last_seen = other.position _last_seen_tick = tick return 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 or sim.are_teammates(me, other): continue # A bot picks out a new opponent only this close; one who shoots it first is # fought at any range it can see (H3). var gap: float = me.position.distance_squared_to(other.position) var notice: float = minf(_sight, Tuning.BOT_ENGAGE_METRES) if gap <= notice * notice: 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) ## Breaks off a fight: runs away from the opponent, over safe ground, for ## BOT_RETREAT_SECONDS, then heals if it can. Any bot without a gun runs from one held ## in view; a bot badly hurt with a way to heal breaks off too, except easy ones. func _check_retreat(sim: Simulation, world: BotWorld, me: SimEntity, target: SimEntity, armed: bool) -> void: if target == null or _fleeing or sim.tick < _retreat_until or sim.tick < _covering_until or me.swimming: return var outgunned: bool = not armed and target_visible and _holds_gun(target) var hurt: bool = _retreat_health > 0 and me.health + me.armor <= _retreat_health and _heal_slot(me) >= 0 if not outgunned and not hurt: return if sim.tick - _retreat_until < roundi(Tuning.BOT_RETREAT_SECONDS * TICKS): return if hurt and not outgunned and builds and sim.tick >= _cover_ready and _build_material(me, StructureSet.WALL) >= 0: # M6: wall off and heal where it stands instead of running across open ground. _take_cover(sim, me, target, Tuning.BOT_COVER_HEAL_SECONDS) return var away: Vector3 = me.position - target.position away.y = 0.0 away = away.normalized() if away.length() > 0.1 else Vector3(1.0, 0.0, 0.0) var phase: int = sim.tide.phase_at(sim.tick) if sim.tide != null else 0 _retreat_goal = world.random_safe_near(nav.stream(sim), phase, me.position + away * Tuning.BOT_RETREAT_METRES, Tuning.BOT_RETREAT_METRES * 0.5) _retreat_until = sim.tick + roundi(Tuning.BOT_RETREAT_SECONDS * TICKS) _forget_target() ## True if `other` has a gun in hand. static func _holds_gun(other: SimEntity) -> bool: if other.selected == Simulation.BOATHOOK_SLOT or other.selected > other.slot_items.size(): return false var def: ItemDef = ItemCatalog.get_def(other.slot_items[other.selected - 1]) return def != null and def.kind == ItemDef.WEAPON and def.damage > 0 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 = nav.stream(sim) _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 = nav.stream(sim) _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. ## With nothing to loot: roams to safe ground nearby, and holds there for a while ## before moving on (H3). The tide check moves it sooner if the water is coming. func _hunt(sim: Simulation, world: BotWorld) -> void: state = "hunt" var arrived: bool = _goal_set and nav.status != NavBot.MOVING if arrived and not _holding: _holding = true _hunt_until = sim.tick + roundi(Tuning.BOT_HOLD_SECONDS * TICKS) var me: SimEntity = sim.entities.find(player_id) var mate: SimEntity = _standing_teammate(sim, world, me) var strayed: bool = mate != null and me.position.distance_to(mate.position) > Tuning.BOT_REGROUP_METRES if strayed and (_holding or _hunt_goal.distance_to(mate.position) > Tuning.BOT_REGROUP_METRES * 0.5): # Duos (M7): too far from the teammate to help them up; go back to them. _holding = false _hunt_until = sim.tick if (not _goal_set and not _holding) or sim.tick >= _hunt_until: var phase: int = sim.tide.phase_at(sim.tick) if sim.tide != null else 0 var around: Vector3 = mate.position if strayed else me.position var radius: float = Tuning.BOT_REGROUP_METRES * 0.3 if strayed else Tuning.BOT_ROAM_METRES _hunt_goal = world.random_safe_near(nav.stream(sim), phase, around, radius) _hunt_until = sim.tick + 40 * TICKS _holding = false _go(_hunt_goal, 4.0) elif _holding: state = "hold" _stop() else: _go(_hunt_goal, 4.0) # Building (M6) ## Counts what the bot placed and gathered since it last thought. func _count_building(world: BotWorld, me: SimEntity) -> void: for kind: int in world.placed.get(player_id, []): stats["pieces"] += 1 match kind: StructureSet.WALL: stats["walls"] += 1 StructureSet.RAMP: stats["ramps"] += 1 StructureSet.BREAKWATER: stats["breakwaters"] += 1 if _in_fight: _fight_built = true var stock: int = 0 for amount: int in me.materials: stock += amount if stock > _stock_seen: stats["harvested"] += stock - _stock_seen _stock_seen = stock ## Starts or ends the fight the bot is in, for the measurement. func _track_fight(sim: Simulation, world: BotWorld, me: SimEntity, buttons: int) -> void: var engaged: bool = target_id != 0 or state == "cover" or state == "retreat" if engaged: if not _in_fight: _in_fight = true _fight_traded = false _fight_built = false _fight_stocked = builds and _build_material(me, StructureSet.WALL) >= 0 _ramps = 0 _fight_seen = sim.tick var shooting: bool = (buttons & PlayerCommand.BUTTON_FIRE) != 0 and (state == "fight" or state == "brawl" or state == "ramp") if shooting or world.attackers.has(player_id): _fight_traded = true elif _in_fight and sim.tick - _fight_seen > roundi(Tuning.BOT_FIGHT_GAP_SECONDS * TICKS): _end_fight(false) func _end_fight(lost: bool) -> void: _in_fight = false if not _fight_traded: return stats["fights"] += 1 if _fight_built: stats["fights_built"] += 1 if _fight_stocked: stats["fights_stocked"] += 1 if _fight_built: stats["fights_stocked_built"] += 1 if lost: stats["fights_lost"] += 1 if _fight_built: stats["fights_built_lost"] += 1 ## Goes behind a wall, toward `target`, for `seconds`. func _take_cover(sim: Simulation, me: SimEntity, target: SimEntity, seconds: float) -> void: _covering_until = sim.tick + roundi(seconds * TICKS) _cover_since = sim.tick _cover_yaw = atan2(target.position.x - me.position.x, target.position.z - me.position.z) _cover_walls = 0 _cover_ready = sim.tick + roundi(Tuning.BOT_COVER_SECONDS * TICKS) ## Chooses the piece, if any, this tick places. Sets `_piece_kind`. func _plan_build(sim: Simulation, grid: NavGrid, world: BotWorld, me: SimEntity, target: SimEntity, distance: float, fighting: bool) -> void: _piece_kind = -1 if not builds or me.swimming or not me.on_ground or me.action_cooldown > 0 or _stage != OUTSIDE: return var stranded: bool = _stranded(sim, world, me) if _in_ring(sim, me) or stranded or _ring_due(sim, world, me): if not _in_ring(sim, me): _begin_ring(sim, me, stranded) for facing: int in 4: if _try_place(sim, me, StructureSet.BREAKWATER, facing * PI * 0.5): state = "breakwater" return if state == "cover": if _cover_walls == 0: if _try_place(sim, me, StructureSet.WALL, _cover_yaw): _cover_walls = 1 elif sim.tick - _cover_since > TICKS / 2: # Nowhere to put a wall: give up on cover, and break off as before. _covering_until = sim.tick return if target == null: return var toward: float = atan2(target.position.x - me.position.x, target.position.z - me.position.z) var rise: float = target.position.y - me.position.y var across: float = Vector2(target.position.x - me.position.x, target.position.z - me.position.z).length() var climbing: bool = sim.tick < _ramp_until var ramp_wanted: bool = ((fighting or state == "chase" or state == "ramp") and _ramps < Tuning.BOT_RAMP_MAX and rise >= Tuning.BOT_RAMP_RISE_METRES and across <= Tuning.BOT_RAMP_REACH_METRES and (climbing or rise / maxf(across, 0.1) >= Tuning.BOT_RAMP_SLOPE or _steep_between(grid, me, target)) and _build_material(me, StructureSet.RAMP) >= 0) # Shot at while reloading, from ambush or when worn down: a wall to shelter behind, # unless it's from up a cliff, where a wall would only block the way up. var shot_at: bool = _hit_by == target.id and sim.tick - _hit_tick <= TICKS / 2 var exposed: bool = me.reload_ticks > 0 or sim.tick - _acquired_tick <= TICKS or me.health + me.armor <= Tuning.BOT_COVER_HEALTH if not ramp_wanted and (fighting or state == "chase") and shot_at and exposed and distance >= Tuning.BOT_COVER_MIN_METRES and sim.tick >= _cover_ready: if _try_place(sim, me, StructureSet.WALL, toward): _take_cover(sim, me, target, Tuning.BOT_COVER_HOLD_SECONDS) _cover_walls = 1 state = "cover" return # Someone up a steep slope or a cliff: ramp up to them. if ramp_wanted: # On the way up, the next ramp goes on from the top of the last: one cell on, # one cell up. Until the bot is there, it keeps walking. var facing: int = _ramp_last.w if climbing else posmod(roundi(toward / (PI * 0.5)), 4) var yaw: float = facing * PI * 0.5 if not climbing: # A ramp of its own already on the way (it broke off to take cover, say): # walk on up it. _probe.position = me.position _probe.yaw = posmod(roundi(yaw / TAU * PlayerCommand.YAW_STEPS), PlayerCommand.YAW_STEPS) _probe.pitch = 0 var first: Building.Target = Building.target(_probe, StructureSet.RAMP) for dy: int in [-1, 0, 1]: var slot: Vector4i = Vector4i(first.slot.x, first.slot.y + dy, first.slot.z, first.slot.w) var piece: StructureSet.Piece = sim.structures.find(sim.structures.at_slot(slot)) if piece != null and piece.kind == StructureSet.RAMP and piece.owner == player_id and piece.facing == facing: _ramp_last = Vector4i(slot.x, slot.y, slot.z, facing) var ahead: Vector2i = StructureSet.FACING_DIRECTIONS[facing] _ramp_direction = Vector2(ahead.x, ahead.y) _ramp_until = sim.tick + roundi(Tuning.BOT_RAMP_WALK_SECONDS * TICKS) return if climbing: _probe.position = me.position _probe.yaw = posmod(roundi(yaw / TAU * PlayerCommand.YAW_STEPS), PlayerCommand.YAW_STEPS) _probe.pitch = 0 var next: Building.Target = Building.target(_probe, StructureSet.RAMP) var step: Vector2i = StructureSet.FACING_DIRECTIONS[facing] var level_step: int = roundi(StructureSet.cell_size() / Tuning.BUILD_LEVEL_METRES) if next.slot.x != _ramp_last.x + step.x or next.slot.z != _ramp_last.z + step.y or next.slot.y != _ramp_last.y + level_step: return if _try_place(sim, me, StructureSet.RAMP, yaw): var placed: Building.Target = Building.target(_probe, StructureSet.RAMP) _ramp_last = Vector4i(placed.slot.x, placed.slot.y, placed.slot.z, facing) var step: Vector2i = StructureSet.FACING_DIRECTIONS[facing] _ramp_direction = Vector2(step.x, step.y) _ramps += 1 _ramp_until = sim.tick + roundi(Tuning.BOT_RAMP_WALK_SECONDS * TICKS) ## True if the ground on the line to `target` is a cliff, or a solid that `target` ## stands up on, somewhere a bot can't walk straight up. static func _steep_between(grid: NavGrid, me: SimEntity, target: SimEntity) -> bool: var from: Vector2 = Vector2(me.position.x, me.position.z) var to: Vector2 = Vector2(target.position.x, target.position.z) var samples: int = ceili(from.distance_to(to) / Tuning.BOT_NAV_CELL_METRES) for index: int in range(1, samples + 1): var at: Vector2 = from.lerp(to, float(index) / samples) var point: Vector2i = grid.point_of(Vector3(at.x, 0.0, at.y)) var cell: int = grid.index_of(point) if grid.steep[cell] != 0: return true if grid.blocked[cell] > 0 and target.position.y > grid.heights[cell] + Tuning.BOT_RAMP_RISE_METRES * 0.5: return true return false ## Starts a ring of breakwaters round the bot's cell. Stranded, it's worth staying in ## while the coming level is within what a breakwater holds back; at the last stand, ## whatever comes. func _begin_ring(sim: Simulation, me: SimEntity, stranded: bool) -> void: var g: float = StructureSet.cell_size() _ring_cell = Vector2i(floori(me.position.x / g), floori(me.position.z / g)) _ring_started = sim.tick _ring_level = me.position.y + Tuning.BREAKWATER_MAX_HEAD - 1.0 if stranded else INF _ring_slots.clear() _probe.position = me.position _probe.pitch = 0 for facing: int in 4: _probe.yaw = posmod(roundi(facing * 0.25 * PlayerCommand.YAW_STEPS), PlayerCommand.YAW_STEPS) _ring_slots.append(Building.target(_probe, StructureSet.BREAKWATER).slot) ## True while the bot is in the cell it began ringing: for two seconds while the ring ## goes up, then for as long as all four stand and the coming level is one it holds. func _in_ring(sim: Simulation, me: SimEntity) -> bool: if _ring_started < 0: return false var g: float = StructureSet.cell_size() if Vector2i(floori(me.position.x / g), floori(me.position.z / g)) != _ring_cell or me.swimming: _ring_started = -1 return false if sim.tide != null and sim.tide.forecast_at(sim.tick) > _ring_level: _ring_started = -1 return false if sim.tick - _ring_started < 2 * TICKS: return true for slot: Vector4i in _ring_slots: if not sim.structures.occupied(slot): _ring_started = -1 return false return true ## True when the bot is running from the tide late in the match (the last ## BOT_STRAND_PHASES phases) and can't make it: the sea will reach its feet before it ## could walk to dry ground, though no higher than a breakwater holds back, and it can ## afford a ring. func _stranded(sim: Simulation, world: BotWorld, me: SimEntity) -> bool: if not _fleeing or sim.tide == null or world.phase_count() == 0: return false var material: int = _build_material(me, StructureSet.BREAKWATER) if material < 0 or me.materials[material] < 4 * StructureSet.cost_of(StructureSet.BREAKWATER): return false if sim.tide.phase_at(sim.tick) < world.phase_count() - Tuning.BOT_STRAND_PHASES: return false var feet: float = me.position.y if sim.tide.forecast_at(sim.tick) > feet + Tuning.BREAKWATER_MAX_HEAD - 1.0: return false if sim.water_level_at(me.position) > feet - 0.3: return false var walk: float = Vector2(_flee_goal.x - me.position.x, _flee_goal.z - me.position.z).length() / Tuning.BOT_FLEE_SPEED for second: int in range(0, ceili(walk) + 1): if sim.tide.level_at(sim.tick + second * TICKS) >= feet - 0.3: return true return false ## True at the last stand: the tide's phase leaves no dry ground, the bot is on the ## last high point, and the rise has begun or is BOT_RING_SECONDS off. func _ring_due(sim: Simulation, world: BotWorld, me: SimEntity) -> bool: if sim.tide == null or world.phase_count() == 0: return false var phase: int = clampi(sim.tide.phase_at(sim.tick), 0, world.phase_count() - 1) if world.phase_cells[phase] != 0 or not world.is_safe(me.position, phase): return false return sim.tide.stage_at(sim.tick) != Tide.HOLD or sim.tide.ticks_until_rise(sim.tick) <= roundi(Tuning.BOT_RING_SECONDS * TICKS) ## The material to build `kind` in: whichever the bot has most of, if that covers the ## cost, or -1. static func _build_material(me: SimEntity, kind: int) -> int: var best: int = 0 for code: int in Materials.NAMES.size(): if me.materials[code] > me.materials[best]: best = code return best if me.materials[best] >= StructureSet.cost_of(kind) else -1 ## Sets this tick's piece to `kind`, facing `yaw`, if the server would accept it from ## where the bot stands. Returns whether it did. func _try_place(sim: Simulation, me: SimEntity, kind: int, yaw: float) -> bool: var material: int = _build_material(me, kind) if material < 0: return false _probe.position = me.position _probe.yaw = posmod(roundi(yaw / TAU * PlayerCommand.YAW_STEPS), PlayerCommand.YAW_STEPS) _probe.pitch = 0 _probe.health = me.health _probe.crouching = me.crouching _probe.swimming = me.swimming _probe.drop_state = me.drop_state _probe.materials = me.materials var at: Building.Target = Building.target(_probe, kind) if Building.check(sim, _probe, at, material) != Building.Result.OK: return false _piece_kind = kind _piece_yaw = yaw _piece_material = material return true ## Gathers materials with the boathook: carries on with the prop it's at, or, at most ## once a second and only when it's been quiet a while and the bot isn't hurt, looks ## for one within BOT_HARVEST_NEAR_METRES (`far` false) or ## BOT_HARVEST_METRES. Sets `state` to "gather" and returns true while it has one. func _gather(sim: Simulation, world: BotWorld, me: SimEntity, far: bool) -> bool: var stock: int = 0 for amount: int in me.materials: stock = maxi(stock, amount) var wanted: int = Tuning.BOT_BUILD_STOCK if sim.tide != null and world.phase_count() > 0 and sim.tide.phase_at(sim.tick) >= world.phase_count() - Tuning.BOT_STRAND_PHASES: # Late in the match: enough for a ring of breakwaters. wanted = 4 * StructureSet.cost_of(StructureSet.BREAKWATER) if stock >= wanted or not Harvest.can_swing(me): _gather_prop = -1 return false if _gather_prop >= 0 and (not sim.props.is_standing(_gather_prop) or sim.tick > _gather_deadline): if sim.props.is_standing(_gather_prop): _gather_skipped[_gather_prop] = true _gather_prop = -1 if _gather_prop < 0: var quiet: int = roundi(Tuning.BOT_GATHER_QUIET_SECONDS * TICKS) if sim.tick - _last_seen_tick < quiet or sim.tick - _hit_tick < quiet or me.health + me.armor < Tuning.BOT_GATHER_HEALTH: return false var index: int = 1 if far else 0 if sim.tick - _gather_checked[index] < TICKS: return false _gather_checked[index] = sim.tick _gather_prop = _find_gather_prop(sim, world, me, Tuning.BOT_HARVEST_METRES if far else Tuning.BOT_HARVEST_NEAR_METRES) if _gather_prop < 0: return false var gap: float = PropSet._distance_to_box(sim.props.boxes[_gather_prop], me.position) _gather_deadline = sim.tick + roundi((Tuning.BOT_HARVEST_SECONDS + gap / 3.0) * TICKS) state = "gather" _stop() var box: AABB = sim.props.boxes[_gather_prop] var eye: Vector3 = Harvest.eye(me) var centre: Vector3 = box.get_center() var aim: Vector3 = Vector3(centre.x, clampf(eye.y, box.position.y + 0.2, box.end.y - 0.1), centre.z) var to: Vector3 = aim - eye if PropSet._distance_to_box(box, eye) <= Harvest.reach() - 0.6: _swing = true _swing_aim = Vector2(atan2(to.x, to.z), atan2(to.y, Vector2(to.x, to.z).length())) return true _walk_to(me, Vector3(centre.x, box.position.y, centre.z), 0.0) if _direct_stalled > 3 * TICKS: _gather_skipped[_gather_prop] = true _gather_prop = -1 return true ## The nearest standing prop of a building material within `radius`, on dry ground ## about level with the bot and outside huts and lofts, that it hasn't given up on. func _find_gather_prop(sim: Simulation, world: BotWorld, me: SimEntity, radius: float) -> int: for prop: int in sim.props.near(me.position, radius): if _gather_skipped.has(prop) or not Materials.is_valid(Materials.code_of(sim.props.material_of(prop))): continue var box: AABB = sim.props.boxes[prop] var foot: Vector3 = Vector3(box.get_center().x, box.position.y, box.get_center().z) if absf(box.position.y - me.position.y) > 3.0 or not _spot_allowed(sim, world, foot): continue if world.in_routed_place(foot): continue return prop return -1