B9: Loot tables and containers

Seeded loot at every point of interest's loot markers, rolled once per match
from the "loot" stream by LootSet.plan() and placed by Simulation.place_loot().

- Each marker holds a sea chest (chance by location) or floor loot (rolls on
  the location's weapon/consumable/ammo/nothing weights). Weapons roll a tier
  from the location's tier weights and come with their ammunition; chests
  hold a weapon (best of two tier rolls), a consumable and spare ammunition.
- Interact opens the nearest closed chest in reach unless a pickup is nearer,
  and spills its contents as pickups.
- Washed-up crate props hold one roll of the crate table and spill it when
  broken by any means.
- If the rolls leave fewer POI weapons than LOOT_MIN_POI_WEAPONS (one per
  player in a full lobby), extra weapon rolls top up floor spots.
- Chest and crate state is part of state_hash(). ServerLoop places loot.

Tests: test_loot (12), including a statistics run of 1,000 loot seeds over
four generated islands that checks tier shares against the tables, that
shrines beat hamlets, and that every match has a weapon per player at POIs
and 1.25 per player counting crates.

Closes #23

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 20:16:20 -05:00
co-authored by Claude Opus 5.5
parent 0c6ad36105
commit 0013a81658
9 changed files with 677 additions and 6 deletions
+1
View File
@@ -24,6 +24,7 @@ func _init(match_seed: int, human_players: int, bot_count: int) -> void:
bots.append(WanderBot.new(id))
# Every match starts on the sky barge.
sim.start_drop()
sim.place_loot()
## Runs one tick and records how long it took.
+255
View File
@@ -0,0 +1,255 @@
## The match's loot: floor loot and sea chests at the points of interest' loot markers,
## and what each washed-up crate holds. Everything is rolled once, from the seeded
## "loot" stream, when the match places its loot, so what a chest or crate holds never
## depends on who opens it first or when.
##
## A stack is a PackedInt32Array of [item code, count, loaded rounds (-1 full), tier],
## ready for Inventory.spawn_pickup. Sources and their tables are in Tuning.LOOT_SOURCES.
class_name LootSet
extends RefCounted
const CATEGORIES: Array[String] = ["weapon", "consumable", "ammo", "nothing"]
## The prop kind whose props hold loot.
const CRATE_KIND: String = "crate"
## Floor loot: {"position": Vector3, "source": String, "stacks": Array[PackedInt32Array]}.
var floor_spots: Array[Dictionary] = []
## Sea chests, by index: where each stands, the source table it rolled from, what it
## holds, and whether it has been opened (1) or not (0).
var chest_positions: Array[Vector3] = []
var chest_sources: Array[String] = []
var chest_contents: Array[Array] = []
var chest_opened: PackedByteArray = PackedByteArray()
## Prop index -> Array[PackedInt32Array] for every crate prop. Spilled crates are erased.
var crate_contents: Dictionary = {}
## Rolls a match's loot. `markers` are PoiSet.loot_markers(); `crates` maps each crate
## prop's index to the point its loot spills from.
static func plan(rng: RandomNumberGenerator, markers: Array[Dictionary], crates: Dictionary) -> LootSet:
var loot: LootSet = LootSet.new()
for marker: Dictionary in markers:
var source: String = marker["kind"]
var table: Dictionary = Tuning.LOOT_SOURCES[source]
if rng.randf() < float(table["chest"]):
loot.chest_positions.append(marker["position"])
loot.chest_sources.append(source)
loot.chest_contents.append(roll_chest(rng, source))
loot.chest_opened.append(0)
else:
var stacks: Array[PackedInt32Array] = []
for _roll: int in int(table["rolls"]):
stacks.append_array(roll_category(rng, source, _pick_category(rng, table)))
loot.floor_spots.append({"position": marker["position"], "source": source, "stacks": stacks})
loot._top_up_weapons(rng)
var crate_ids: Array = crates.keys()
crate_ids.sort()
for prop: int in crate_ids:
var table: Dictionary = Tuning.LOOT_SOURCES[CRATE_KIND]
var stacks: Array[PackedInt32Array] = []
for _roll: int in int(table["rolls"]):
stacks.append_array(roll_category(rng, CRATE_KIND, _pick_category(rng, table)))
loot.crate_contents[prop] = stacks
return loot
## Weapons at points of interest, on floors and in chests. Crates aren't counted.
func poi_weapons() -> int:
var count: int = 0
for spot: Dictionary in floor_spots:
count += _weapons_in(spot["stacks"])
for contents: Array in chest_contents:
count += _weapons_in(contents)
return count
## Below Tuning.LOOT_MIN_POI_WEAPONS weapons at points of interest, adds weapon rolls to
## the floor spots in marker order until there are enough, so no match is starved.
func _top_up_weapons(rng: RandomNumberGenerator) -> void:
if floor_spots.is_empty():
return
var missing: int = Tuning.LOOT_MIN_POI_WEAPONS - poi_weapons()
var index: int = 0
while missing > 0:
var spot: Dictionary = floor_spots[index % floor_spots.size()]
spot["stacks"].append_array(_roll_weapon(rng, spot["source"], 1))
spot["topped_up"] = int(spot.get("topped_up", 0)) + 1
missing -= 1
index += 1
static func _weapons_in(stacks: Array) -> int:
var count: int = 0
for stack: PackedInt32Array in stacks:
if ItemCatalog.get_def(stack[0]).kind == ItemDef.WEAPON:
count += 1
return count
## A chest's contents: weapons with their ammunition, consumables and extra ammunition.
static func roll_chest(rng: RandomNumberGenerator, source: String) -> Array[PackedInt32Array]:
var stacks: Array[PackedInt32Array] = []
for _index: int in Tuning.LOOT_CHEST_WEAPONS:
stacks.append_array(_roll_weapon(rng, source, Tuning.LOOT_CHEST_TIER_ROLLS))
for _index: int in Tuning.LOOT_CHEST_CONSUMABLES:
stacks.append_array(roll_category(rng, source, "consumable"))
for _index: int in Tuning.LOOT_CHEST_EXTRA_AMMO:
stacks.append_array(roll_category(rng, source, "ammo"))
return stacks
## The stacks one roll of a category gives.
static func roll_category(rng: RandomNumberGenerator, source: String, category: String) -> Array[PackedInt32Array]:
var stacks: Array[PackedInt32Array] = []
match category:
"weapon":
stacks.append_array(_roll_weapon(rng, source, 1))
"consumable":
var id: String = _pick_by_rarity(rng, Tuning.ITEMS)
stacks.append(_stack(id, int(Tuning.ITEMS[id]["loot"]), 0))
"ammo":
var ammo_ids: Array = Tuning.AMMO.keys()
var id: String = ammo_ids[rng.randi_range(0, ammo_ids.size() - 1)]
stacks.append(_stack(id, int(Tuning.AMMO[id]["pickup"]), 0))
return stacks
## Rolls a tier from a source's weights, `rolls` times, keeping the best.
static func roll_tier(rng: RandomNumberGenerator, source: String, rolls: int) -> int:
var weights: Array = Tuning.LOOT_SOURCES[source]["tiers"]
var best: int = 0
for _roll: int in rolls:
best = maxi(best, _pick_weighted(rng, weights))
return best
## Weapon item IDs that can spawn as loot: every weapon except the boathook.
static func loot_weapons() -> Dictionary:
var weapons: Dictionary = {}
for id: String in Tuning.WEAPONS:
if id != ItemCatalog.BOATHOOK:
weapons[id] = Tuning.WEAPONS[id]
return weapons
## How many chests haven't been opened yet.
func closed_chests() -> int:
return chest_opened.count(0)
## Puts the floor loot in the world as pickups.
func place_floor(sim: Simulation) -> void:
for spot: Dictionary in floor_spots:
_spill(sim, spot["position"], spot["stacks"])
## The nearest closed chest whose base is within Tuning.CHEST_RANGE of `feet`, or -1.
## Ties go to the lower index.
func nearest_chest(feet: Vector3) -> int:
var best: int = -1
var best_distance: float = Tuning.CHEST_RANGE
for index: int in chest_positions.size():
if chest_opened[index] != 0:
continue
var distance: float = chest_positions[index].distance_to(feet)
if distance <= best_distance and (best == -1 or distance < best_distance):
best = index
best_distance = distance
return best
## Opens the nearest closed chest in reach, unless a pickup is nearer, and spills what
## it holds. Returns the chest's index, or -1. Appends a "chest_opened" event.
func open_nearest(sim: Simulation, player: SimEntity) -> int:
var chest: int = nearest_chest(player.position)
if chest < 0:
return -1
var pickup_id: int = Inventory.nearest_pickup(sim, player)
if pickup_id != 0:
var pickup: SimEntity = sim.entities.find(pickup_id)
if pickup.position.distance_to(player.position) < chest_positions[chest].distance_to(player.position):
return -1
chest_opened[chest] = 1
var ids: Array[int] = _spill(sim, chest_positions[chest], chest_contents[chest])
sim.events.append({"type": "chest_opened", "player": player.id, "chest": chest, "pickups": ids})
return chest
## Spills a broken crate's loot where it stood. Returns the new pickups' IDs.
func spill_crate(sim: Simulation, prop: int, at: Vector3) -> Array[int]:
if not crate_contents.has(prop):
return []
var stacks: Array = crate_contents[prop]
crate_contents.erase(prop)
return _spill(sim, at, stacks)
## Opened flags and unspilled crates, for Simulation.state_hash().
func write_state(buffer: StreamPeerBuffer) -> void:
buffer.put_64(chest_positions.size())
buffer.put_data(chest_opened)
var crate_ids: Array = crate_contents.keys()
crate_ids.sort()
buffer.put_64(crate_ids.size())
for prop: int in crate_ids:
buffer.put_32(prop)
func _spill(sim: Simulation, at: Vector3, stacks: Array) -> Array[int]:
var ids: Array[int] = []
for index: int in stacks.size():
var stack: PackedInt32Array = stacks[index]
var spot: Vector3 = at
if stacks.size() > 1:
var angle: float = TAU * index / stacks.size()
spot += Vector3(sin(angle), 0.0, cos(angle)) * Tuning.LOOT_SCATTER_METRES
ids.append(Inventory.spawn_pickup(sim, spot, stack[0], stack[1], stack[2], stack[3]))
return ids
static func _roll_weapon(rng: RandomNumberGenerator, source: String, tier_rolls: int) -> Array[PackedInt32Array]:
var stacks: Array[PackedInt32Array] = []
var weapons: Dictionary = loot_weapons()
var id: String = _pick_by_rarity(rng, weapons)
var stats: Dictionary = weapons[id]
var thrown: bool = int(stats.get("stack", 1)) > 1
var tier: int = roll_tier(rng, source, tier_rolls)
stacks.append(_stack(id, Tuning.LOOT_THROWN_COUNT if thrown else 1, tier))
if stats.has("ammo"):
var ammo_id: String = stats["ammo"]
for _index: int in Tuning.LOOT_AMMO_WITH_WEAPON:
stacks.append(_stack(ammo_id, int(Tuning.AMMO[ammo_id]["pickup"]), 0))
return stacks
static func _stack(id: String, count: int, tier: int) -> PackedInt32Array:
return PackedInt32Array([ItemCatalog.code_of(id), count, -1, tier])
static func _pick_category(rng: RandomNumberGenerator, table: Dictionary) -> String:
var weights: Array = []
for category: String in CATEGORIES:
weights.append(int(table[category]))
return CATEGORIES[_pick_weighted(rng, weights)]
## Picks a key of `table` weighted by LOOT_RARITY_WEIGHTS of each entry's "rarity".
static func _pick_by_rarity(rng: RandomNumberGenerator, table: Dictionary) -> String:
var ids: Array = table.keys()
var weights: Array = []
for id: String in ids:
weights.append(Tuning.LOOT_RARITY_WEIGHTS[int(table[id].get("rarity", 0))])
return ids[_pick_weighted(rng, weights)]
## An index into `weights`, chosen in proportion to its weight. Uses one draw.
static func _pick_weighted(rng: RandomNumberGenerator, weights: Array) -> int:
var total: int = 0
for weight: int in weights:
total += weight
var roll: int = rng.randi_range(0, total - 1)
for index: int in weights.size():
roll -= int(weights[index])
if roll < 0:
return index
return weights.size() - 1
+1
View File
@@ -0,0 +1 @@
uid://c3sor06dyfkns
+42 -1
View File
@@ -33,6 +33,9 @@ var structures: StructureSet = StructureSet.new()
## The sky barge, from start_drop() on. Null in matches and tests that start on foot.
var drop: Drop = null
## Floor loot, sea chests and crate contents. Empty until place_loot().
var loot: LootSet = LootSet.new()
## Items lying in the world, as entity IDs in ascending order. See Inventory.
var pickups: Array[int] = []
## Shots in flight, as entity IDs in ascending order. See Weapons.
@@ -44,6 +47,8 @@ var events: Array[Dictionary] = []
## Player entity ID -> { command tick -> PlayerCommand }
var _pending: Dictionary = {}
## How many entries of props.destroyed have been checked for crate loot.
var _destroyed_checked: int = 0
## Player entity IDs, ascending.
var _players: Array[int] = []
@@ -115,6 +120,26 @@ func start_drop() -> void:
Drop.board(entities.find(player_id), drop.barge_position(tick))
## Rolls the match's loot from the "loot" stream and puts the floor loot in the world.
## Chests and crates spill theirs when opened or broken. Does nothing on a test ground
## with no island, and only works once.
func place_loot() -> void:
if island == null or loot.floor_spots.size() + loot.chest_positions.size() + loot.crate_contents.size() > 0:
return
loot = LootSet.plan(rng.stream("loot"), pois.loot_markers(), crate_spill_points(props))
loot.place_floor(self)
## Each crate prop's index mapped to where its loot spills: the middle of its base.
static func crate_spill_points(prop_set: PropSet) -> Dictionary:
var points: Dictionary = {}
for prop: int in prop_set.count():
if prop_set.kind_name(prop) == LootSet.CRATE_KIND and prop_set.is_standing(prop):
var box: AABB = prop_set.boxes[prop]
points[prop] = Vector3(box.get_center().x, box.position.y, box.get_center().z)
return points
## Advances the simulation by one tick.
func step() -> void:
events.clear()
@@ -133,6 +158,7 @@ func step() -> void:
else:
_apply_command(player, command)
Weapons.advance_projectiles(self)
_spill_broken_crates()
_check_eliminations()
if drop != null and not drop.finished and drop.is_over(tick + 1):
# The end of the route: everyone still aboard goes over the side.
@@ -170,7 +196,8 @@ func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
Inventory.select(player, command.selection)
if Harvest.can_swing(player):
if pressed & PlayerCommand.BUTTON_INTERACT:
Inventory.interact(self, player)
if loot.open_nearest(self, player) < 0:
Inventory.interact(self, player)
if pressed & PlayerCommand.BUTTON_DROP:
Inventory.drop_held(self, player)
if command != null and command.is_pressed(PlayerCommand.BUTTON_RELOAD):
@@ -192,6 +219,19 @@ func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
Weapons.fire(self, player, command.is_pressed(PlayerCommand.BUTTON_AIM))
## Spills the loot of every crate destroyed since the last check, however it broke.
func _spill_broken_crates() -> void:
while _destroyed_checked < props.destroyed.size():
var prop: int = props.destroyed[_destroyed_checked]
_destroyed_checked += 1
if not loot.crate_contents.has(prop):
continue
var box: AABB = props.boxes[prop]
var at: Vector3 = Vector3(box.get_center().x, box.position.y, box.get_center().z)
var ids: Array[int] = loot.spill_crate(self, prop, at)
events.append({"type": "crate_spilled", "prop": prop, "pickups": ids})
## Marks players whose health reached 0 as eliminated, and drops what they carried.
func _check_eliminations() -> void:
for player_id: int in _players:
@@ -282,6 +322,7 @@ func state_hash() -> String:
buffer.put_64(props.count())
buffer.put_data(props.health.to_byte_array())
structures.write_state(buffer)
loot.write_state(buffer)
var hasher: HashingContext = HashingContext.new()
hasher.start(HashingContext.HASH_SHA256)
+38 -4
View File
@@ -336,8 +336,42 @@ const LINE_PULL_LIFT: float = 4.0
# unless interrupted. `heal` restores health up to `heal_cap` (default full), `armor`
# adds armor up to PLAYER_MAX_ARMOR. An item that would do nothing can't be started.
const ITEMS: Dictionary = {
"sailcloth_bandage": {"heal": 25, "heal_cap": 75, "use_seconds": 3.0, "stack": 6, "rarity": 0},
"brine_tonic": {"heal": 60, "use_seconds": 8.0, "stack": 3, "rarity": 1},
"cork_vest": {"armor": 50, "use_seconds": 5.0, "stack": 2, "rarity": 1},
"tar_patch": {"armor": 20, "use_seconds": 2.0, "stack": 5, "rarity": 0},
"sailcloth_bandage": {"heal": 25, "heal_cap": 75, "use_seconds": 3.0, "stack": 6, "rarity": 0, "loot": 3},
"brine_tonic": {"heal": 60, "use_seconds": 8.0, "stack": 3, "rarity": 1, "loot": 1},
"cork_vest": {"armor": 50, "use_seconds": 5.0, "stack": 2, "rarity": 1, "loot": 1},
"tar_patch": {"armor": 20, "use_seconds": 2.0, "stack": 5, "rarity": 0, "loot": 2},
}
# Loot. Every loot marker at a point of interest holds either a sea chest, with chance
# `chest`, or floor loot: `rolls` rolls on the source's category weights. Washed-up
# crates (props) hold one source "crate" roll each and spill it when broken. A weapon
# rolls its tier from `tiers` (weights, lowest tier first) and comes with
# LOOT_AMMO_WITH_WEAPON pickups of its ammunition. Within a category, an item's weight
# is LOOT_RARITY_WEIGHTS[rarity]. Consumables spawn `loot` of themselves (ITEMS), thrown
# weapons LOOT_THROWN_COUNT, and ammunition one pickup amount (AMMO).
const LOOT_SOURCES: Dictionary = {
"hamlet": {"chest": 0.3, "rolls": 2, "weapon": 50, "consumable": 25, "ammo": 15, "nothing": 10, "tiers": [55, 30, 12, 3]},
"dock": {"chest": 0.4, "rolls": 2, "weapon": 45, "consumable": 25, "ammo": 20, "nothing": 10, "tiers": [50, 32, 14, 4]},
"salt_works": {"chest": 0.3, "rolls": 2, "weapon": 45, "consumable": 30, "ammo": 15, "nothing": 10, "tiers": [55, 30, 12, 3]},
"quarry": {"chest": 0.4, "rolls": 2, "weapon": 45, "consumable": 20, "ammo": 25, "nothing": 10, "tiers": [50, 32, 14, 4]},
"lighthouse": {"chest": 0.6, "rolls": 2, "weapon": 50, "consumable": 25, "ammo": 20, "nothing": 5, "tiers": [35, 35, 22, 8]},
"shrine": {"chest": 0.8, "rolls": 2, "weapon": 55, "consumable": 25, "ammo": 15, "nothing": 5, "tiers": [20, 35, 30, 15]},
"crate": {"chest": 0.0, "rolls": 1, "weapon": 35, "consumable": 30, "ammo": 25, "nothing": 10, "tiers": [65, 27, 7, 1]},
}
## A sea chest holds this many weapons and consumables, and ammunition for each weapon
## plus LOOT_CHEST_EXTRA_AMMO random ammunition pickups. Its weapons roll their tier
## LOOT_CHEST_TIER_ROLLS times and keep the best.
const LOOT_CHEST_WEAPONS: int = 1
const LOOT_CHEST_CONSUMABLES: int = 1
const LOOT_CHEST_EXTRA_AMMO: int = 1
const LOOT_CHEST_TIER_ROLLS: int = 2
## If the rolls leave fewer weapons than this on floors and in chests, extra weapon
## rolls are added to floor spots in marker order: one per player in a full lobby.
const LOOT_MIN_POI_WEAPONS: int = SOLO_PLAYERS
const LOOT_RARITY_WEIGHTS: Array[int] = [6, 3, 1]
const LOOT_AMMO_WITH_WEAPON: int = 1
const LOOT_THROWN_COUNT: int = 2
## Interact opens a closed chest whose base is within this distance of the feet.
const CHEST_RANGE: float = 2.5
## Loot from one spot lands on a ring this far from it.
const LOOT_SCATTER_METRES: float = 0.7