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
+20
View File
@@ -225,6 +225,26 @@ used up; taking damage doesn't. An item that would do nothing can't be started.
| Tar Patch | Adds a little armor, quickly |
| Cork Vest | Adds a lot of armor |
### Loot
Loot is rolled once per match from the seed, when the match places it, so the same seed
always gives the same loot and nothing depends on who gets somewhere first. Every loot
marker at a point of interest holds either a **sea chest** or **floor loot**. Chests are
likelier in exposed, high places (shrines, lighthouses) than in hamlets, and their
weapons roll their tier twice and keep the better one. A chest always holds a weapon
with its ammunition, a consumable and a spare ammunition pickup. Interact opens a chest
in reach and spills what it holds; a pickup that is nearer is taken first.
**Washed-up crates** on the beaches each hold one roll of their own table, spilled when
the crate is broken by any means.
Tables live in `LOOT_SOURCES`: per location, the chance of a chest, how many floor rolls,
weights for weapon, consumable, ammunition or nothing, and tier weights. Within a
category, rarer items are picked less often (`LOOT_RARITY_WEIGHTS`). If a match's rolls
leave fewer weapons at points of interest than `LOOT_MIN_POI_WEAPONS` (one per player in
a full lobby), extra weapon rolls are added to floor spots, so no match is starved. The
loot test checks all of this over 1,000 seeds.
A player has `PLAYER_MAX_HEALTH` health, up to `PLAYER_MAX_ARMOR` armor, which takes
damage first, and `INVENTORY_SLOTS` slots. The top `HEAD_HEIGHT` of the body takes
each weapon's headshot multiplier.
+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
+6 -1
View File
@@ -10,7 +10,12 @@ func _run(match_seed: int, players: int, bots: int, ticks: int) -> ServerLoop:
func test_creates_players_then_bots() -> void:
var loop: ServerLoop = ServerLoop.new(1, 2, 3)
assert_eq(loop.sim.entities.count(), 5)
var players: int = 0
for entity: SimEntity in loop.sim.entities.entities():
if entity.archetype == SimEntity.ARCHETYPE_PLAYER:
players += 1
assert_eq(players, 5)
assert_true(loop.sim.pickups.size() > 0, "the match's floor loot was placed")
assert_eq(loop.player_ids, [1, 2, 3, 4, 5] as Array[int])
assert_eq(loop.bots.size(), 3)
assert_eq(loop.bots[0].player_id, 3)
+313
View File
@@ -0,0 +1,313 @@
extends TestCase
## Loot from issue B9: seeded floor loot and sea chests at loot markers, crates that
## spill when broken, tables by location and tier, and a statistics run over 1,000 seeds.
## Islands whose markers and crates the statistics run rolls loot over. Generating a
## whole island takes most of a second, so 1,000 loot seeds share these four islands:
## loot seed N uses island ISLAND_SEEDS[N % 4].
const ISLAND_SEEDS: Array[int] = [1, 2, 3, 4]
const STAT_SEEDS: int = 1000
const FEET: Vector3 = Vector3(100.0, 0.0, 100.0)
static var _surveys: Array[Dictionary] = []
func _press(sim: Simulation, buttons: int) -> void:
var player: SimEntity = sim.entities.find(1)
sim.submit_command(1, PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0, buttons, player.selected))
sim.step()
func _interact(sim: Simulation) -> void:
_press(sim, PlayerCommand.BUTTON_INTERACT)
_press(sim, 0)
## A flat world with one player at FEET and one chest `offset` from the feet holding a
## carbine and some cartridges.
func _chest_world(offset: Vector3) -> Simulation:
var sim: Simulation = Simulation.new(5, SimGround.flat())
sim.add_player()
sim.entities.find(1).position = FEET
sim.loot.chest_positions.append(FEET + offset)
sim.loot.chest_sources.append("hamlet")
sim.loot.chest_contents.append([
PackedInt32Array([ItemCatalog.code_of("dock_carbine"), 1, -1, 2]),
PackedInt32Array([ItemCatalog.code_of("cartridges"), 30, -1, 0]),
])
sim.loot.chest_opened.append(0)
return sim
## Markers and crate spill points of each statistics island, generated once.
func _islands() -> Array[Dictionary]:
if _surveys.is_empty():
for seed_value: int in ISLAND_SEEDS:
var island: Island = Island.generate(seed_value)
var pois: PoiSet = PoiSet.generate(island)
var props: PropSet = PropSet.generate(island, pois)
_surveys.append({"markers": pois.loot_markers(), "crates": Simulation.crate_spill_points(props)})
return _surveys
func _is_weapon(stack: PackedInt32Array) -> bool:
return ItemCatalog.get_def(stack[0]).kind == ItemDef.WEAPON
func test_tables_cover_every_location_category_and_tier() -> void:
for kind: String in Tuning.POI_KINDS:
assert_true(Tuning.LOOT_SOURCES.has(kind), "%s has a loot table" % kind)
assert_true(Tuning.LOOT_SOURCES.has(LootSet.CRATE_KIND), "crates have a loot table")
for source: String in Tuning.LOOT_SOURCES:
var table: Dictionary = Tuning.LOOT_SOURCES[source]
for category: String in LootSet.CATEGORIES:
assert_true(int(table[category]) >= 0, "%s %s weight" % [source, category])
assert_true(int(table["weapon"]) > 0, "%s can hold weapons" % source)
assert_eq(table["tiers"].size(), Tuning.WEAPON_TIERS.size(), "%s has a weight per tier" % source)
assert_true(int(table["rolls"]) >= 1)
for id: String in Tuning.ITEMS:
var count: int = int(Tuning.ITEMS[id]["loot"])
assert_true(count >= 1 and count <= int(Tuning.ITEMS[id]["stack"]), "%s loot count fits a stack" % id)
for id: String in LootSet.loot_weapons():
assert_true(int(LootSet.loot_weapons()[id]["rarity"]) < Tuning.LOOT_RARITY_WEIGHTS.size(), "%s rarity has a weight" % id)
func test_loot_is_deterministic_for_a_seed() -> void:
var a: Simulation = Simulation.new(21)
var b: Simulation = Simulation.new(21)
a.place_loot()
b.place_loot()
assert_true(a.pickups.size() > 0, "floor loot was placed")
assert_true(a.loot.chest_positions.size() > 0, "chests were placed")
assert_eq(a.pickups.size(), b.pickups.size())
for index: int in a.pickups.size():
var pa: SimEntity = a.entities.find(a.pickups[index])
var pb: SimEntity = b.entities.find(b.pickups[index])
assert_eq([pa.item, pa.item_count, pa.item_rounds, pa.item_tier], [pb.item, pb.item_count, pb.item_rounds, pb.item_tier])
assert_eq(pa.position, pb.position)
assert_eq(a.loot.chest_contents, b.loot.chest_contents)
assert_eq(a.loot.crate_contents, b.loot.crate_contents)
assert_eq(a.state_hash(), b.state_hash())
# Placing twice changes nothing.
var before: String = a.state_hash()
a.place_loot()
assert_eq(a.state_hash(), before, "loot is placed once")
func test_different_seeds_roll_different_loot_on_the_same_markers() -> void:
var survey: Dictionary = _islands()[0]
var first: LootSet = LootSet.plan(SimRng.new(1).stream("loot"), survey["markers"], survey["crates"])
var again: LootSet = LootSet.plan(SimRng.new(1).stream("loot"), survey["markers"], survey["crates"])
var other: LootSet = LootSet.plan(SimRng.new(2).stream("loot"), survey["markers"], survey["crates"])
assert_eq(first.chest_contents, again.chest_contents)
assert_eq(first.floor_spots, again.floor_spots)
assert_true(first.floor_spots != other.floor_spots or first.chest_contents != other.chest_contents, "a different seed changes the loot")
func test_floor_loot_stands_at_its_markers() -> void:
var sim: Simulation = Simulation.new(3)
sim.place_loot()
var placed: int = 0
for spot: Dictionary in sim.loot.floor_spots:
placed += spot["stacks"].size()
assert_eq(sim.pickups.size(), placed, "every floor stack became a pickup")
for pickup_id: int in sim.pickups:
var pickup: SimEntity = sim.entities.find(pickup_id)
var nearest: float = INF
for spot: Dictionary in sim.loot.floor_spots:
nearest = minf(nearest, Vector2(pickup.position.x, pickup.position.z).distance_to(Vector2(spot["position"].x, spot["position"].z)))
assert_true(nearest <= Tuning.LOOT_SCATTER_METRES + 0.01, "pickup %d lies at its marker" % pickup_id)
var under: float = sim.ground.support_height(pickup.position.x, pickup.position.z, pickup.position.y + 0.1)
assert_near(pickup.position.y, under, 0.01, "pickup %d rests on a floor" % pickup_id)
func test_chests_hold_a_weapon_with_its_ammunition() -> void:
var survey: Dictionary = _islands()[1]
var loot: LootSet = LootSet.plan(SimRng.new(9).stream("loot"), survey["markers"], survey["crates"])
assert_true(loot.chest_contents.size() > 0)
for contents: Array in loot.chest_contents:
var weapons: int = 0
var consumables: int = 0
for stack: PackedInt32Array in contents:
var def: ItemDef = ItemCatalog.get_def(stack[0])
assert_not_null(def)
assert_true(stack[1] >= 1)
if def.kind == ItemDef.WEAPON:
weapons += 1
if def.ammo_code >= 0:
var has_ammo: bool = false
for other: PackedInt32Array in contents:
has_ammo = has_ammo or other[0] == def.ammo_code
assert_true(has_ammo, "%s comes with its ammunition" % def.id)
elif def.kind == ItemDef.CONSUMABLE:
consumables += 1
assert_eq(weapons, Tuning.LOOT_CHEST_WEAPONS)
assert_eq(consumables, Tuning.LOOT_CHEST_CONSUMABLES)
func test_interact_opens_a_chest_once_and_spills_it() -> void:
var sim: Simulation = _chest_world(Vector3(1.0, 0.0, 0.0))
_interact(sim)
assert_eq(sim.loot.chest_opened[0], 1, "the chest opened")
assert_eq(sim.pickups.size(), 2, "its two stacks spilled")
assert_eq(sim.entities.find(1).slot_items[0], Inventory.EMPTY, "opening doesn't also pick up")
# The next press picks up instead of opening again.
_interact(sim)
assert_eq(sim.loot.chest_opened.count(1), 1)
var player: SimEntity = sim.entities.find(1)
assert_true(player.slot_items[0] != Inventory.EMPTY or player.ammo[Inventory.ammo_index(ItemCatalog.code_of("cartridges"))] > 0, "a spilled stack was picked up")
func test_chest_out_of_reach_stays_shut() -> void:
var sim: Simulation = _chest_world(Vector3(Tuning.CHEST_RANGE + 0.5, 0.0, 0.0))
_interact(sim)
assert_eq(sim.loot.chest_opened[0], 0)
assert_eq(sim.pickups.size(), 0)
func test_a_nearer_pickup_is_taken_before_the_chest_is_opened() -> void:
var sim: Simulation = _chest_world(Vector3(2.0, 0.0, 0.0))
Inventory.spawn_pickup(sim, FEET + Vector3(0.5, 0.0, 0.0), ItemCatalog.code_of("tar_patch"), 2)
_interact(sim)
assert_eq(sim.loot.chest_opened[0], 0, "the nearer pickup wins")
assert_eq(Inventory.count_of(sim.entities.find(1), ItemCatalog.code_of("tar_patch")), 2)
_interact(sim)
assert_eq(sim.loot.chest_opened[0], 1, "then the chest opens")
func test_opening_a_chest_changes_the_state_hash() -> void:
var a: Simulation = _chest_world(Vector3(1.0, 0.0, 0.0))
var b: Simulation = _chest_world(Vector3(1.0, 0.0, 0.0))
_press(a, 0)
_press(b, 0)
assert_eq(a.state_hash(), b.state_hash())
_interact(a)
_press(b, 0)
_press(b, 0)
assert_ne(a.state_hash(), b.state_hash())
func test_a_broken_crate_spills_its_loot_where_it_stood() -> void:
var sim: Simulation = Simulation.new(4)
sim.place_loot()
var crate: int = -1
for prop: int in sim.loot.crate_contents:
if not sim.loot.crate_contents[prop].is_empty():
crate = prop
break
assert_true(crate >= 0, "some crate holds loot")
var stacks: int = sim.loot.crate_contents[crate].size()
var before: int = sim.pickups.size()
assert_true(sim.damage_prop(crate, 100000))
sim.step()
assert_eq(sim.pickups.size(), before + stacks, "the crate spilled")
assert_false(sim.loot.crate_contents.has(crate))
var spilled: bool = false
for event: Dictionary in sim.events:
spilled = spilled or (event["type"] == "crate_spilled" and event["prop"] == crate)
assert_true(spilled, "a crate_spilled event was raised")
var box: AABB = sim.props.boxes[crate]
var newest: SimEntity = sim.entities.find(sim.pickups[sim.pickups.size() - 1])
assert_true(Vector2(newest.position.x, newest.position.z).distance_to(Vector2(box.get_center().x, box.get_center().z)) <= Tuning.LOOT_SCATTER_METRES + 0.01)
sim.step()
assert_eq(sim.pickups.size(), before + stacks, "a crate spills once")
## The statistics run from the issue: 1,000 loot seeds, each over one of four real
## islands. It checks the tier distribution against the tables, that better places
## give better tiers, and that every match has a weapon for every player.
func test_statistics_over_1000_seeds() -> void:
var islands: Array[Dictionary] = _islands()
var tier_counts: PackedInt32Array = PackedInt32Array()
tier_counts.resize(Tuning.WEAPON_TIERS.size())
var expected: PackedFloat64Array = PackedFloat64Array()
expected.resize(Tuning.WEAPON_TIERS.size())
var shrine_tiers: Vector2 = Vector2.ZERO
var hamlet_tiers: Vector2 = Vector2.ZERO
var fewest_weapons: int = 1 << 30
var fewest_poi_weapons: int = 1 << 30
var fewest_weapon_sites: int = 1 << 30
var short_matches: int = 0
var topped_up_matches: int = 0
var total_weapons: int = 0
for seed_value: int in range(1, STAT_SEEDS + 1):
var survey: Dictionary = islands[seed_value % islands.size()]
var loot: LootSet = LootSet.plan(SimRng.new(seed_value).stream("loot"), survey["markers"], survey["crates"])
var poi_weapons: int = 0
var sites: Dictionary = {}
var groups: Array[Array] = []
for spot: Dictionary in loot.floor_spots:
groups.append([spot["source"], spot["stacks"], spot["position"], 1])
for index: int in loot.chest_contents.size():
groups.append([loot.chest_sources[index], loot.chest_contents[index], loot.chest_positions[index], Tuning.LOOT_CHEST_TIER_ROLLS])
for group: Array in groups:
for stack: PackedInt32Array in group[1]:
if not _is_weapon(stack):
continue
poi_weapons += 1
sites[group[2]] = true
tier_counts[stack[3]] += 1
_add_expected(expected, group[0], group[3])
if group[0] == "shrine":
shrine_tiers += Vector2(stack[3], 1)
elif group[0] == "hamlet":
hamlet_tiers += Vector2(stack[3], 1)
var crate_weapons: int = 0
for prop: int in loot.crate_contents:
for stack: PackedInt32Array in loot.crate_contents[prop]:
if _is_weapon(stack):
crate_weapons += 1
tier_counts[stack[3]] += 1
_add_expected(expected, LootSet.CRATE_KIND, 1)
var weapons: int = poi_weapons + crate_weapons
total_weapons += weapons
fewest_weapons = mini(fewest_weapons, weapons)
fewest_poi_weapons = mini(fewest_poi_weapons, poi_weapons)
fewest_weapon_sites = mini(fewest_weapon_sites, sites.size())
if poi_weapons < Tuning.SOLO_PLAYERS:
short_matches += 1
for spot: Dictionary in loot.floor_spots:
if spot.has("topped_up"):
topped_up_matches += 1
break
# Tier distribution: each tier's share within two percentage points of what the
# tables predict, and rarer the better it is.
var counted: int = 0
for count: int in tier_counts:
counted += count
for tier: int in tier_counts.size():
var share: float = float(tier_counts[tier]) / counted
var predicted: float = expected[tier] / counted
assert_near(share, predicted, 0.02, "tier %s share" % Tuning.WEAPON_TIERS[tier]["name"])
assert_true(tier_counts[tier] > 0, "tier %d appears" % tier)
if tier > 0:
assert_true(tier_counts[tier] < tier_counts[tier - 1], "tier %d is rarer than tier %d" % [tier, tier - 1])
assert_true(shrine_tiers.x / shrine_tiers.y > hamlet_tiers.x / hamlet_tiers.y + 0.5, "shrines hold better weapons than hamlets")
# Every player can find a weapon: points of interest alone hold one per player in a
# full lobby in every match (topped up when the rolls fall short, which should be
# rare), and counting crates there are at least a quarter more. Weapons are spread
# over at least eight places.
assert_eq(short_matches, 0, "matches whose POIs hold fewer weapons than players")
assert_true(fewest_poi_weapons >= Tuning.SOLO_PLAYERS, "fewest POI weapons: %d" % fewest_poi_weapons)
assert_true(fewest_weapons >= ceili(Tuning.SOLO_PLAYERS * 1.25), "fewest weapons in a match: %d" % fewest_weapons)
assert_true(topped_up_matches <= STAT_SEEDS / 10, "matches that needed topping up: %d" % topped_up_matches)
assert_true(fewest_weapon_sites >= 8, "fewest places with a weapon: %d" % fewest_weapon_sites)
print("loot stats: weapons per match mean %.1f, min %d; POI min %d; topped up %d; tiers %s" % [float(total_weapons) / STAT_SEEDS, fewest_weapons, fewest_poi_weapons, topped_up_matches, tier_counts])
## Adds one weapon's expected tier probabilities: the best of `rolls` rolls on the
## source's weights.
func _add_expected(expected: PackedFloat64Array, source: String, rolls: int) -> void:
var weights: Array = Tuning.LOOT_SOURCES[source]["tiers"]
var total: float = 0.0
for weight: int in weights:
total += weight
var below: float = 0.0
for tier: int in weights.size():
var at_most: float = pow((below + weights[tier]) / total, rolls)
var under: float = pow(below / total, rolls)
expected[tier] += at_most - under
below += weights[tier]
+1
View File
@@ -0,0 +1 @@
uid://br6rnqgyq2f67