M8: Complete offline match

`make match` plays one whole match from the lobby to the results and back to the
lobby: one scripted player and 23 bots on a local server, with no script errors.

- CommandLog records the seed, the rules and every command the server is given.
  MatchReplay plays a log again with nobody thinking and ends on the same state
  hash; `make match` saves the log, reads it back and checks that.
- ServerLoop.submit() is now the one way commands reach the simulation, so a
  recording server sees them all.
- ScriptedPlayer plays a human seat: it drops, loots, fights and flees as a bot
  does, and also cuts driftwood and builds a breakwater and a wall.
- Bots draw randomness from their own per-bot generators, not the simulation's
  streams. A bot thinking no longer changes the simulation's state, which a
  replay without bots needs.
- MatchView and EntityView draw a match from one Simulation: terrain, sea,
  points of interest, props, pieces, players, the barge, items and chests, with
  stand-in shapes for the art pass to replace.
- `make match-captures` renders eight stages of the recorded match.

Closes #31

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 05:35:32 -05:00
co-authored by Claude Opus 5.5
parent 8cf164d562
commit 1d6a24ab64
38 changed files with 1633 additions and 15 deletions
+44
View File
@@ -0,0 +1,44 @@
extends TestCase
## The scripted player from issue M8: a stand-in for a person, which also harvests and
## builds, things bots don't do yet.
func test_a_scripted_seat_sends_commands_like_anyone_else() -> void:
var loop: ServerLoop = ServerLoop.new(99, 1, 1)
loop.play_humans_by_script()
assert_eq(loop.scripted.size(), 1)
assert_eq(loop.scripted[0].player_id, 1)
assert_eq(loop.bots.size(), 1)
for _index: int in Tuning.TICK_RATE_HZ * 24:
loop.run_tick()
assert_ne(loop.sim.entities.find(1).drop_state, Drop.ABOARD, "the scripted player leapt from the barge")
func test_harvests_driftwood_and_builds_with_it() -> void:
# Seed 2 is the match `make match` plays: the player lands, finds a weapon, cuts
# driftwood and puts up a breakwater and a wall about a minute in.
var loop: ServerLoop = ServerLoop.new(2, 1, 23)
loop.play_humans_by_script()
var player: ScriptedPlayer = loop.scripted[0]
var placed: int = 0
var harvests: int = 0
while loop.ticks < 2400 and player.step != ScriptedPlayer.DONE:
loop.run_tick()
for event: Dictionary in loop.sim.events:
if event["type"] == "piece_placed" and event["player"] == player.player_id:
placed += 1
elif event["type"] == "harvest" and event["player"] == player.player_id:
harvests += 1
assert_eq(player.step, ScriptedPlayer.DONE)
assert_true(harvests >= 3, "swung at props %d times" % harvests)
assert_true(player.harvested >= ScriptedPlayer.WANTED_DRIFTWOOD, "harvested %d" % player.harvested)
assert_eq(player.built, 2)
assert_eq(placed, 2)
var kinds: Array[int] = []
for piece: StructureSet.Piece in loop.sim.structures.pieces.values():
if piece.owner == player.player_id:
kinds.append(piece.kind)
kinds.sort()
assert_eq(kinds, [StructureSet.WALL, StructureSet.BREAKWATER] as Array[int])
assert_false(loop.sim.entities.find(player.player_id).eliminated)
+1
View File
@@ -0,0 +1 @@
uid://cci7ssoaiiyt8
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"]
[node name="CaptureMatch" type="Node3D"]
script = ExtResource("1")
stage = "barge"
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"]
[node name="CaptureMatch" type="Node3D"]
script = ExtResource("1")
stage = "built"
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"]
[node name="CaptureMatch" type="Node3D"]
script = ExtResource("1")
stage = "final"
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"]
[node name="CaptureMatch" type="Node3D"]
script = ExtResource("1")
stage = "glide"
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"]
[node name="CaptureMatch" type="Node3D"]
script = ExtResource("1")
stage = "landed"
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"]
[node name="CaptureMatch" type="Node3D"]
script = ExtResource("1")
stage = "lobby"
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"]
[node name="CaptureMatch" type="Node3D"]
script = ExtResource("1")
stage = "results"
+149
View File
@@ -0,0 +1,149 @@
## Capture scenario for a whole match. It replays the command log `make match` saved
## to the moment `stage` names, draws that moment with the client's MatchView, and
## prints what it shows as a caption (Godot's default font; this is a test caption,
## not the game's HUD).
##
## Stages: lobby, barge, glide, landed, built, final, tide (the island just before the
## end, from where the lobby saw it), results.
extends Node3D
const TICKS: int = Tuning.TICK_RATE_HZ
## The scripted player's handle.
const PLAYER: int = 1
@export var log_path: String = "res://build/match/match.tclog"
@export var stage: String = "lobby"
var _replay: MatchReplay
var _view: MatchView
func _ready() -> void:
var commands: CommandLog = CommandLog.load_from(log_path)
if commands == null:
push_error("match capture: no usable command log at %s; run `make match` first" % log_path)
return
_replay = MatchReplay.new(commands)
var flow: Match = _replay.flow
var last: int = commands.final_tick
match stage:
"lobby":
pass
"barge":
_replay.run_until(func() -> bool: return flow.in_match() and flow.sim.tick >= 2 * TICKS)
"glide":
_replay.run_until(func() -> bool: return _player() != null and _player().drop_state == Drop.GLIDING)
_run_ticks(TICKS)
"landed":
_replay.run_until(func() -> bool: return _player() != null and _player().drop_state == Drop.NONE and flow.in_match())
_run_ticks(4 * TICKS)
"built":
_replay.run_until(func() -> bool: return flow.sim.structures.count() >= 2)
_run_ticks(3 * TICKS)
"tide":
_replay.run_until(func() -> bool: return flow.in_match() and flow.sim.tick >= last - 2 * TICKS)
"final":
_replay.run_until(func() -> bool: return flow.in_match() and flow.sim.tick > 10 * TICKS and flow.alive().size() <= 3)
"results":
_replay.run_to_end()
_:
push_error("match capture: unknown stage '%s'" % stage)
return
var sim: Simulation = flow.sim
var player_id: int = int(flow.entity_of.get(PLAYER, 0))
_view = MatchView.new()
_view.setup(sim, player_id)
add_child(_view)
var watched: int = _watched()
var who: String = "nobody"
if stage == "lobby" or stage == "tide":
_view.overview()
who = "the island"
elif stage == "barge":
var along: Vector3 = (sim.drop.finish - sim.drop.start).normalized()
var at: Vector3 = sim.drop.barge_position(sim.tick)
_view.look_from(at - along * 22.0 + Vector3(0.0, 9.0, 0.0) + along.cross(Vector3.UP) * 9.0, at + along * 40.0 - Vector3(0.0, 22.0, 0.0))
who = "the barge"
elif watched != 0:
var entity: SimEntity = sim.entities.find(flow.entity_of[watched])
var airborne: bool = entity.drop_state != Drop.NONE
if stage == "built" and sim.structures.count() > 0:
var piece: StructureSet.Piece = sim.structures.pieces.values()[0]
_view.frame(entity.id, 7.0, 2.8, piece.boxes[0].get_center())
elif stage == "results":
_view.frame(entity.id)
else:
_view.follow(entity.id, deg_to_rad(-22.0) if airborne else deg_to_rad(-9.0))
who = "the player" if watched == PLAYER else "bot %d" % -watched
else:
_view.overview()
_view.settle()
_caption(_describe(who))
func _player() -> SimEntity:
var flow: Match = _replay.flow
if not flow.entity_of.has(PLAYER):
return null
return flow.sim.entities.find(flow.entity_of[PLAYER])
func _run_ticks(count: int) -> void:
for _index: int in count:
if not _replay.step():
return
## The handle the camera follows: the player while they stand, then whoever they're
## spectating, then a winner, then anyone still standing. 0 for nobody.
func _watched() -> int:
var flow: Match = _replay.flow
var living: Array[int] = flow.alive()
if living.has(PLAYER):
return PLAYER
var target: int = flow.spectate_target(PLAYER)
if target != 0 and flow.entity_of.has(target):
return target
if not flow.winners.is_empty():
return flow.winners[0]
return living[0] if not living.is_empty() else 0
func _describe(who: String) -> String:
var flow: Match = _replay.flow
var sim: Simulation = flow.sim
var lines: Array[String] = []
lines.append("%s · %s · seed %d" % [stage.to_upper(), flow.phase_name(), _replay.commands.session_seed])
if flow.phase == Match.LOBBY or flow.phase == Match.COUNTDOWN:
lines.append("%d waiting · the match starts in %d s" % [flow.participants.size(), (flow.rules.lobby_ticks + flow.rules.countdown_ticks) / TICKS])
return "\n".join(lines)
lines.append("%d:%02d · %d of %d standing · sea %.1f m · tide phase %d" % [
sim.tick / TICKS / 60, sim.tick / TICKS % 60, flow.alive().size(), flow.summary().size(), sim.sea_level,
sim.tide.phase_at(sim.tick) + 1 if sim.tide != null else 0])
var me: SimEntity = _player()
if me != null:
lines.append("player: health %d · driftwood %d · %d pieces built · watching %s" % [
me.health, me.materials[Materials.DRIFTWOOD], sim.structures.count(), who])
if flow.phase == Match.RESULTS:
for row: Dictionary in flow.summary():
if row["place"] <= 3 or row["handle"] == PLAYER:
lines.append("#%d %s · %d eliminations · %d damage · %d s" % [
row["place"], "player" if row["handle"] == PLAYER else "bot %d" % -int(row["handle"]),
row["eliminations"], row["damage_dealt"], roundi(row["survival_seconds"])])
return "\n".join(lines)
func _caption(text: String) -> void:
var settings: LabelSettings = LabelSettings.new()
settings.font_size = 20
settings.font_color = Color(0.96, 0.94, 0.88)
settings.outline_size = 6
settings.outline_color = Color(0.08, 0.09, 0.1)
var label: Label = Label.new()
label.label_settings = settings
label.text = text
label.position = Vector2(18.0, 14.0)
var layer: CanvasLayer = CanvasLayer.new()
layer.add_child(label)
add_child(layer)
+1
View File
@@ -0,0 +1 @@
uid://ix887lku6smh
+7
View File
@@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"]
[node name="CaptureMatch" type="Node3D"]
script = ExtResource("1")
stage = "tide"
+81
View File
@@ -0,0 +1,81 @@
extends TestCase
## The client's picture of a match (issue M8): one view over a simulation, with every
## player, the barge, items and chests drawn from it.
func _match(bots: int = 3) -> ServerLoop:
return ServerLoop.new(2, 1, bots)
func test_draws_every_player_and_the_barge() -> void:
var loop: ServerLoop = _match()
var view: MatchView = MatchView.new()
view.setup(loop.sim, 1)
assert_eq(view.entities.figure_count(), 4)
assert_true(view.entities.barge().visible)
assert_true(view.entities.barge().position.distance_to(loop.sim.drop.barge_position(loop.sim.tick)) < 0.001)
# Passengers are spread over the deck, not stacked on one spot.
assert_true(view.entities.figure_of(1).position.distance_to(view.entities.figure_of(2).position) > 1.0)
assert_eq(view.entities.get_node("Pickups").multimesh.instance_count, loop.sim.pickups.size())
assert_eq(view.entities.get_node("Chests").multimesh.instance_count, loop.sim.loot.chest_positions.size())
assert_not_null(view.terrain)
view.free()
func test_follows_the_simulation() -> void:
var loop: ServerLoop = _match()
var view: MatchView = MatchView.new()
view.setup(loop.sim, 1)
while not loop.sim.drop.finished:
loop.run_tick()
loop.sim.entities.find(3).health = 0
loop.run_tick()
loop.sim.set_sea_level(6.5)
view.sync()
assert_false(view.entities.barge().visible, "the barge is gone once the drop is over")
assert_false(view.entities.figure_of(3).visible, "an eliminated player isn't drawn")
var bot: SimEntity = loop.sim.entities.find(2)
if not bot.eliminated:
assert_true(view.entities.figure_of(2).position.distance_to(bot.position) < 0.001)
assert_near(view.water.level, 6.5, 0.001)
assert_eq(view.entities.get_node("Pickups").multimesh.instance_count, loop.sim.pickups.size())
view.free()
func test_gliding_players_show_a_wing_sail() -> void:
var loop: ServerLoop = _match(1)
var view: MatchView = MatchView.new()
view.setup(loop.sim, 1)
var bot: SimEntity = loop.sim.entities.find(2)
assert_false((view.entities.figure_of(2).get_node("Sail") as Node3D).visible)
var guard: int = 0
while bot.drop_state != Drop.GLIDING and guard < 3000:
loop.run_tick()
guard += 1
view.sync()
assert_eq(bot.drop_state, Drop.GLIDING)
assert_true((view.entities.figure_of(2).get_node("Sail") as Node3D).visible)
view.free()
func test_the_camera_follows_a_player_and_frames_one() -> void:
var loop: ServerLoop = _match()
var view: MatchView = MatchView.new()
view.setup(loop.sim, 1)
while not loop.sim.drop.finished:
loop.run_tick()
view.sync()
var bot: SimEntity = loop.sim.entities.find(2)
assert_true(view.follow(2))
var gap: float = view.camera.position.distance_to(bot.position)
assert_true(gap > 0.5 and gap < 6.0, "the camera is %f m from the player" % gap)
assert_eq(view.terrain.focus, view.camera.position)
assert_true(view.frame(2))
var to_player: Vector3 = (bot.position + Vector3(0.0, 1.2, 0.0) - view.camera.position).normalized()
assert_true(to_player.dot(-view.camera.transform.basis.z) > 0.98, "the camera looks at the player")
assert_false(view.follow(999))
assert_false(view.frame(999))
view.overview()
assert_true(view.camera.position.y > 200.0)
view.free()
+1
View File
@@ -0,0 +1 @@
uid://0vi50i7uptfw
+105
View File
@@ -0,0 +1,105 @@
extends TestCase
## The command log from issue M8: what a match was given, kept so it can be replayed.
func _command(tick: int, buttons: int) -> PlayerCommand:
return PlayerCommand.from_input(tick, Vector2(0.5, -1.0), 1.25, -0.3, buttons, 2, 1)
func _log() -> CommandLog:
var rules: MatchRules = MatchRules.new()
rules.max_players = 6
rules.lobby_ticks = 12
rules.fill_with_bots = false
# A seed too large for a JSON number to hold exactly.
var commands: CommandLog = CommandLog.new(0x7FFFFFFFFFFFFFF1, 2, rules)
commands.record(0, 1, _command(0, PlayerCommand.BUTTON_JUMP))
commands.record(0, -3, _command(0, 0))
commands.record(7, 2, _command(9, PlayerCommand.BUTTON_FIRE | PlayerCommand.BUTTON_BUILD))
commands.final_tick = 8
commands.final_hash = "abc123"
commands.winners = [-3] as Array[int]
commands.notes = {"bots": 4}
return commands
func test_records_keep_their_tick_handle_and_command() -> void:
var commands: CommandLog = _log()
assert_eq(commands.count(), 3)
assert_eq(commands.at_tick_of(2), 7)
assert_eq(commands.handle_of(1), -3)
assert_eq(commands.handle_of(2), 2)
assert_eq(commands.command_of(2).encode(), _command(9, PlayerCommand.BUTTON_FIRE | PlayerCommand.BUTTON_BUILD).encode())
func test_round_trips_through_bytes() -> void:
var commands: CommandLog = _log()
var back: CommandLog = CommandLog.from_bytes(commands.to_bytes())
assert_not_null(back)
assert_eq(back.session_seed, 0x7FFFFFFFFFFFFFF1, "the whole 63-bit seed survives")
assert_eq(back.humans, 2)
assert_eq(back.rules.max_players, 6)
assert_eq(back.rules.lobby_ticks, 12)
assert_false(back.rules.fill_with_bots)
assert_eq(back.rules.countdown_ticks, commands.rules.countdown_ticks)
assert_eq(back.count(), 3)
for index: int in 3:
assert_eq(back.at_tick_of(index), commands.at_tick_of(index))
assert_eq(back.handle_of(index), commands.handle_of(index))
assert_eq(back.command_of(index).encode(), commands.command_of(index).encode())
assert_eq(back.final_tick, 8)
assert_eq(back.final_hash, "abc123")
assert_eq(back.winners, [-3] as Array[int])
assert_eq(int(back.notes["bots"]), 4)
func test_an_empty_log_round_trips() -> void:
var back: CommandLog = CommandLog.from_bytes(CommandLog.new(5, 0).to_bytes())
assert_not_null(back)
assert_eq(back.count(), 0)
assert_eq(back.session_seed, 5)
func test_saves_and_loads_a_file() -> void:
var path: String = "user://test_command_log/roundtrip.tclog"
assert_eq(_log().save(path), OK)
var back: CommandLog = CommandLog.load_from(path)
assert_not_null(back)
assert_eq(back.count(), 3)
DirAccess.remove_absolute(path)
assert_null(CommandLog.load_from(path), "a missing file is no log")
func test_bad_bytes_are_refused_without_errors() -> void:
var good: PackedByteArray = _log().to_bytes()
assert_null(CommandLog.from_bytes(PackedByteArray()))
assert_null(CommandLog.from_bytes("TWCL".to_ascii_buffer()))
var wrong_magic: PackedByteArray = good.duplicate()
wrong_magic[0] = 0x58
assert_null(CommandLog.from_bytes(wrong_magic))
# Cut short anywhere: never a log with records missing, never an engine error.
for size: int in range(0, good.size(), 7):
var cut: CommandLog = CommandLog.from_bytes(good.slice(0, size))
assert_true(cut == null or cut.count() == 3, "cut at %d bytes" % size)
# A header length that points past the end.
var long_header: PackedByteArray = good.duplicate()
long_header.encode_u32(4, 0x7FFFFFFF)
assert_null(CommandLog.from_bytes(long_header))
# A header that isn't JSON.
var head_size: int = good.decode_u32(4)
var not_json: PackedByteArray = good.duplicate()
for index: int in range(8, 8 + head_size):
not_json[index] = 0x7B
assert_null(CommandLog.from_bytes(not_json))
# A raw length that is huge, or not a whole number of records.
var huge: PackedByteArray = good.duplicate()
huge.encode_u32(8 + head_size, 0x7FFFFFF0)
assert_null(CommandLog.from_bytes(huge))
var ragged: PackedByteArray = good.duplicate()
ragged.encode_u32(8 + head_size, CommandLog.RECORD_SIZE * 3 + 1)
assert_null(CommandLog.from_bytes(ragged))
# Records that don't decompress to the promised length.
var short: PackedByteArray = good.duplicate()
short.encode_u32(8 + head_size, CommandLog.RECORD_SIZE * 40)
assert_null(CommandLog.from_bytes(short))
+1
View File
@@ -0,0 +1 @@
uid://clgykma7ju4if
+93
View File
@@ -0,0 +1,93 @@
extends TestCase
## Issue M8: a seed and a command log reproduce a match.
## Plays a small match to its end with one scripted player, recording it.
func _recorded(seed_value: int, bots: int, rules: MatchRules = null) -> ServerLoop:
var loop: ServerLoop = ServerLoop.new(seed_value, 1, bots, rules)
loop.play_humans_by_script()
loop.record_commands()
var limit: int = BotBatch.tick_limit() + 2000
while loop.ticks < limit and loop.recorder.final_hash.is_empty():
loop.run_tick()
return loop
func test_a_replay_ends_in_the_same_state() -> void:
var loop: ServerLoop = _recorded(41, 5)
var commands: CommandLog = loop.recorder
assert_false(commands.final_hash.is_empty(), "the match ended")
assert_eq(commands.winners.size(), 1)
assert_true(commands.count() >= commands.final_tick * 6, "every seat's command is logged every tick")
# Through bytes, as a saved file would be.
var replay: MatchReplay = MatchReplay.new(CommandLog.from_bytes(commands.to_bytes()))
assert_true(replay.run_to_end())
var verdict: Dictionary = replay.verify()
assert_true(verdict["ok"], "replay %s" % verdict)
assert_eq(replay.sim.tick, commands.final_tick)
assert_eq(replay.flow.winners, commands.winners)
assert_false(replay.step(), "a finished replay doesn't step")
func test_a_replay_runs_the_lobby_and_countdown_too() -> void:
var rules: MatchRules = MatchRules.new()
rules.max_players = 4
rules.lobby_ticks = 20
rules.countdown_ticks = 10
var loop: ServerLoop = _recorded(42, 3, rules)
var replay: MatchReplay = MatchReplay.new(loop.recorder)
assert_eq(replay.flow.phase, Match.LOBBY)
assert_true(replay.run_until(func() -> bool: return replay.flow.in_match()))
assert_eq(replay.ticks, 30)
assert_eq(replay.sim.tick, 0)
assert_true(replay.run_to_end())
assert_true(replay.verify()["ok"])
func test_a_replay_can_stop_partway() -> void:
var loop: ServerLoop = _recorded(41, 5)
var again: ServerLoop = ServerLoop.new(41, 1, 5)
again.play_humans_by_script()
for _index: int in 400:
again.run_tick()
var replay: MatchReplay = MatchReplay.new(loop.recorder)
assert_true(replay.run_until(func() -> bool: return replay.sim.tick >= 400))
assert_eq(replay.sim.tick, 400)
assert_eq(replay.sim.state_hash(), again.sim.state_hash(), "the replay passes through the same states")
func test_different_commands_give_a_different_match() -> void:
var loop: ServerLoop = _recorded(41, 5)
var silent: CommandLog = CommandLog.new(41, 1, loop.recorder.rules)
silent.final_tick = loop.recorder.final_tick
silent.final_hash = loop.recorder.final_hash
silent.winners = loop.recorder.winners
var replay: MatchReplay = MatchReplay.new(silent)
replay.run_to_end()
assert_false(replay.verify()["ok"], "nobody moving isn't the same match")
func test_bots_leave_the_simulations_random_streams_alone() -> void:
# A bot is a player: thinking must not change the simulation, or a replay with no
# bots thinking could never reach the same state.
var loop: ServerLoop = ServerLoop.new(9, 0, 8)
for _index: int in 900:
loop.run_tick()
assert_false(loop.sim.rng.stream_names().has("bots"))
func test_only_the_first_match_is_recorded() -> void:
var rules: MatchRules = ServerLoop.immediate_rules(0, 3)
rules.results_ticks = 2
var loop: ServerLoop = ServerLoop.new(5, 0, 3, rules)
var commands: CommandLog = loop.record_commands()
for bot: BotBrain in loop.bots.slice(1):
loop.sim.entities.find(bot.player_id).health = 0
loop.run_tick()
assert_false(commands.final_hash.is_empty())
var count: int = commands.count()
for _index: int in 30:
loop.run_tick()
assert_eq(loop.match_flow.matches_started, 2)
assert_eq(commands.count(), count, "the second match isn't added to the log")
+1
View File
@@ -0,0 +1 @@
uid://dt28p01xtfa12