M5: Bot looting, combat and tide awareness
BotBrain plays a match with the commands a player sends: it picks a landing marker near the barge's route, loots points of interest (following their own walking routes into huts, lofts and piers), fights opponents it can see, bandages itself, and gets to ground the coming tide will leave dry. BotWorld is the map every bot shares: loot markers, routes, and each tide phase's safe ground, which is the dry land joined to the island's highest walkable ground. Three difficulties (Tuning.BOT_DIFFICULTIES) set reaction time, sight range and aim error. The server mixes them unless --bot-difficulty says otherwise. NavGrid labels connected regions when it is built, so a goal that is cut off is turned down without a search of the whole island (about 70 ms each). make bot-matches plays 20 bot-only matches and checks winners, drownings and difficulty. Seeds 101 to 120: 20 of 20 with a winner, 7 of 460 deaths were drownings (1.5%), easy bots placed worst (13.7 against 11.8 and 12.0) and hard bots took the most eliminations (186 against 137 and 132). Closes #28 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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)
|
||||
@@ -0,0 +1 @@
|
||||
uid://jmh12jrvvnce
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
uid://vvulplgfes5l
|
||||
@@ -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()):
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
_:
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user