From 2167900e45896e3f305ec24cdb5db342b27f8c51 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 03:01:09 -0500 Subject: [PATCH] M7: Duos and revive Two-player teams, enforced by the simulation: - Match puts every player on a team (SimEntity.team); Weapons.damage_player refuses damage between teammates from every weapon, the boathook and blasts. - A player whose health runs out with a teammate standing goes down instead of out: 60 health to bleed (one point every half second), crawling at 1 m/s, no firing, building, looting or items. Hits still take it; drowning too. - A standing teammate within 2 m holding interact for 6 s revives them with 30 health. Letting go or moving away starts it over. - Downed players are out when their health runs out again or when no teammate is left standing, credited to whoever downed them. A team falls together and shares its place; the tie-break puts standing ahead of downed. - Downs and revives go through Match events and the kill feed ("X knocked Y down"); the HUD says what to do while down. Wire: FLAG_DOWNED in the player record and the own block (flags now u16), so prediction crawls too. Protocol version 5. Bots: never target a teammate, land with their teammate, regroup when they stray past 30 m, crawl toward a standing teammate when down, go to revive a downed teammate within 60 m when not in a fight, and turn from a downed target to its standing teammate when it's in view. Options: --team-size=2 on the server, --duos offline, and Solo/Duos under Crew in the Practice menu. The figure has a downed crawl pose. Tests: test_duos (downing, crawl, revive, interrupted revive, bleed-out, finishing, team out, falling together, no friendly damage including kegs, drowning while down, hash, match placement and tie-break), bots as teammates, the downed flag on the wire, the feed, server and menu options. make duo-matches plays 10 bot duos matches. Closes #30 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 1 + Makefile | 9 +- README.md | 2 +- docs/GDD.md | 11 + docs/PLAY.md | 16 ++ docs/SERVER.md | 1 + packaging/deb/man/tidewall-server.6 | 4 + packaging/deb/man/tidewall.6 | 3 + src/app/app_shell.gd | 6 +- src/app/client_config.gd | 10 +- src/app/main.gd | 2 +- src/bots/bot_brain.gd | 113 +++++++++- src/bots/bot_world.gd | 3 + src/client/entities/entity_view.gd | 4 +- src/client/entities/figure_poses.gd | 16 ++ src/client/entities/figure_rig.gd | 5 +- src/client/game_settings.gd | 6 + src/client/hud/hud.gd | 13 ++ src/client/hud/hud_state.gd | 26 ++- src/net/client_mirror.gd | 1 + src/net/client_prediction.gd | 2 +- src/net/net_feed.gd | 11 +- src/net/net_protocol.gd | 2 +- src/net/net_snapshot.gd | 15 +- src/server/headless_server.gd | 3 +- src/server/local_server.gd | 10 + src/server/net_game.gd | 2 +- src/server/server_config.gd | 13 +- src/sim/explosives.gd | 4 +- src/sim/match.gd | 34 ++- src/sim/movement.gd | 9 + src/sim/sim_entity.gd | 8 + src/sim/simulation.gd | 146 +++++++++++- src/sim/tuning.gd | 19 ++ src/sim/weapons.gd | 6 +- src/ui/menus.gd | 11 +- test/bots/bot_batch.gd | 29 ++- test/bots/test_bot_brain.gd | 63 ++++++ test/capture/client_hud_downed.tscn | 7 + test/capture/client_scene.gd | 44 +++- test/capture/figure_scene.gd | 7 +- test/client/test_figure_rig.gd | 4 + test/client/test_hud.gd | 13 ++ test/net/test_net_snapshot.gd | 23 ++ test/server/test_server_config.gd | 10 + test/sim/test_duos.gd | 331 ++++++++++++++++++++++++++++ test/sim/test_duos.gd.uid | 1 + test/sim/test_match.gd | 5 +- test/sim/test_results.gd | 5 + test/ui/test_menus.gd | 8 +- tools/duo_matches.gd | 49 ++++ tools/duo_matches.gd.uid | 1 + tools/duo_matches.sh | 19 ++ 53 files changed, 1105 insertions(+), 61 deletions(-) create mode 100644 test/capture/client_hud_downed.tscn create mode 100644 test/sim/test_duos.gd create mode 100644 test/sim/test_duos.gd.uid create mode 100644 tools/duo_matches.gd create mode 100644 tools/duo_matches.gd.uid create mode 100755 tools/duo_matches.sh diff --git a/CLAUDE.md b/CLAUDE.md index c4bb8c1..df2fdfd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,6 +32,7 @@ continuity. | `tools/capture.sh ` | Renders the real client offscreen in a throwaway `tidewall-capture-*` Docker container (Xvfb, Mesa software rendering) and saves a PNG. Fails on a blank frame or a renderer fallback. | | `tools/godot.sh --script res://tools/island_map.gd -- --seed=N --out=res://captures/island.png` | Draws a top-down map of a seed's island, with a contour at each tide level. | | `make bot-matches` | Plays 20 bot-only matches (about ten minutes, under `nice`) and checks every one has a winner, under a tenth of deaths are drownings, and easy bots win less than an even share and take the fewest eliminations. `BOT_MATCH_SEEDS=5 BOT_MATCH_FIRST=40` changes the seeds; under 20 matches the difficulty checks are skipped. | +| `make duo-matches` | M7: plays 10 bot-only duos matches (12 teams of two, under `nice`, about 5 min) and checks each is won by one team, bots go down and revive each other, no hit between teammates did damage, and the worst p99 tick is within budget. `DUO_MATCH_SEEDS`, `DUO_MATCH_FIRST` change the seeds. | | `make bot-builds` | M6: plays 40 bot-only matches (about 12 minutes, under `nice`) in which every other bot gathers and builds, and compares them with the rest. Builders must build in over a third of the fights they begin with the materials for a wall, lose fewer of the fights they build in than of the rest, and place no worse on average; every match's p99 tick must be within budget. `BOT_BUILDS_SEEDS=5 BOT_BUILDS_FIRST=40` changes the seeds; under 20 matches only completion and timing are judged. Lines in `build/bot_builds/matches.jsonl`. See docs/BALANCE.md. | | `make balance` | H3: plays 200 bot-only matches in four processes under `nice` (about 15 min) and writes `build/balance/report.txt`: match length, players standing over time, causes of death, eliminations by weapon and by difficulty. Fails if the median match is outside 12 to 18 minutes or a weapon takes over 35% of eliminations (`BALANCE_*` in tuning). `BALANCE_MATCHES`, `BALANCE_FIRST`, `BALANCE_JOBS` scale it. See docs/BALANCE.md. | | `make match` | Plays one whole offline match, lobby to results: a scripted player and 23 bots on a local server (about 25 s). Saves the command log to `build/match/match.tclog`, replays it and checks the replay ends on the same state hash. `MATCH_SEED=N` changes the seed; the default, 29, is one where the scripted player also builds. | diff --git a/Makefile b/Makefile index 29af8c4..aeb9112 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ # Tidewall build entry points. Everything runs headless with the repo-local engine. GODOT := tools/godot.sh -.PHONY: qa-captures effects-captures app-icon deb deb-check bench dist dist-check build-captures poi-captures art figure figure-captures sea-captures models item-captures audio audio-check check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine balance bot-matches bot-builds match match-captures client-check client-captures hud-captures style-captures menu-captures chart-captures discovery-check fuzz stability soak soak-selfcheck server-package-check +.PHONY: qa-captures effects-captures app-icon deb deb-check bench dist dist-check build-captures poi-captures art figure figure-captures sea-captures models item-captures audio audio-check check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine balance bot-matches duo-matches bot-builds match match-captures client-check client-captures hud-captures style-captures menu-captures chart-captures discovery-check fuzz stability soak soak-selfcheck server-package-check ## A8: regenerates every sound in assets/audio/ from tools/audio/ (about 6 s). audio: import @@ -116,6 +116,12 @@ balance: import bot-matches: import @tools/bot_matches.sh +## M7: plays 10 bot-only duos matches (12 teams of two, under nice) and checks each is +## won by one team, bots go down and revive each other, teammates never hurt each other +## and the ticks keep within budget. DUO_MATCH_SEEDS and DUO_MATCH_FIRST change the seeds. +duo-matches: import + @tools/duo_matches.sh + ## M6: plays 40 bot-only matches in which every other bot gathers and builds (about 12 ## minutes, under nice) and checks the builders build in over a third of the fights they ## can afford to, lose fewer of the fights they build in than of the rest, and place no @@ -156,6 +162,7 @@ client-captures: import hud-captures: import @CAPTURE_SIZE=1280x720 tools/capture.sh client_hud captures/hud_720.png @CAPTURE_SIZE=1280x720 tools/capture.sh client_hud_build captures/hud_build_720.png + @CAPTURE_SIZE=1280x720 tools/capture.sh client_hud_downed captures/hud_downed_720.png @CAPTURE_SIZE=3840x2160 tools/capture.sh client_hud captures/hud_2160.png ## A10: every menu screen (captures/menu_*.png, about 5 min). Needs Docker. Look at them. diff --git a/README.md b/README.md index 8db6275..e1742ea 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ All of this is checked headless or with **software rendering in a container**. N ## Known limitations - **Untested on real hardware.** No real GPU, Wayland session or hybrid-graphics machine has run it yet ([docs/PLAY.md](docs/PLAY.md#tested-configurations)). -- **Solo only.** Duos and reviving ([#30](https://gitea.eom.dev/claude/tidewall/issues/30)) aren't in this release. +- **The 1.0.0 packages are solo only.** Duos with downs and revives ([#30](https://gitea.eom.dev/claude/tidewall/issues/30)) are on `main` since 1.0.0 was tagged: `--team-size=2` on a server, `--duos` or the Practice menu's Crew offline. Bots play as teammates and revive, but don't otherwise stick together. - Bots carry powder kegs but don't throw them ([#83](https://gitea.eom.dev/claude/tidewall/issues/83)). - Most bots fall early in a match ([#74](https://gitea.eom.dev/claude/tidewall/issues/74)). Bots build on `main` since 1.0.0 was tagged ([#29](https://gitea.eom.dev/claude/tidewall/issues/29)), but only cover walls, ramps and a last-stand ring of breakwaters, not forts. The 1.0.0 packages have bots that don't build. - **No gamepad support or tutorial** ([#53](https://gitea.eom.dev/claude/tidewall/issues/53), [#52](https://gitea.eom.dev/claude/tidewall/issues/52)). No character customization ([#43](https://gitea.eom.dev/claude/tidewall/issues/43)) or editing of placed pieces ([#18](https://gitea.eom.dev/claude/tidewall/issues/18)). diff --git a/docs/GDD.md b/docs/GDD.md index af46fd7..b794035 100644 --- a/docs/GDD.md +++ b/docs/GDD.md @@ -67,6 +67,17 @@ to heal instead of running when badly hurt, and build ramps up to someone on a c or a steep rise. At the last stand they ring their spot with breakwaters. They don't use powder kegs or the line thrower. Offline play is a local server filled with bots, the same game code as online play. A downed duo partner can be revived, within `REVIVE_SECONDS`. +In duos (M7) bots never target their teammate, crawl toward it when downed, and go to a +downed teammate within `BOT_REVIVE_METRES` to revive it when they aren't in a fight. + +**Duos rules (M7).** Teams are set by `Match` and held on each player +(`SimEntity.team`), so the simulation enforces them: `Weapons.damage_player` refuses +damage between teammates from every weapon, the boathook and blasts. A player whose +health runs out with a teammate standing goes down (`DOWNED_HEALTH`, bleeding one point +every `DOWNED_BLEED_INTERVAL_TICKS`, crawling at `DOWNED_CRAWL_SPEED`); a standing +teammate within `REVIVE_RANGE` holding interact for `REVIVE_SECONDS` brings them back +with `REVIVE_HEALTH`. Downed players are eliminated when their health runs out again or +when no teammate is left standing, credited to whoever downed them. ## The island diff --git a/docs/PLAY.md b/docs/PLAY.md index f1153c7..ace31ee 100644 --- a/docs/PLAY.md +++ b/docs/PLAY.md @@ -38,6 +38,7 @@ Replace `1.0.0` with the version you downloaded. The game opens on its main menu. - **Practice** plays offline against bots on an island of its own. No network needed. + Crew picks solo or duos, with a bot as your crewmate. - **Join a server** lists the servers it finds on your local network. Pick one, or type an address (`host` or `host:port`; the default port is 24650) for any other server. - **Settings** has Controls, Mouse, Graphics, Display and Audio tabs. @@ -46,6 +47,7 @@ You can also start straight into a match from a terminal: ./tidewall --offline # practice against 23 bots ./tidewall --offline --bots=5 --seed=42 # fewer bots, a chosen island + ./tidewall --offline --duos # duos, with the first bot as your crewmate ./tidewall --connect=192.0.2.7:24650 --name=Mara ./tidewall --headless --browse # print the LAN's servers, then quit ./tidewall --headless --browse --list=lists.example.org:24660 # and a list server's @@ -54,6 +56,20 @@ On a server, matches run back to back: a short lobby, a countdown, the drop, the and the results, then a new island. If you join during a match you wait in the lobby for the next one. Leaving during a match counts as being eliminated where you stood. +### Duos + +In duos you play in a crew of two, on a server started with `--team-size=2` or in +practice. Crewmates can't hurt each other, with any weapon or keg. + +- When your health runs out while your crewmate is still standing, you go **down** + instead of out. You crawl, slowly, and can't fire, build, loot or use anything. Your + health becomes 60 to bleed, one point every half second, and hits still take it. +- Your crewmate hauls you up by standing beside you (within 2 m) and holding **Pick + up** (E) for 6 seconds without a break. You get up with 30 health. +- You're out when you bleed out, when you're finished off, or when your crewmate goes + down or out too: a crew with nobody standing is eliminated, and both share its place. +- Drowning still takes a downed player, and faster than bleeding. + ## Controls Every key can be rebound in Settings → Controls. Mouse sensitivity and inversion are on diff --git a/docs/SERVER.md b/docs/SERVER.md index 97667f6..76a857a 100644 --- a/docs/SERVER.md +++ b/docs/SERVER.md @@ -49,6 +49,7 @@ server with exit code 2 instead of running the wrong match. | `port=N` | 24650 | UDP port for players. LAN discovery uses this port plus one. | | `bots=N` | 0 | Any number above 0 fills each match's empty places with bots. | | `bot-difficulty=` | `mixed` | `easy`, `normal`, `hard` or `mixed`. | +| `team-size=N` | 1 | 1 for solo, 2 for duos: players pair up in the order they join (bots fill in after), can't hurt their teammate, and go down instead of out while their teammate stands. | | `name=NAME` | `Tidewall server` | The name shown in server lists. | | `list=HOST[:PORT]` | none | Register with a list server, so people off your LAN can find you. Can be given more than once. | | `no-lan` | off | Don't answer LAN discovery. | diff --git a/packaging/deb/man/tidewall-server.6 b/packaging/deb/man/tidewall-server.6 index 6281b86..9889f8e 100644 --- a/packaging/deb/man/tidewall-server.6 +++ b/packaging/deb/man/tidewall-server.6 @@ -26,6 +26,10 @@ UDP port (default 24650). LAN discovery answers on the port plus one. .BI \-\-bots= n Fill each match's empty places with bots. .TP +.BI \-\-team\-size= n +1 for solo (the default), 2 for duos: pairs who can't hurt each other and go +down instead of out while their teammate stands. +.TP .BI \-\-name= name The name shown in server lists. .TP diff --git a/packaging/deb/man/tidewall.6 b/packaging/deb/man/tidewall.6 index 703b434..d58fc2c 100644 --- a/packaging/deb/man/tidewall.6 +++ b/packaging/deb/man/tidewall.6 @@ -30,6 +30,9 @@ The name to play under. .TP .B \-\-offline Start a practice match against bots at once. +.TP +.B \-\-duos +With \-\-offline, play duos with the first bot as your crewmate. .SH FILES .TP .I ~/.local/share/godot/app_userdata/Tidewall/ diff --git a/src/app/app_shell.gd b/src/app/app_shell.gd index c725866..6ebc1f3 100644 --- a/src/app/app_shell.gd +++ b/src/app/app_shell.gd @@ -62,11 +62,11 @@ func _ready() -> void: menus.show_screen("main", false) -## Starts an offline match against bots. -func start_practice(bots: int, difficulty: int) -> void: +## Starts an offline match against bots, solo or in duos (`team_size` 2, M7). +func start_practice(bots: int, difficulty: int, team_size: int = 1) -> void: var match_seed: int = int(Time.get_unix_time_from_system() * 1000.0) & 0x7FFFFFFF var practice: ClientSession = ClientSession.new() - practice.play_offline(match_seed, bots, null, difficulty) + practice.play_offline(match_seed, bots, LocalServer.offline_rules(bots, team_size), difficulty) _begin(practice) diff --git a/src/app/client_config.gd b/src/app/client_config.gd index 62edc1a..95c087b 100644 --- a/src/app/client_config.gd +++ b/src/app/client_config.gd @@ -3,7 +3,7 @@ ## tidewall the main menu (with a window) ## tidewall --offline an offline match against bots ## tidewall --connect=HOST[:PORT] join a server -## options: --name=NAME --seed=N --bots=N (offline) --autoplay +## options: --name=NAME --seed=N --bots=N (offline) --duos (offline) --autoplay ## --client-seconds=N quit after N seconds, saying what happened ## tidewall --browse [--list=HOST[:PORT]]... [--lan-target=ADDRESS]... [--lan-port=N] ## print the servers found on the LAN and in list @@ -25,6 +25,8 @@ var player_name: String = DEFAULT_NAME var match_seed: int = 0 var has_seed: bool = false var bots: int = DEFAULT_BOTS +## Offline in duos (M7) with --duos: the player and the first bot are a team. +var team_size: int = 1 var autoplay: bool = false ## Quit after this many seconds; 0 runs until the window is closed. var seconds: float = 0.0 @@ -43,7 +45,7 @@ var errors: Array[String] = [] ## Every option parse() knows, by name. const OPTIONS: Array[String] = [ - "--offline", "--autoplay", "--browse", "--list", "--lan-port", "--lan-target", + "--offline", "--autoplay", "--duos", "--browse", "--list", "--lan-port", "--lan-target", "--connect", "--name", "--seed", "--bots", "--client-seconds", ] @@ -73,6 +75,8 @@ static func parse(args: PackedStringArray) -> ClientConfig: config.asked = true "--autoplay": config.autoplay = true + "--duos": + config.team_size = Tuning.DUO_TEAM_SIZE "--browse": config.asked = true config.browse = true @@ -120,6 +124,8 @@ static func parse(args: PackedStringArray) -> ClientConfig: _: if arg.begins_with("--"): config.errors.append("unknown option '%s'" % arg) + if config.team_size > 1 and not config.host.is_empty(): + config.errors.append("--duos is for an offline match; a server decides its own teams") if config.browse and not config.host.is_empty(): config.errors.append("--browse and --connect can't be used together") return config diff --git a/src/app/main.gd b/src/app/main.gd index 005d744..9cca1ff 100644 --- a/src/app/main.gd +++ b/src/app/main.gd @@ -55,7 +55,7 @@ func _ready() -> void: _session.input.autoplay = _config.autoplay if _config.host.is_empty(): var match_seed: int = _config.match_seed if _config.has_seed else int(Time.get_unix_time_from_system() * 1000.0) & 0x7FFFFFFF - _session.play_offline(match_seed, _config.bots) + _session.play_offline(match_seed, _config.bots, LocalServer.offline_rules(_config.bots, _config.team_size)) else: var error: Error = _session.connect_to(_config.host, _config.port, _config.player_name) if error != OK: diff --git a/src/bots/bot_brain.gd b/src/bots/bot_brain.gd index 29182c7..fed3765 100644 --- a/src/bots/bot_brain.gd +++ b/src/bots/bot_brain.gd @@ -178,6 +178,8 @@ func think(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand: return PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0) if me.drop_state != Drop.NONE: return _drop(sim, grid, world) + if me.downed: + return _crawl(sim, world, me) _count_building(world, me) _sense(sim, world, me) _check_tide(sim, world, me) @@ -205,6 +207,8 @@ func think(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand: and not _fleeing and not retreating and not covering and distance <= Tuning.BOT_BRAWL_METRES and provoked) var interact: bool = false var walk: bool = true + var patient: SimEntity = _patient(sim, world, me) if not me.swimming else null + var tending: bool = false # Where to go. _direct_on = false @@ -234,6 +238,14 @@ func think(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand: elif brawling: state = "brawl" _stop() + elif patient != null: + # A teammate is down (M7): get to them and hold interact until they're up. + state = "revive" + if me.position.distance_to(patient.position) <= Tuning.REVIVE_RANGE * 0.75: + _stop() + tending = true + else: + _go(patient.position, Tuning.REVIVE_RANGE * 0.5) elif target != null and armed: state = "chase" _go(_last_seen, 3.0) @@ -361,6 +373,14 @@ func think(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand: chosen_material = _piece_material if _piece_kind != StructureSet.RAMP: direction = Vector2.ZERO + if tending: + var to_patient: Vector2 = Vector2(patient.position.x - me.position.x, patient.position.z - me.position.z) + if to_patient.length() > 0.05: + yaw = atan2(to_patient.x, to_patient.y) + pitch = 0.0 + direction = Vector2.ZERO + buttons = PlayerCommand.BUTTON_INTERACT + chosen_material = 0 _track_fight(sim, world, me, buttons) var forward: Vector2 = Vector2(sin(yaw), cos(yaw)) var right: Vector2 = Vector2(-cos(yaw), sin(yaw)) @@ -368,6 +388,64 @@ func think(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand: return PlayerCommand.from_input(sim.tick, move, yaw, pitch, buttons, selection, chosen_material) +# Duos (M7) + +## The nearest standing teammate, or null. +func _standing_teammate(sim: Simulation, world: BotWorld, me: SimEntity) -> SimEntity: + if me == null or me.team < 0: + return null + var best: SimEntity = null + var best_gap: float = INF + for other_id: int in world.player_ids: + var other: SimEntity = sim.entities.find(other_id) + if not Simulation.is_standing(other) or not sim.are_teammates(me, other) or other.drop_state != Drop.NONE: + continue + var gap: float = me.position.distance_squared_to(other.position) + if gap < best_gap: + best = other + best_gap = gap + return best + + +## The nearest downed teammate within Tuning.BOT_REVIVE_METRES, or null. +func _patient(sim: Simulation, world: BotWorld, me: SimEntity) -> SimEntity: + var best: SimEntity = null + var best_gap: float = Tuning.BOT_REVIVE_METRES * Tuning.BOT_REVIVE_METRES + for other_id: int in world.player_ids: + var other: SimEntity = sim.entities.find(other_id) + if other == null or not other.downed or other.eliminated or not sim.are_teammates(me, other): + continue + var gap: float = me.position.distance_squared_to(other.position) + if gap <= best_gap: + best = other + best_gap = gap + return best + + +## Downed: crawl straight for the nearest standing teammate, and stop beside them. +func _crawl(sim: Simulation, world: BotWorld, me: SimEntity) -> PlayerCommand: + state = "downed" + _stop() + _forget_target() + var yaw: float = float(me.yaw) / PlayerCommand.YAW_STEPS * TAU + var move: Vector2 = Vector2.ZERO + var nearest: SimEntity = null + var nearest_gap: float = INF + for other_id: int in world.player_ids: + var other: SimEntity = sim.entities.find(other_id) + if not Simulation.is_standing(other) or not sim.are_teammates(me, other): + continue + var gap: float = me.position.distance_squared_to(other.position) + if gap < nearest_gap: + nearest = other + nearest_gap = gap + if nearest != null and nearest_gap > Tuning.REVIVE_RANGE * Tuning.REVIVE_RANGE * 0.25: + var to: Vector2 = Vector2(nearest.position.x - me.position.x, nearest.position.z - me.position.z) + yaw = atan2(to.x, to.y) + move = Vector2(0.0, 1.0) + return PlayerCommand.from_input(sim.tick, move, yaw, 0.0) + + # Movement goals func _go(goal: Vector3, radius: float) -> void: @@ -388,6 +466,13 @@ func _stop() -> void: ## Rides the barge to within reach of a loot marker near its route, then glides to it. func _drop(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand: state = "drop" + var rider: SimEntity = sim.entities.find(player_id) + if _landing < 0 and rider != null and rider.team >= 0 and world.team_landings.has(rider.team): + # Duos (M7): land with the teammate who already chose. + _landing = int(world.team_landings[rider.team]) + _marker = _landing + _marker_since = sim.tick + _go(world.markers[_landing], 2.0) if _landing < 0 and not world.markers.is_empty() and sim.drop != null: var rng: RandomNumberGenerator = nav.stream(sim) var a: Vector2 = Vector2(sim.drop.start.x, sim.drop.start.z) @@ -413,6 +498,8 @@ func _drop(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand: best_crowd = crowd _landing = pick world.landings.append(world.markers[_landing]) + if rider != null and rider.team >= 0: + world.team_landings[rider.team] = _landing _marker = _landing _marker_since = sim.tick _go(world.markers[_landing], 2.0) @@ -455,6 +542,18 @@ func _sense(sim: Simulation, world: BotWorld, me: SimEntity) -> void: elif tick - _last_seen_tick > roundi(Tuning.BOT_MEMORY_SECONDS * TICKS): _forget_target() target = null + if target != null and target.downed and target_visible: + # Duos (M7): a downed target can't shoot back, but its teammate can. Turn on the + # teammate if they're in view; otherwise finish the job. + for other_id: int in world.player_ids: + var other: SimEntity = sim.entities.find(other_id) + if Simulation.is_standing(other) and other.drop_state == Drop.NONE and sim.are_teammates(target, other) \ + and me.position.distance_to(other.position) <= minf(_sight, Tuning.BOT_ENGAGE_METRES) and _can_see(sim, world, me, other, false): + target_id = other.id + _acquired_tick = tick + _last_seen = other.position + _last_seen_tick = tick + return if target != null and target_visible: return # Look for someone new, nearest first, with a few sight lines at most. @@ -463,7 +562,7 @@ func _sense(sim: Simulation, world: BotWorld, me: SimEntity) -> void: 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: + if other == null or other.eliminated or other.drop_state != Drop.NONE or sim.are_teammates(me, other): continue # A bot picks out a new opponent only this close; one who shoots it first is # fought at any range it can see (H3). @@ -974,10 +1073,18 @@ func _hunt(sim: Simulation, world: BotWorld) -> void: if arrived and not _holding: _holding = true _hunt_until = sim.tick + roundi(Tuning.BOT_HOLD_SECONDS * TICKS) + var me: SimEntity = sim.entities.find(player_id) + var mate: SimEntity = _standing_teammate(sim, world, me) + var strayed: bool = mate != null and me.position.distance_to(mate.position) > Tuning.BOT_REGROUP_METRES + if strayed and (_holding or _hunt_goal.distance_to(mate.position) > Tuning.BOT_REGROUP_METRES * 0.5): + # Duos (M7): too far from the teammate to help them up; go back to them. + _holding = false + _hunt_until = sim.tick if (not _goal_set and not _holding) or sim.tick >= _hunt_until: var phase: int = sim.tide.phase_at(sim.tick) if sim.tide != null else 0 - var me: SimEntity = sim.entities.find(player_id) - _hunt_goal = world.random_safe_near(nav.stream(sim), phase, me.position, Tuning.BOT_ROAM_METRES) + var around: Vector3 = mate.position if strayed else me.position + var radius: float = Tuning.BOT_REGROUP_METRES * 0.3 if strayed else Tuning.BOT_ROAM_METRES + _hunt_goal = world.random_safe_near(nav.stream(sim), phase, around, radius) _hunt_until = sim.tick + 40 * TICKS _holding = false _go(_hunt_goal, 4.0) diff --git a/src/bots/bot_world.gd b/src/bots/bot_world.gd index 20ebb38..3d9905a 100644 --- a/src/bots/bot_world.gd +++ b/src/bots/bot_world.gd @@ -44,6 +44,9 @@ var phase_tops: Array[Vector3] = [] var walkable: PackedByteArray = PackedByteArray() ## Where bots have chosen to land this match, so later bots can spread out (H3). var landings: Array[Vector3] = [] +## Duos (M7): team -> the marker index its first bot chose to land at, so its +## teammate lands there too. +var team_landings: Dictionary = {} ## Victim entity ID -> attacker entity ID, for hits landed during the last tick. var attackers: Dictionary = {} ## Builder entity ID -> the kinds of the pieces it placed during the last tick (M6). diff --git a/src/client/entities/entity_view.gd b/src/client/entities/entity_view.gd index bb73425..27979e1 100644 --- a/src/client/entities/entity_view.gd +++ b/src/client/entities/entity_view.gd @@ -176,9 +176,9 @@ func hear(records: Array[Dictionary]) -> void: ## Puts the held item's model in the figure's hand; the figure points it where the -## player looks. Nothing is held aboard the barge, falling, gliding or swimming. +## player looks. Nothing is held aboard the barge, falling, gliding, swimming or down. func _hold(figure: FigureRig, entity: SimEntity) -> void: - var busy: bool = entity.drop_state != Drop.NONE or entity.swimming or entity.eliminated + var busy: bool = entity.drop_state != Drop.NONE or entity.swimming or entity.eliminated or entity.downed figure.hand().visible = not busy if busy: return diff --git a/src/client/entities/figure_poses.gd b/src/client/entities/figure_poses.gd index 65cacd8..8d9423e 100644 --- a/src/client/entities/figure_poses.gd +++ b/src/client/entities/figure_poses.gd @@ -231,6 +231,22 @@ static func _clips() -> Dictionary: [0.0, swim], [0.325, swim_pull], [0.65, mirror(swim)], [0.975, mirror(swim_pull)], ]] + # Downed in duos (M7): on hands and knees, head up, crawling a hand and knee at a time. + var downed: Dictionary = { + "hips": Vector3(78, 0, 0), "waist": Vector3(-4, 0, 0), "neck": Vector3(-52, 0, 0), + "shoulder_r": Vector3(-84, 0, -6), "elbow_r": Vector3(-8, 0, 0), + "shoulder_l": Vector3(-84, 0, 6), "elbow_l": Vector3(-8, 0, 0), + "hip_r": Vector3(-78, 0, -4), "knee_r": Vector3(92, 0, 0), + "hip_l": Vector3(-78, 0, 4), "knee_l": Vector3(92, 0, 0), "lift": Vector3(0, -0.5, 0), + } + var downed_reach: Dictionary = over(downed, { + "shoulder_r": Vector3(-104, 0, -6), "hip_l": Vector3(-64, 0, 4), "knee_l": Vector3(84, 0, 0), + "waist": Vector3(-4, 6, 0), + }) + clips["downed"] = [1.6, true, [ + [0.0, downed], [0.4, downed_reach], [0.8, downed], [1.2, mirror(downed_reach)], + ]] + # How the held item is carried (arms only). # Long things at the chest, the right hand at the grip and the left reaching # along to the fore-end. diff --git a/src/client/entities/figure_rig.gd b/src/client/entities/figure_rig.gd index e830b36..794d48e 100644 --- a/src/client/entities/figure_rig.gd +++ b/src/client/entities/figure_rig.gd @@ -55,7 +55,7 @@ const COLOURS: Dictionary = { } const COAT_SHADE: float = 0.28 ## The states of `move`, in input order. -const STATES: Array[String] = ["ground", "crouch", "air", "skydive", "glide", "swim", "aboard"] +const STATES: Array[String] = ["ground", "crouch", "air", "skydive", "glide", "swim", "aboard", "downed"] const HOLDS: Array[String] = ["long", "short", "carry"] const ACTIONS: Array[String] = ["fire_long", "fire_short", "swing", "throw", "build"] ## How long a figure must be off the ground before it's drawn in the air, so steps @@ -304,6 +304,9 @@ static func state_of(entity: SimEntity, airborne: bool) -> String: return "glide" if entity.swimming: return "swim" + if entity.downed: + # Duos (M7): down on hands and knees, crawling. + return "downed" if airborne: return "air" return "crouch" if entity.crouching else "ground" diff --git a/src/client/game_settings.gd b/src/client/game_settings.gd index bd239f5..84f48e8 100644 --- a/src/client/game_settings.gd +++ b/src/client/game_settings.gd @@ -71,6 +71,10 @@ var practice_bots: int = Tuning.SOLO_PLAYERS - 1: var practice_difficulty: int = -1: set(value): practice_difficulty = clampi(value, -1, Tuning.BOT_DIFFICULTIES.size() - 1) +## Practice solo (1) or in duos with a bot teammate (Tuning.DUO_TEAM_SIZE), M7. +var practice_team_size: int = 1: + set(value): + practice_team_size = clampi(value, 1, Tuning.DUO_TEAM_SIZE) func shadow_distance() -> float: @@ -118,6 +122,7 @@ func save(path: String = DEFAULT_PATH) -> Error: config.set_value("player", "last_server", last_server) config.set_value("practice", "bots", practice_bots) config.set_value("practice", "difficulty", practice_difficulty) + config.set_value("practice", "team_size", practice_team_size) return config.save(path) @@ -144,6 +149,7 @@ static func load_from(path: String = DEFAULT_PATH) -> GameSettings: settings.last_server = String(server_value).strip_edges().left(255) settings.practice_bots = _int(config, "practice", "bots", settings.practice_bots) settings.practice_difficulty = _int(config, "practice", "difficulty", settings.practice_difficulty) + settings.practice_team_size = _int(config, "practice", "team_size", settings.practice_team_size) return settings diff --git a/src/client/hud/hud.gd b/src/client/hud/hud.gd index 8a9e32f..70676df 100644 --- a/src/client/hud/hud.gd +++ b/src/client/hud/hud.gd @@ -14,6 +14,8 @@ const FONT_SMALL: int = 13 const FONT_BODY: int = 16 const FONT_TITLE: int = 22 const MARGIN: float = 18.0 +## Shown while downed in duos (M7). +const DOWN_TEXT: String = "DOWN · bleeding out · crawl to your crewmate, who can haul you up with interact" var state: HudState = HudState.new() @@ -24,6 +26,8 @@ var _vitals: Vitals var _hotbar: HBoxContainer var _materials: VBoxContainer var _build: Label +## Down in duos (M7): what to do about it, above the hotbar. +var _down: Label var _reticle: Reticle var _hurt: HurtEdge ## When a feed line was first shown (msec), so lines fade after HudState.FEED_SECONDS. @@ -90,6 +94,14 @@ func _init() -> void: _build.size = Vector2(520.0, 24.0) _build.position = Vector2(-260.0, -112.0 - MARGIN - 30.0) add_child(_build) + _down = _label(FONT_BODY, Palette.WARNING) + _down.set_anchors_preset(Control.PRESET_CENTER_BOTTOM) + _down.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + _down.size = Vector2(720.0, 24.0) + _down.position = Vector2(-360.0, -112.0 - MARGIN - 30.0) + _down.text = DOWN_TEXT + _down.visible = false + add_child(_down) _materials = VBoxContainer.new() _materials.set_anchors_preset(Control.PRESET_BOTTOM_RIGHT) @@ -157,6 +169,7 @@ func show_state(shown: HudState) -> void: var count: int = shown.materials[code] if code < shown.materials.size() else 0 (_materials.get_child(code) as Label).text = "%s %d" % [Materials.NAMES[code].replace("_", " ").capitalize(), count] + _down.visible = shown.playing and shown.downed _build.visible = shown.playing and not shown.build.is_empty() if _build.visible: var build: Dictionary = shown.build diff --git a/src/client/hud/hud_state.gd b/src/client/hud/hud_state.gd index d399f18..1b83312 100644 --- a/src/client/hud/hud_state.gd +++ b/src/client/hud/hud_state.gd @@ -25,6 +25,8 @@ var standing: int = 0 var total: int = 0 ## Lines for the kill feed, oldest first: {"text", "you"}. var feed: Array[Dictionary] = [] +## Down in duos (M7): crawling, bleeding, waiting for a crewmate to haul them up. +var downed: bool = false ## True when the aiming reticle is shown: playing, on foot or swimming. var reticle: bool = false ## Hit feedback (A7, HitFeedback): the marker for a shot that struck someone and the @@ -50,9 +52,11 @@ static func from_client(game: ClientGame, input: ClientInput, own_handle: int, f state.playing = true state.health = drawn.health if drawn != null else me.health state.armor = drawn.armor if drawn != null else me.armor - state.reticle = me.drop_state == Drop.NONE + state.reticle = me.drop_state == Drop.NONE and not me.downed + state.downed = me.downed _fill_carried(state, me) - state.build = build_of(input.build_mode, input.build_kind, input.material, me.materials) + if not me.downed: + state.build = build_of(input.build_mode, input.build_kind, input.material, me.materials) return state @@ -78,9 +82,11 @@ static func from_match(flow: Match, handle: int, build_mode: bool = false, build state.playing = true state.health = me.health state.armor = me.armor - state.reticle = me.drop_state == Drop.NONE + state.reticle = me.drop_state == Drop.NONE and not me.downed + state.downed = me.downed _fill_carried(state, me) - state.build = build_of(build_mode, build_kind, material, me.materials) + if not me.downed: + state.build = build_of(build_mode, build_kind, material, me.materials) return state @@ -112,7 +118,10 @@ static func feed_lines(entries: Array[Dictionary], own_handle: int) -> Array[Dic var by_is_you: bool = int(entry.get("by", 0)) == own_handle and own_handle != 0 var victim: String = "You" if victim_is_you else String(entry.get("victim_name", "Someone")) var by: String = "You" if by_is_you else String(entry.get("by_name", "")) - lines.append({"text": feed_text(victim, by, String(entry.get("cause", "none")), int(entry.get("item", -1)), victim_is_you), "you": victim_is_you or by_is_you}) + var text: String = feed_text(victim, by, String(entry.get("cause", "none")), int(entry.get("item", -1)), victim_is_you) + if bool(entry.get("downed", false)): + text = downed_text(victim, by, victim_is_you) + lines.append({"text": text, "you": victim_is_you or by_is_you}) return lines @@ -136,6 +145,13 @@ static func feed_text(victim: String, by: String, cause: String, item: int, vict return "%s is out" % victim +## A down in duos (M7): the player isn't out until they bleed out or their team falls. +static func downed_text(victim: String, by: String, victim_is_you: bool) -> String: + if not by.is_empty() and by != victim: + return "%s knocked %s down" % [by, "you" if victim_is_you else victim] + return "%s %s down" % [victim, "are" if victim_is_you else "is"] + + ## "flintlock_pistol" -> "Flintlock Pistol". static func item_name(id: String) -> String: return id.replace("_", " ").capitalize() diff --git a/src/net/client_mirror.gd b/src/net/client_mirror.gd index 2d82ab0..bd6ed5f 100644 --- a/src/net/client_mirror.gd +++ b/src/net/client_mirror.gd @@ -147,6 +147,7 @@ func _show_player(entity: SimEntity, record: PackedInt32Array, shown: Dictionary entity.crouching = flags & NetSnapshot.FLAG_CROUCHING != 0 entity.swimming = flags & NetSnapshot.FLAG_SWIMMING != 0 entity.eliminated = flags & NetSnapshot.FLAG_ELIMINATED != 0 + entity.downed = flags & NetSnapshot.FLAG_DOWNED != 0 entity.drop_state = (flags >> NetSnapshot.FLAG_DROP_SHIFT) & 3 # Only whether they last, for drawing: the ticks left aren't replicated. entity.reload_ticks = 1 if flags & NetSnapshot.FLAG_RELOADING != 0 else 0 diff --git a/src/net/client_prediction.gd b/src/net/client_prediction.gd index 3d665b4..fd24fda 100644 --- a/src/net/client_prediction.gd +++ b/src/net/client_prediction.gd @@ -15,7 +15,7 @@ class_name ClientPrediction extends RefCounted ## The flags movement reads and changes. -const _MOVEMENT_FLAGS: int = NetSnapshot.FLAG_ON_GROUND | NetSnapshot.FLAG_SWIMMING | NetSnapshot.FLAG_ELIMINATED | (3 << NetSnapshot.FLAG_DROP_SHIFT) +const _MOVEMENT_FLAGS: int = NetSnapshot.FLAG_ON_GROUND | NetSnapshot.FLAG_SWIMMING | NetSnapshot.FLAG_ELIMINATED | NetSnapshot.FLAG_DOWNED | (3 << NetSnapshot.FLAG_DROP_SHIFT) ## Predicted ticks kept to compare with the server: four seconds. const HISTORY_TICKS: int = 120 diff --git a/src/net/net_feed.gd b/src/net/net_feed.gd index 23991b8..b3edc26 100644 --- a/src/net/net_feed.gd +++ b/src/net/net_feed.gd @@ -7,7 +7,8 @@ ## server -> FEED ## u8 type, u8 standing, u8 players in the match, u8 entry count, then entries: ## s32 victim handle, s32 eliminator handle (0 = none), u8 cause (CAUSES), -## u8 item code plus one (0 = none), u8 place, u8 flags (1 = tied), +## u8 item code plus one (0 = none), u8 place, u8 flags (1 = tied, 2 = downed, +## not out: duos, M7), ## str victim name, str eliminator name, ## where str is u8 byte length then that many UTF-8 bytes (at most MAX_NAME_BYTES). ## @@ -23,11 +24,12 @@ const ENTRY_FIXED_BYTES: int = 12 const MAX_ENTRIES: int = 16 const MAX_NAME_BYTES: int = 32 const FLAG_TIED: int = 1 +const FLAG_DOWNED: int = 2 ## Encodes the count and `entries`, newest last. Each entry has "victim", "by", -## "cause" (a name in CAUSES), "item" (-1 none), "place", "tied", "victim_name" and -## "by_name". Only the newest MAX_ENTRIES are kept. +## "cause" (a name in CAUSES), "item" (-1 none), "place", "tied", "downed", "victim_name" +## and "by_name". Only the newest MAX_ENTRIES are kept. static func encode(standing: int, total: int, entries: Array[Dictionary]) -> PackedByteArray: var out: StreamPeerBuffer = StreamPeerBuffer.new() out.put_u8(MSG_FEED) @@ -42,7 +44,7 @@ static func encode(standing: int, total: int, entries: Array[Dictionary]) -> Pac out.put_u8(maxi(0, CAUSES.find(String(entry.get("cause", "none"))))) out.put_u8(clampi(int(entry.get("item", -1)) + 1, 0, 255)) out.put_u8(clampi(int(entry.get("place", 0)), 0, 255)) - out.put_u8(FLAG_TIED if bool(entry.get("tied", false)) else 0) + out.put_u8((FLAG_TIED if bool(entry.get("tied", false)) else 0) | (FLAG_DOWNED if bool(entry.get("downed", false)) else 0)) _put_name(out, String(entry.get("victim_name", ""))) _put_name(out, String(entry.get("by_name", ""))) return out.data_array @@ -67,6 +69,7 @@ static func decode(bytes: PackedByteArray) -> Dictionary: var entry: Dictionary = { "victim": bytes.decode_s32(at), "by": bytes.decode_s32(at + 4), "cause": CAUSES[cause], "item": int(bytes[at + 9]) - 1, "place": int(bytes[at + 10]), "tied": bytes[at + 11] & FLAG_TIED != 0, + "downed": bytes[at + 11] & FLAG_DOWNED != 0, } at += ENTRY_FIXED_BYTES var names: Array[String] = [] diff --git a/src/net/net_protocol.gd b/src/net/net_protocol.gd index 97ceeae..743874b 100644 --- a/src/net/net_protocol.gd +++ b/src/net/net_protocol.gd @@ -16,7 +16,7 @@ class_name NetProtocol extends RefCounted ## Raised whenever the wire format changes in a way old clients can't read. -const VERSION: int = 4 +const VERSION: int = 5 const MAGIC: String = "TDWL" const CHANNEL_CONTROL: int = 0 ## Unreliable game traffic: commands up, snapshots down. diff --git a/src/net/net_snapshot.gd b/src/net/net_snapshot.gd index 58d22b9..b6d3233 100644 --- a/src/net/net_snapshot.gd +++ b/src/net/net_snapshot.gd @@ -38,8 +38,8 @@ const MATCH_BYTES: int = 14 ## told. Exact, not quantized, so a prediction made from it matches the server's to the ## bit: position and velocity (three f32 each, which is all a Vector3 holds), the water ## level around the player (f64), which of the nine flood cells around the player that -## water reaches (u16), swimming stamina in ticks (u16) and the player's FLAG_ bits (u8). -const SELF_BYTES: int = 37 +## water reaches (u16), swimming stamina in ticks (u16) and the player's FLAG_ bits (u16). +const SELF_BYTES: int = 38 ## Every bit of the nine-cell water mask. const WATER_EVERYWHERE: int = 0x1FF ## The most commands one INPUT may carry. Clients send fewer; see Tuning. @@ -80,6 +80,8 @@ const FLAG_ELIMINATED: int = 1 << 3 const FLAG_DROP_SHIFT: int = 4 const FLAG_RELOADING: int = 1 << 6 const FLAG_USING: int = 1 << 7 +## Down, not out (duos, M7): crawling and waiting for a teammate. +const FLAG_DOWNED: int = 1 << 8 const _U8: int = 0 const _S8: int = 1 @@ -89,7 +91,7 @@ const _WIDTH: Array[int] = [1, 1, 2, 4] ## Per archetype: the wire type of every record index. const _TYPES: Dictionary = { - SimEntity.ARCHETYPE_PLAYER: [_U8, _U16, _U16, _U16, _U16, _S8, _U8, _U8, _U8, _U8], + SimEntity.ARCHETYPE_PLAYER: [_U8, _U16, _U16, _U16, _U16, _S8, _U8, _U8, _U16, _U8], SimEntity.ARCHETYPE_PICKUP: [_U8, _U16, _U16, _U16, _U8, _U16, _U8], SimEntity.ARCHETYPE_PROJECTILE: [_U8, _U16, _U16, _U16, _U8, _U32], } @@ -157,6 +159,8 @@ static func flags_of(entity: SimEntity) -> int: flags |= FLAG_RELOADING if entity.use_ticks > 0: flags |= FLAG_USING + if entity.downed: + flags |= FLAG_DOWNED return flags @@ -180,6 +184,7 @@ static func apply_self(player: SimEntity, own: Dictionary) -> void: player.crouching = flags & FLAG_CROUCHING != 0 player.swimming = flags & FLAG_SWIMMING != 0 player.eliminated = flags & FLAG_ELIMINATED != 0 + player.downed = flags & FLAG_DOWNED != 0 player.drop_state = (flags >> FLAG_DROP_SHIFT) & 3 @@ -257,7 +262,7 @@ static func encode_snapshot(header: Dictionary, removed: PackedInt32Array, recor out.put_double(own["water"]) out.put_u16(int(own["water_mask"]) & WATER_EVERYWHERE) out.put_u16(clampi(int(own["stamina"]), 0, 65535)) - out.put_u8(int(own["flags"]) & 0xFF) + out.put_u16(int(own["flags"]) & 0xFFFF) out.put_u8(removed.size()) for entity_id: int in removed: _put_varint(out, entity_id) @@ -325,7 +330,7 @@ static func decode_snapshot(bytes: PackedByteArray) -> Dictionary: "water": bytes.decode_double(at + 24), "water_mask": bytes.decode_u16(at + 32) & WATER_EVERYWHERE, "stamina": bytes.decode_u16(at + 34), - "flags": bytes[at + 36], + "flags": bytes.decode_u16(at + 36), } for value: float in [own["position"].x, own["position"].y, own["position"].z, own["velocity"].x, own["velocity"].y, own["velocity"].z, own["water"]]: if not is_finite(value): diff --git a/src/server/headless_server.gd b/src/server/headless_server.gd index e5294e4..01ca2d6 100644 --- a/src/server/headless_server.gd +++ b/src/server/headless_server.gd @@ -55,10 +55,11 @@ func _ready() -> void: if not config.has_seed: config.match_seed = _fresh_seed() Engine.max_fps = 0 if config.unthrottled else REALTIME_MAX_FPS - var rules: MatchRules = null + var rules: MatchRules = ServerLoop.immediate_rules(config.players, config.bots) if config.listen: rules = MatchRules.new() rules.fill_with_bots = config.bots > 0 + rules.team_size = config.team_size loop = ServerLoop.new(config.match_seed, config.players, config.bots, rules, config.bot_difficulty) if config.listen: var net: NetServer = NetServer.new() diff --git a/src/server/local_server.gd b/src/server/local_server.gd index f3e81bb..c271338 100644 --- a/src/server/local_server.gd +++ b/src/server/local_server.gd @@ -17,6 +17,16 @@ var _accumulator: float = 0.0 var _greeted: bool = false +## Rules for an offline match of one person and `bots` bots on teams of `team_size`: +## null for solo, which ServerLoop starts at once with its own rules. +static func offline_rules(bots: int, team_size: int) -> MatchRules: + if team_size <= 1: + return null + var rules: MatchRules = ServerLoop.immediate_rules(1, bots) + rules.team_size = team_size + return rules + + ## A match of one person and `bots` bots. With `rules` null it starts at once, and a ## new one starts after each one's results. `difficulty` is every bot's, as an index ## into Tuning.BOT_DIFFICULTIES, or -1 to mix them. diff --git a/src/server/net_game.gd b/src/server/net_game.gd index 6d9e319..b03b3b0 100644 --- a/src/server/net_game.gd +++ b/src/server/net_game.gd @@ -119,7 +119,7 @@ func after_tick() -> void: feed_changes = PackedByteArray() own_changes.clear() for event: Dictionary in flow.events: - if event["type"] == "placed" or event["type"] == "match_started": + if event["type"] in ["placed", "match_started", "downed", "revived"]: feed_changed = true if event["type"] == "phase": changed = true diff --git a/src/server/server_config.gd b/src/server/server_config.gd index 44bf82b..741e4b2 100644 --- a/src/server/server_config.gd +++ b/src/server/server_config.gd @@ -1,7 +1,7 @@ ## Command-line configuration for a headless server. ## ## tools/godot.sh -- --server [--listen] [--port=N] [--seed=N] [--players=N] [--bots=N] -## [--bot-difficulty=mixed|easy|normal|hard] [--ticks=N] +## [--bot-difficulty=mixed|easy|normal|hard] [--team-size=1|2] [--ticks=N] ## [--unthrottled] [--log-every=N] [--matches=N] [--world-hash-every=N] ## [--name=NAME] [--list=HOST[:PORT]]... [--no-lan] ## [--health-port=N] [--health-bind=ADDRESS] [--stop-file=PATH] @@ -24,6 +24,9 @@ ## A listening server answers LAN discovery on its port plus one unless `--no-lan`, ## and registers with each `--list` server (see ListServer) under `--name`. ## +## `--team-size=2` plays duos (M7): pairs in join order, who can't hurt each other and +## go down instead of out while their teammate stands. 1, solo, is the default. +## ## Unknown or malformed arguments are errors, so a typo can't silently run the wrong ## match. See `parse()`. class_name ServerConfig @@ -46,6 +49,8 @@ var port: int = DEFAULT_PORT ## Idle player slots, for a server that isn't listening. var players: int = 0 var bots: int = 0 +## Players on a team: 1 for solo, Tuning.DUO_TEAM_SIZE for duos. +var team_size: int = 1 ## 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. @@ -107,6 +112,7 @@ func to_dictionary() -> Dictionary: "port": port, "players": players, "bots": bots, + "team_size": team_size, "bot_difficulty": "mixed" if bot_difficulty < 0 else String(Tuning.BOT_DIFFICULTIES[bot_difficulty]["name"]), "ticks": ticks, "matches": matches, @@ -147,6 +153,9 @@ func _parse_one(arg: String) -> void: "--bots": if _check_int(key, value): bots = value.to_int() + "--team-size": + if _check_int(key, value): + team_size = value.to_int() "--ticks": if _check_int(key, value): ticks = value.to_int() @@ -260,6 +269,8 @@ func _validate() -> void: ) if listen and players > 0: errors.append("--players is for a server that isn't listening; with --listen, people join over the network") + if team_size < 1 or team_size > Tuning.DUO_TEAM_SIZE: + errors.append("--team-size must be 1 (solo) or %d (duos), got %d" % [Tuning.DUO_TEAM_SIZE, team_size]) if ticks < 0: errors.append("--ticks can't be negative") if log_every < 0: diff --git a/src/sim/explosives.gd b/src/sim/explosives.gd index fbc9189..27ef251 100644 --- a/src/sim/explosives.gd +++ b/src/sim/explosives.gd @@ -16,8 +16,8 @@ ## - Falloff: full damage at the middle, down linearly to Tuning.BLAST_EDGE_FACTOR of it ## at the edge, times the charge's tier. ## - Players take `damage`, armor first, credited to the thrower. The thrower takes -## Tuning.BLAST_SELF_FACTOR of theirs. Everyone else takes it all: there are no -## teammates in solo, and duos (M7) will apply one team rule to every weapon. +## Tuning.BLAST_SELF_FACTOR of theirs. Everyone else takes it all, except the thrower's +## teammates, who take none (Weapons.damage_player's team rule). ## - Pieces and props take `structure_damage`. A breakwater is a piece, so a charge can ## breach one and let the sea in. ## Everything a blast reaches is worked out before any of it is applied, in ID order, diff --git a/src/sim/match.gd b/src/sim/match.gd index def003a..dd91b9f 100644 --- a/src/sim/match.gd +++ b/src/sim/match.gd @@ -222,6 +222,7 @@ func step() -> void: DROP, PLAY: sim.step() _collect_damage() + _collect_downs() _collect_eliminations() if phase == DROP and sim.drop.finished: _enter(PLAY) @@ -252,6 +253,7 @@ func _start() -> void: entity_of[handle] = entity_id handle_of[entity_id] = handle team_of[handle] = index / size + sim.set_team(entity_id, index / size) stats[handle] = {"eliminations": 0, "damage_dealt": 0, "damage_taken": 0} _match_size = participants.size() _roster = participants.duplicate() @@ -279,6 +281,32 @@ func _collect_damage() -> void: _last_weapon[victim] = int(event.get("item", -1)) +## Reports downs and revives (M7) by handle: {"type": "downed", "handle", "by", "cause", +## "item"} and {"type": "revived", "handle", "by"}. Downs also go in the kill feed, marked +## "downed". +func _collect_downs() -> void: + for event: Dictionary in sim.events: + if not handle_of.has(event.get("player", 0)): + continue + var handle: int = handle_of[event["player"]] + if event["type"] == "downed": + var by: int = int(handle_of.get(event["by"], 0)) + var record: Dictionary = { + "type": "downed", "handle": handle, "by": by, "cause": String(event["cause"]), + "item": int(_last_weapon.get(handle, -1)) if by != 0 else -1, "tick": sim.tick, + } + events.append(record) + var entry: Dictionary = record.duplicate() + entry.erase("type") + entry["downed"] = true + entry["place"] = 0 + entry["tied"] = false + entry["left"] = false + kill_feed.append(entry) + elif event["type"] == "revived": + events.append({"type": "revived", "handle": handle, "by": int(handle_of.get(event["by"], 0))}) + + ## Places everyone the simulation eliminated this tick. They share the best place of ## the range they fall into: with five standing and two falling together, both are 4th. func _collect_eliminations() -> void: @@ -377,8 +405,8 @@ func _check_finished() -> void: events.append({"type": "match_ended", "match": current_seed(), "winners": winners.duplicate(), "timed_out": timed_out}) -## The best of `handles` by the tie-break: most health, then highest feet, then the -## earliest to join. With `worst`, the worst instead. +## The best of `handles` by the tie-break: standing over downed, most health, then +## highest feet, then the earliest to join. With `worst`, the worst instead. func _tie_break(handles: Array[int], worst: bool = false) -> int: var chosen: int = handles[0] for handle: int in handles: @@ -393,6 +421,8 @@ func _tie_break(handles: Array[int], worst: bool = false) -> int: func _beats(a: int, b: int) -> bool: var pa: SimEntity = sim.entities.find(entity_of[a]) var pb: SimEntity = sim.entities.find(entity_of[b]) + if pa.downed != pb.downed: + return pb.downed if pa.health != pb.health: return pa.health > pb.health if not is_equal_approx(pa.position.y, pb.position.y): diff --git a/src/sim/movement.gd b/src/sim/movement.gd index 5ee104e..9f82130 100644 --- a/src/sim/movement.gd +++ b/src/sim/movement.gd @@ -21,6 +21,11 @@ static func step(player: SimEntity, command: PlayerCommand, ground: SimGround, s player.crouching = command.is_pressed(PlayerCommand.BUTTON_CROUCH) wants_jump = command.is_pressed(PlayerCommand.BUTTON_JUMP) and not player.crouching wish = _wish_velocity(command, player.crouching) + if player.downed: + # Downed (M7): low to the ground and crawling, with no jump or sprint. + player.crouching = true + wants_jump = false + wish = wish.limit_length(Tuning.DOWNED_CRAWL_SPEED) if player.drop_state == Drop.ABOARD: # Riders move with the barge; Simulation places them. @@ -228,6 +233,10 @@ static func _swim(player: SimEntity, command: PlayerCommand, ground: SimGround, speed = Tuning.SWIM_SPRINT_SPEED if not has_stamina: speed *= Tuning.SWIM_EXHAUSTED_FACTOR + if player.downed: + # A downed swimmer paddles at a crawl and can't dive. + speed = minf(speed, Tuning.DOWNED_CRAWL_SPEED) + diving = false var velocity: Vector3 = move * speed var float_depth: float = Tuning.SWIM_FLOAT_DEPTH if has_stamina else Tuning.SWIM_EXHAUSTED_DEPTH diff --git a/src/sim/sim_entity.gd b/src/sim/sim_entity.gd index 07bb3a1..196d897 100644 --- a/src/sim/sim_entity.gd +++ b/src/sim/sim_entity.gd @@ -63,6 +63,14 @@ var prev_buttons: int = 0 var view_quarters: int = 0 ## Set once health reaches 0. Eliminated players take no more commands. var eliminated: bool = false +## The player's team, set by Match; -1 for none. Players on the same team can't hurt +## each other, and a player with a teammate standing goes down instead of out (M7). +var team: int = -1 +## Down but not out: crawling, bleeding health, waiting for a teammate. See Simulation. +var downed: bool = false +## Ticks a teammate has spent reviving this downed player without a break, and who. +var revive_ticks: int = 0 +var reviver: int = 0 ## The player who last damaged this one, or 0. var last_attacker: int = 0 ## What dealt this player's most recent damage: one of the CAUSE_ constants. The cause diff --git a/src/sim/simulation.gd b/src/sim/simulation.gd index b3a036e..7bcaf0c 100644 --- a/src/sim/simulation.gd +++ b/src/sim/simulation.gd @@ -62,6 +62,8 @@ var _planned_levels: PackedFloat32Array = PackedFloat32Array() var _destroyed_checked: int = 0 ## Player entity IDs, ascending. var _players: Array[int] = [] +## Downed players someone worked on reviving this tick. +var _tended: Dictionary = {} ## Generates the island from the seed, unless `world` is given. Tests that don't care @@ -107,6 +109,51 @@ func add_player() -> int: return player.id +## Puts a player on a team. Players on one team can't hurt each other, and go down +## instead of out while a teammate stands (M7). Match sets every player's team. +func set_team(player_id: int, team: int) -> void: + var player: SimEntity = entities.find(player_id) + if player != null: + player.team = team + + +## Whether `a` and `b` are different players on the same team. +func are_teammates(a: SimEntity, b: SimEntity) -> bool: + return a != null and b != null and a.id != b.id and a.team >= 0 and a.team == b.team + + +## On their feet: in the match, not eliminated, not downed, health left. +static func is_standing(player: SimEntity) -> bool: + return player != null and not player.eliminated and not player.downed and player.health > 0 + + +## Whether any teammate of `player` is standing. +func has_standing_teammate(player: SimEntity) -> bool: + if player.team < 0: + return false + for other_id: int in _players: + var other: SimEntity = entities.find(other_id) + if are_teammates(player, other) and is_standing(other): + return true + return false + + +## The nearest downed teammate within Tuning.REVIVE_RANGE of `player`, or null. Ties go +## to the lower ID. +func revivable_teammate(player: SimEntity) -> SimEntity: + var best: SimEntity = null + var best_distance: float = Tuning.REVIVE_RANGE * Tuning.REVIVE_RANGE + for other_id: int in _players: + var other: SimEntity = entities.find(other_id) + if not are_teammates(player, other) or not other.downed or other.eliminated: + continue + var distance: float = player.position.distance_squared_to(other.position) + if distance <= best_distance and (best == null or distance < best_distance): + best = other + best_distance = distance + return best + + ## Removes a player and any commands queued for it. func remove_player(player_id: int) -> void: entities.remove(player_id) @@ -204,6 +251,7 @@ func step() -> void: drop.ride(player, command, tick) else: _apply_command(player, command) + _advance_downed() Weapons.advance_projectiles(self) _spill_broken_crates() _check_eliminations() @@ -220,12 +268,20 @@ func step() -> void: func _apply_command(player: SimEntity, command: PlayerCommand) -> void: var water: float = water_level_at(player.position) Movement.step(player, command, ground, water) - var sprinting: bool = command != null and command.is_pressed(PlayerCommand.BUTTON_SPRINT) + var sprinting: bool = command != null and command.is_pressed(PlayerCommand.BUTTON_SPRINT) and not player.downed Water.update(player, water_level_at(player.position), drown_dps, sprinting) if player.action_cooldown > 0: player.action_cooldown -= 1 if command != null: Weapons.note_view(player, command, tick) + if player.downed: + # Crawling is all a downed player can do. + player.prev_buttons = command.buttons if command != null else 0 + return + if command != null and command.is_pressed(PlayerCommand.BUTTON_INTERACT) and _tend(player): + # Reviving takes both hands: no looting, firing or building meanwhile. + player.prev_buttons = command.buttons + return Weapons.update(player) Consumables.update(self, player, command) var held: int = command.buttons if command != null else 0 @@ -273,19 +329,87 @@ func _spill_broken_crates() -> void: events.append({"type": "crate_spilled", "prop": prop, "pickups": ids}) -## Marks players whose health reached 0 as eliminated, and drops what they carried. +## A standing player holding interact works on reviving the nearest downed teammate in +## range. Returns true if there was one. Revives on the REVIVE_SECONDS-th tick in a row. +func _tend(player: SimEntity) -> bool: + if player.drop_state != Drop.NONE or player.swimming: + return false + var patient: SimEntity = revivable_teammate(player) + if patient == null: + return false + if patient.reviver != player.id: + patient.revive_ticks = 0 + patient.reviver = player.id + patient.revive_ticks += 1 + _tended[patient.id] = true + if patient.revive_ticks >= roundi(Tuning.REVIVE_SECONDS * Tuning.TICK_RATE_HZ): + patient.downed = false + patient.health = Tuning.REVIVE_HEALTH + patient.revive_ticks = 0 + patient.reviver = 0 + events.append({"type": "revived", "player": patient.id, "by": player.id}) + return true + + +## Downed players bleed, and a revive nobody worked on this tick starts over. +func _advance_downed() -> void: + for player_id: int in _players: + var player: SimEntity = entities.find(player_id) + if not player.downed or player.eliminated: + continue + if not _tended.has(player_id): + player.revive_ticks = 0 + player.reviver = 0 + if tick % Tuning.DOWNED_BLEED_INTERVAL_TICKS == 0: + player.health = maxi(player.health - 1, 0) + _tended.clear() + + +## Players whose health reached 0 go down if a teammate is still standing, and are +## eliminated otherwise, dropping what they carried. Downed players are eliminated once +## their health runs out again, or once no teammate is left standing to revive them. +## The blow that downed them is what eliminated them, credited to who struck it. func _check_eliminations() -> void: + var out: Array[SimEntity] = [] for player_id: int in _players: var player: SimEntity = entities.find(player_id) if player.eliminated or player.health > 0: continue - player.eliminated = true - player.velocity = Vector3.ZERO - events.append({ - "type": "eliminated", "player": player_id, "by": player.last_attacker, - "cause": SimEntity.CAUSE_NAMES[player.last_cause], - }) - Inventory.drop_all(self, player) + if not player.downed and player.drop_state == Drop.NONE and has_standing_teammate(player): + player.downed = true + player.health = Tuning.DOWNED_HEALTH + player.armor = 0 + player.reload_ticks = 0 + player.use_ticks = 0 + player.revive_ticks = 0 + player.reviver = 0 + events.append({ + "type": "downed", "player": player_id, "by": player.last_attacker, + "cause": SimEntity.CAUSE_NAMES[player.last_cause], + }) + else: + out.append(player) + for player: SimEntity in out: + _eliminate(player) + # A downed player with nobody left to revive them is out. + for player_id: int in _players: + var player: SimEntity = entities.find(player_id) + if player.downed and not player.eliminated and not has_standing_teammate(player): + _eliminate(player) + + +func _eliminate(player: SimEntity) -> void: + player.eliminated = true + player.health = 0 + player.velocity = Vector3.ZERO + player.downed = false + player.revive_ticks = 0 + player.reviver = 0 + events.append({ + "type": "eliminated", "player": player.id, "by": player.last_attacker, + "cause": SimEntity.CAUSE_NAMES[player.last_cause], + }) + Inventory.drop_all(self, player) ## Moves the sea surface, and spreads the flood for it at once. Takes effect on the @@ -369,6 +493,10 @@ func state_hash() -> String: buffer.put_32(entity.prev_buttons) buffer.put_u8(1 if entity.eliminated else 0) buffer.put_64(entity.view_quarters) + buffer.put_32(entity.team) + buffer.put_u8(1 if entity.downed else 0) + buffer.put_32(entity.revive_ticks) + buffer.put_32(entity.reviver) buffer.put_32(entity.last_attacker) buffer.put_u8(entity.last_cause) buffer.put_32(entity.item) diff --git a/src/sim/tuning.gd b/src/sim/tuning.gd index c10e775..e409e19 100644 --- a/src/sim/tuning.gd +++ b/src/sim/tuning.gd @@ -58,6 +58,20 @@ const DUO_TEAMS: int = 12 const DUO_TEAM_SIZE: int = 2 const REVIVE_SECONDS: float = 6.0 +# Duos: downed, revive and bleed-out (M7). See Simulation. +## A player whose health runs out while a teammate is still standing goes down instead +## of out, with this much health to bleed. Hits on a downed player take it, too. +const DOWNED_HEALTH: int = 60 +## A downed player loses one health this often, so bleeding out takes 30 seconds. +const DOWNED_BLEED_INTERVAL_TICKS: int = 15 +## Downed players crawl: no jumping, sprinting, firing, building or using items. +const DOWNED_CRAWL_SPEED: float = 1.0 +## A standing teammate holding interact within this distance (feet to feet) revives a +## downed one in REVIVE_SECONDS. Letting go or moving away starts it over. +const REVIVE_RANGE: float = 2.0 +## Health a revived player gets up with. +const REVIVE_HEALTH: int = 30 + # Match flow, in seconds. See Match and MatchRules, which can override each one. ## The lobby counts down once this many participants have joined. const MATCH_MIN_PLAYERS: int = 1 @@ -265,6 +279,11 @@ 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 +## Duos (M7): a bot goes to revive a downed teammate this close, unless it's in a fight. +const BOT_REVIVE_METRES: float = 60.0 +## Duos: a roaming bot this far from its teammate heads back to them. +const BOT_REGROUP_METRES: float = 30.0 + # 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, diff --git a/src/sim/weapons.gd b/src/sim/weapons.gd index df4baea..e4baa9d 100644 --- a/src/sim/weapons.gd +++ b/src/sim/weapons.gd @@ -269,10 +269,14 @@ static func _pull(sim: Simulation, player: SimEntity, point: Vector3, speed: flo ## Takes `amount` from armor, then health. Returns the damage actually done. `item` is -## the weapon's item code, or -1, for the kill feed. +## the weapon's item code, or -1, for the kill feed. Every weapon, the boathook and +## blasts come through here, so this is the one team rule: nobody can hurt a teammate +## (M7). Hurting yourself, as with your own keg, still counts. static func damage_player(sim: Simulation, victim: SimEntity, amount: int, attacker: int, headshot: bool = false, item: int = -1) -> int: if victim == null or victim.eliminated or amount <= 0: return 0 + if attacker != 0 and sim.are_teammates(victim, sim.entities.find(attacker)): + return 0 var to_armor: int = mini(victim.armor, amount) victim.armor -= to_armor var to_health: int = mini(victim.health, amount - to_armor) diff --git a/src/ui/menus.gd b/src/ui/menus.gd index 94a9505..56cfd23 100644 --- a/src/ui/menus.gd +++ b/src/ui/menus.gd @@ -9,7 +9,7 @@ class_name Menus extends Control -signal practice_requested(bots: int, difficulty: int) +signal practice_requested(bots: int, difficulty: int, team_size: int) signal join_requested(host: String, port: int, player_name: String) signal resume_requested signal leave_requested @@ -41,6 +41,7 @@ var _binding_note: Label ## Practice. var _bots: SpinBox var _difficulty: OptionButton +var _mode: OptionButton ## Join. var _name: LineEdit var _address: LineEdit @@ -360,6 +361,10 @@ func _build_practice() -> void: for index: int in Tuning.BOT_DIFFICULTIES.size(): _difficulty.add_item(String(Tuning.BOT_DIFFICULTIES[index]["name"]).capitalize(), index + 1) _row(column, "Bot skill", _difficulty) + _mode = OptionButton.new() + _mode.add_item("Solo", 1) + _mode.add_item("Duos, with a bot crewmate", Tuning.DUO_TEAM_SIZE) + _row(column, "Crew", _mode) _button(column, "Set out", _start_practice) _button(column, "Back", back) @@ -367,8 +372,9 @@ func _build_practice() -> void: func _start_practice() -> void: settings.practice_bots = int(_bots.value) settings.practice_difficulty = _difficulty.selected - 1 + settings.practice_team_size = _mode.get_item_id(_mode.selected) save_settings() - practice_requested.emit(settings.practice_bots, settings.practice_difficulty) + practice_requested.emit(settings.practice_bots, settings.practice_difficulty, settings.practice_team_size) func _build_join() -> void: @@ -580,6 +586,7 @@ func _build_results() -> void: func _refresh_controls() -> void: _bots.value = settings.practice_bots _difficulty.selected = settings.practice_difficulty + 1 + _mode.selected = maxi(_mode.get_item_index(settings.practice_team_size), 0) _name.text = settings.player_name if _address.text.is_empty(): _address.text = settings.last_server diff --git a/test/bots/bot_batch.gd b/test/bots/bot_batch.gd index 68dfc71..1f4b469 100644 --- a/test/bots/bot_batch.gd +++ b/test/bots/bot_batch.gd @@ -18,11 +18,19 @@ static func tick_limit() -> int: ## count from the barge leaving. Each group (M6) adds up its bots' BotBrain.stats and ## holds their "bots", "places" and "wins". ## +## With `team_size` 2 the match is duos (M7), and the result also has "downs", +## "revives", "team_hits" (hits that did damage between teammates, which must be 0) and +## "winner_teams" (how many teams the winners came from, which must be 1). +## ## With `split_builders`, only every other bot gathers and builds; the rest are the ## control group. Bot difficulty also goes by turns of three, so both groups have each ## level equally (within one bot). -static func run_match(seed_value: int, bots: int = Tuning.SOLO_PLAYERS, difficulty: int = -1, split_builders: bool = false) -> Dictionary: - var loop: ServerLoop = ServerLoop.new(seed_value, 0, bots, null, difficulty) +static func run_match(seed_value: int, bots: int = Tuning.SOLO_PLAYERS, difficulty: int = -1, split_builders: bool = false, team_size: int = 1) -> Dictionary: + var rules: MatchRules = null + if team_size > 1: + rules = ServerLoop.immediate_rules(0, bots) + rules.team_size = team_size + var loop: ServerLoop = ServerLoop.new(seed_value, 0, bots, rules, difficulty) var flow: Match = loop.match_flow var level_of: Dictionary = {} for bot: BotBrain in loop.bots: @@ -31,6 +39,7 @@ static func run_match(seed_value: int, bots: int = Tuning.SOLO_PLAYERS, difficul "seed": seed_value, "finished": false, "winner": 0, "winner_difficulty": "", "timed_out": false, "causes": {}, "places": {}, "eliminations": {}, "shots": 0, "slow_ticks": [], "weapon_kills": {}, "death_seconds": [], + "downs": 0, "revives": 0, "team_hits": 0, "winner_teams": 0, } var limit: int = tick_limit() var split: bool = false @@ -45,13 +54,25 @@ static func run_match(seed_value: int, bots: int = Tuning.SOLO_PLAYERS, difficul if Time.get_ticks_usec() - before > ServerLoop.TICK_BUDGET_USEC: result["slow_ticks"].append(loop.sim.tick) for event: Dictionary in loop.sim.events: - if event["type"] == "shot": - result["shots"] += 1 + match String(event["type"]): + "shot": + result["shots"] += 1 + "downed": + result["downs"] += 1 + "revived": + result["revives"] += 1 + "player_hit": + if int(event["armor"]) + int(event["health"]) > 0 and loop.sim.are_teammates(loop.sim.entities.find(int(event["victim"])), loop.sim.entities.find(int(event["player"]))): + result["team_hits"] += 1 for event: Dictionary in flow.events: if event["type"] == "match_ended": result["timed_out"] = event["timed_out"] result["ticks"] = loop.sim.tick result["finished"] = flow.phase == Match.RESULTS + var winner_teams: Dictionary = {} + for handle: int in flow.winners: + winner_teams[flow.team_of[handle]] = true + result["winner_teams"] = winner_teams.size() if flow.winners.size() > 0: result["winner"] = flow.winners[0] result["winner_difficulty"] = level_of.get(flow.winners[0], "") diff --git a/test/bots/test_bot_brain.gd b/test/bots/test_bot_brain.gd index e3fea61..91a4e52 100644 --- a/test/bots/test_bot_brain.gd +++ b/test/bots/test_bot_brain.gd @@ -446,3 +446,66 @@ func test_a_bot_with_nothing_to_do_holds_its_ground() -> void: _run(roundi(Tuning.BOT_HOLD_SECONDS * 0.8) * TICKS) assert_true(me.position.distance_to(at) < 3.0, "and stays put while holding (moved %.1f m)" % me.position.distance_to(at)) assert_true(at.distance_to(HOME) <= Tuning.BOT_ROAM_METRES + 5.0, "it didn't roam far (%.1f m)" % at.distance_to(HOME)) + + +# Duos (M7): bots as teammates. + +func test_bots_never_target_or_shoot_a_teammate() -> void: + _setup() + var brain: BotBrain = _bot(HOME, BotBrain.HARD) + var me: SimEntity = sim.entities.find(brain.player_id) + _arm(me) + var mate: SimEntity = _player(HOME + Vector3(8.0, 0.0, 0.0)) + sim.set_team(me.id, 0) + sim.set_team(mate.id, 0) + _ready_world() + _pin(brain) + _run(3 * TICKS) + assert_eq(brain.target_id, 0, "a teammate in plain view isn't a target") + assert_eq(int(shots_by.get(me.id, 0)), 0) + assert_eq(mate.health, Tuning.PLAYER_MAX_HEALTH) + + +func test_a_bot_goes_to_a_downed_teammate_and_revives_them() -> void: + _setup() + var brain: BotBrain = _bot(HOME) + var me: SimEntity = sim.entities.find(brain.player_id) + _arm(me) + var mate: SimEntity = _player(HOME + Vector3(12.0, 0.0, 6.0)) + sim.set_team(me.id, 0) + sim.set_team(mate.id, 0) + _ready_world() + mate.health = 0 + _run(1) + assert_true(mate.downed) + var revived: Array[bool] = [false] + var states: Dictionary = {} + _run(20 * TICKS, func() -> bool: + states[brain.state] = true + for event: Dictionary in sim.events: + if event["type"] == "revived" and event["by"] == me.id: + revived[0] = true + return revived[0]) + assert_true(states.has("revive"), "states: %s" % [states.keys()]) + assert_true(revived[0], "revived within 20 s (mate downed: %s, %.1f m apart)" % [mate.downed, me.position.distance_to(mate.position)]) + assert_false(mate.downed) + assert_true(Simulation.is_standing(mate)) + + +func test_a_downed_bot_crawls_toward_its_standing_teammate() -> void: + _setup() + var brain: BotBrain = _bot(HOME) + var me: SimEntity = sim.entities.find(brain.player_id) + var mate: SimEntity = _player(HOME + Vector3(10.0, 0.0, 0.0)) + sim.set_team(me.id, 0) + sim.set_team(mate.id, 0) + _ready_world() + me.health = 0 + _run(1) + assert_true(me.downed) + var before: float = me.position.distance_to(mate.position) + _run(3 * TICKS) + assert_eq(brain.state, "downed") + var after: float = me.position.distance_to(mate.position) + assert_near(before - after, 3.0 * Tuning.DOWNED_CRAWL_SPEED, 0.5, "crawled toward the teammate") + assert_eq(int(shots_by.get(me.id, 0)), 0) diff --git a/test/capture/client_hud_downed.tscn b/test/capture/client_hud_downed.tscn new file mode 100644 index 0000000..fe51aa5 --- /dev/null +++ b/test/capture/client_hud_downed.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/client_scene.gd" id="1"] + +[node name="CaptureClient" type="Node3D"] +script = ExtResource("1") +stage = "hud_downed" diff --git a/test/capture/client_scene.gd b/test/capture/client_scene.gd index 222e140..e4be5f6 100644 --- a/test/capture/client_scene.gd +++ b/test/capture/client_scene.gd @@ -12,7 +12,9 @@ ## hud and hud_build (issue A9): once landed, the server hands the player a carbine, a ## fowling piece and bandages, wounds them a little and takes three bots out in ## different ways, so every part of the HUD has something to show; hud_build then goes -## into build mode. Every stage draws the HUD as the client's HudState has it. +## into build mode. hud_downed (issue M7) plays duos, with the first bot as the player's +## crewmate, and after the hud staging a bot's shot downs the player. Every stage draws +## the HUD as the client's HudState has it. extends Node3D const DT: float = 1.0 / Tuning.TICK_RATE_HZ @@ -34,6 +36,8 @@ func _ready() -> void: rules.max_players = bots + 1 rules.lobby_ticks = 6 rules.countdown_ticks = 6 + if stage == "hud_downed": + rules.team_size = Tuning.DUO_TEAM_SIZE _loop = ServerLoop.new(match_seed, 0, bots, rules) _net = NetServer.new() if _net.listen(0, HOST) != OK: @@ -68,7 +72,7 @@ func _ready() -> void: reached = me.drop_state == Drop.ABOARD and _session.game.prediction.next_tick > 3 * Tuning.TICK_RATE_HZ "glide": reached = me.drop_state == Drop.GLIDING - "landed", "basin", "build", "build_refused", "hud", "hud_build": + "landed", "basin", "build", "build_refused", "hud", "hud_build", "hud_downed": reached = me.drop_state == Drop.NONE if reached and since < 0: since = 0 @@ -94,6 +98,11 @@ func _ready() -> void: return if stage == "hud_build" and _build_mode(true).is_empty(): return + if stage == "hud_downed": + var downed_text: String = _down_player() + if downed_text.is_empty(): + return + basin_text += downed_text _session.hud.fade_feed = false _session.hud.show_state(_session.hud_state()) _session.view.settle() @@ -139,7 +148,7 @@ func _stage_hud() -> String: var taken: int = 0 for bot: int in flow.bot_handles.keys(): var player: SimEntity = sim.entities.find(int(flow.entity_of.get(bot, 0))) - if player == null or player.eliminated: + if player == null or player.eliminated or sim.are_teammates(mine, player): continue player.health = 0 player.last_cause = causes[taken] @@ -164,6 +173,35 @@ func _stage_hud() -> String: return " · %d of %d standing, %d feed lines" % [hud.standing, hud.total, hud.feed.size()] +## Duos: a bot's shot takes the player's last health with their crewmate still up, so +## they go down. Returns a caption line, or "" after reporting an error. +func _down_player() -> String: + var flow: Match = _loop.match_flow + var sim: Simulation = _loop.sim + var mine: SimEntity = sim.entities.find(int(flow.entity_of.get(_session.link.handle, 0))) + var foe: SimEntity = null + for bot: int in flow.bot_handles.keys(): + var player: SimEntity = sim.entities.find(int(flow.entity_of.get(bot, 0))) + if player != null and not player.eliminated and not sim.are_teammates(mine, player): + foe = player + break + if mine == null or foe == null or not sim.has_standing_teammate(mine): + push_error("client capture: no foe, or no crewmate standing, to down the player") + return "" + mine.armor = 0 + Weapons.damage_player(sim, mine, mine.health, foe.id, false, ItemCatalog.code_of("dock_carbine")) + for _round: int in Tuning.TICK_RATE_HZ: + _game.poll() + _loop.run_tick() + _game.after_tick() + _session.pump(DT) + var hud: HudState = _session.hud_state() + if not mine.downed or not hud.downed: + push_error("client capture: the player isn't down (server %s, HUD %s)" % [mine.downed, hud.downed]) + return "" + return " · downed, %d health to bleed" % mine.health + + ## Stops the autoplay where the player stands and goes into build mode for a driftwood ## wall, after the server has given the player plenty of materials or taken them all. ## Returns a caption line, or "" after reporting an error. diff --git a/test/capture/figure_scene.gd b/test/capture/figure_scene.gd index e8f2d17..8f3acb8 100644 --- a/test/capture/figure_scene.gd +++ b/test/capture/figure_scene.gd @@ -3,7 +3,7 @@ ## animation, seen from in front and to their right: ## ## - states: idle, walk, run, crouched, creeping, in the air, skydiving, gliding, -## swimming. (Aboard the barge is the idle with the feet set wider; the deck +## swimming, downed (M7). (Aboard the barge is the idle with the feet set wider; the deck ## placement would pull it out of the row.) ## - actions: carrying a longgun, a revolver and a tonic, firing each kind, a boathook ## swing, a keg thrown, building, reloading, drinking and a flinch. @@ -24,6 +24,7 @@ const STATES: Array = [ ["skydive", "", "skydive", 0.8, ""], ["glide", "", "glide", 0.8, ""], ["swim", "", "swim", 0.35, ""], + ["downed", "", "downed", 0.5, ""], ] const ACTIONS: Array = [ ["long", "whalers_longgun", "ground", 0.6, ""], @@ -114,6 +115,10 @@ func _stand(at: Vector3, row: Array) -> SimEntity: "swim": player.swimming = true player.on_ground = false + "downed": + player.downed = true + player.crouching = true + player.health = Tuning.DOWNED_HEALTH "aboard": player.drop_state = Drop.ABOARD player.on_ground = false diff --git a/test/client/test_figure_rig.gd b/test/client/test_figure_rig.gd index 3e8eb45..e24b7b0 100644 --- a/test/client/test_figure_rig.gd +++ b/test/client/test_figure_rig.gd @@ -87,7 +87,11 @@ func test_states_follow_the_replicated_flags() -> void: player.crouching = true assert_eq(FigureRig.state_of(player, false), "crouch") assert_eq(FigureRig.state_of(player, true), "air") + player.downed = true + assert_eq(FigureRig.state_of(player, true), "downed", "M7: down on hands and knees") player.swimming = true + assert_eq(FigureRig.state_of(player, true), "swim", "a downed swimmer still swims") + player.downed = false assert_eq(FigureRig.state_of(player, true), "swim") for drop: Array in [[Drop.ABOARD, "aboard"], [Drop.FREEFALL, "skydive"], [Drop.GLIDING, "glide"]]: player.drop_state = drop[0] diff --git a/test/client/test_hud.gd b/test/client/test_hud.gd index 218ef98..9e45cf6 100644 --- a/test/client/test_hud.gd +++ b/test/client/test_hud.gd @@ -201,3 +201,16 @@ func _texts(node: Node) -> Array[String]: for child: Node in node.get_children(): found.append_array(_texts(child)) return found + + +func test_a_down_in_duos_travels_in_the_feed_and_reads_as_a_down() -> void: + var entries: Array[Dictionary] = [ + {"victim": -3, "by": 1, "cause": "weapon", "item": -1, "place": 0, "tied": false, "downed": true, "victim_name": "Thole", "by_name": "Ada"}, + {"victim": -4, "by": 0, "cause": "fall", "item": -1, "place": 0, "tied": false, "downed": true, "victim_name": "Brine", "by_name": ""}, + ] + var told: Dictionary = NetFeed.decode(NetFeed.encode(3, 24, entries)) + assert_true(told["entries"][0]["downed"]) + var lines: Array[Dictionary] = HudState.feed_lines(told["entries"], 1) + assert_eq(lines[0]["text"], "You knocked Thole down") + assert_eq(lines[1]["text"], "Brine is down") + assert_eq(HudState.feed_lines(told["entries"], -3)[0]["text"], "Ada knocked you down") diff --git a/test/net/test_net_snapshot.gd b/test/net/test_net_snapshot.gd index 732871c..8d7c117 100644 --- a/test/net/test_net_snapshot.gd +++ b/test/net/test_net_snapshot.gd @@ -165,6 +165,7 @@ func test_the_own_block_round_trips_exactly() -> void: assert_eq(copy.stamina_ticks, 1234) assert_true(copy.swimming and not copy.on_ground) assert_eq(copy.drop_state, Drop.GLIDING) + assert_false(copy.downed) assert_eq(back["self"]["water"], own["water"]) assert_eq(back["self"]["water_mask"], 0b101010101) for length: int in bytes.size(): @@ -176,3 +177,25 @@ func test_the_own_block_round_trips_exactly() -> void: assert_true(NetSnapshot.decode_snapshot(poisoned).is_empty(), "a NaN position") poisoned.encode_float(at, INF) assert_true(NetSnapshot.decode_snapshot(poisoned).is_empty(), "an infinite position") + + +func test_downed_travels_in_the_record_and_the_own_block() -> void: + var sim: Simulation = Simulation.new(3, SimGround.flat()) + var player: SimEntity = _player(sim, Vector3(100.0, 0.0, 100.0)) + player.downed = true + player.crouching = true + player.reload_ticks = 3 + var record: PackedInt32Array = NetSnapshot.record_of(player) + assert_true(record[NetSnapshot.R_FLAGS] & NetSnapshot.FLAG_DOWNED != 0) + var own: Dictionary = NetSnapshot.self_of(player, 0.0, 0) + var bytes: PackedByteArray = NetSnapshot.encode_snapshot({"tick": 2, "sim_tick": 2, "own_id": player.id, "self": own}, PackedInt32Array(), [[player.id, NetSnapshot.full_mask(SimEntity.ARCHETYPE_PLAYER), record]]) + var back: Dictionary = NetSnapshot.decode_snapshot(bytes) + assert_false(back.is_empty()) + var merged: PackedInt32Array = NetSnapshot.merge_record(PackedInt32Array(), SimEntity.ARCHETYPE_PLAYER, back["records"][0][2], back["records"][0][3]) + assert_eq(merged, record) + var flags: int = merged[NetSnapshot.R_FLAGS] + assert_true(flags & NetSnapshot.FLAG_DOWNED != 0, "in the record") + assert_true(flags & NetSnapshot.FLAG_RELOADING != 0, "the low byte is still there") + var copy: SimEntity = SimEntity.new(1, SimEntity.ARCHETYPE_PLAYER) + NetSnapshot.apply_self(copy, back["self"]) + assert_true(copy.downed, "in the own block, so prediction crawls too") diff --git a/test/server/test_server_config.gd b/test/server/test_server_config.gd index 48f8bb5..313acac 100644 --- a/test/server/test_server_config.gd +++ b/test/server/test_server_config.gd @@ -153,3 +153,13 @@ func test_health_and_stop_options() -> void: assert_eq([config.health_port, config.health_bind, config.stop_file], [8080, "0.0.0.0", "/tmp/x"]) assert_false(_parse(["--server", "--health-bind=localhost"]).is_valid()) assert_false(_parse(["--server", "--health-port=70000"]).is_valid()) + + +func test_team_size_picks_solo_or_duos() -> void: + assert_eq(_parse(["--server"]).team_size, 1, "solo by default") + var duos: ServerConfig = _parse(["--server", "--team-size=2", "--bots=23", "--players=1"]) + assert_true(duos.is_valid(), str(duos.errors)) + assert_eq(duos.team_size, Tuning.DUO_TEAM_SIZE) + assert_eq(duos.to_dictionary()["team_size"], 2) + for bad: String in ["--team-size=0", "--team-size=3", "--team-size=two"]: + assert_false(_parse(["--server", bad]).is_valid(), bad) diff --git a/test/sim/test_duos.gd b/test/sim/test_duos.gd new file mode 100644 index 0000000..319d8ff --- /dev/null +++ b/test/sim/test_duos.gd @@ -0,0 +1,331 @@ +extends TestCase + +## Duos from issue M7: going down instead of out while a teammate stands, crawling, +## revives, bleeding out, a team eliminated when both are out, no friendly damage, and +## team placement in a match. + +const FEET: Vector3 = Vector3(100.0, 0.0, 100.0) +const REVIVE_TICKS: int = roundi(Tuning.REVIVE_SECONDS * Tuning.TICK_RATE_HZ) + + +## A flat world with four players in a row 1 m apart, facing +z: 1 and 2 on team 0, +## 3 and 4 on team 1. +func _sim() -> Simulation: + var sim: Simulation = Simulation.new(77, SimGround.flat()) + for index: int in 4: + var player: SimEntity = sim.entities.find(sim.add_player()) + player.position = FEET + Vector3(index * 1.0, 0.0, 0.0) + player.on_ground = true + sim.set_team(player.id, index / 2) + return sim + + +func _p(sim: Simulation, id: int) -> SimEntity: + return sim.entities.find(id) + + +## Steps once, with `buttons` and `move` for the players in `held`, and nothing else. +func _step(sim: Simulation, held: Dictionary = {}, move: Vector2 = Vector2.ZERO) -> void: + for id: int in [1, 2, 3, 4]: + if not sim.entities.contains(id): + continue + var buttons: int = int(held.get(id, 0)) + var player: SimEntity = _p(sim, id) + sim.submit_command(id, PlayerCommand.from_input(sim.tick, move if held.has(id) else Vector2.ZERO, 0.0, 0.0, buttons, player.selected)) + sim.step() + + +func _events(sim: Simulation, kind: String) -> Array[Dictionary]: + var found: Array[Dictionary] = [] + for event: Dictionary in sim.events: + if event["type"] == kind: + found.append(event) + return found + + +## Lands a lethal hit on `victim` from `attacker`, then steps. +func _knock(sim: Simulation, victim: int, attacker: int) -> void: + _p(sim, victim).health = 5 + _p(sim, victim).armor = 0 + assert_eq(Weapons.damage_player(sim, _p(sim, victim), 50, attacker), 5) + _step(sim) + + +func test_a_lethal_hit_downs_a_player_whose_teammate_stands() -> void: + var sim: Simulation = _sim() + _knock(sim, 1, 3) + var downed: SimEntity = _p(sim, 1) + assert_true(downed.downed, "down, not out") + assert_false(downed.eliminated) + assert_eq(downed.health, Tuning.DOWNED_HEALTH) + var events: Array[Dictionary] = _events(sim, "downed") + assert_eq(events.size(), 1) + assert_eq(events[0]["player"], 1) + assert_eq(events[0]["by"], 3) + assert_eq(_events(sim, "eliminated").size(), 0) + + +func test_a_player_with_no_team_or_no_teammate_standing_is_eliminated_outright() -> void: + var sim: Simulation = _sim() + sim.set_team(1, -1) + _knock(sim, 1, 3) + assert_true(_p(sim, 1).eliminated, "no team: out") + assert_false(_p(sim, 1).downed) + # Player 2's teammate is out, so 2 has nobody to wait for either. + _knock(sim, 2, 3) + assert_true(_p(sim, 2).eliminated) + + +func test_downed_players_crawl_and_cannot_fire_build_or_loot() -> void: + var sim: Simulation = _sim() + Inventory.give(_p(sim, 1), ItemCatalog.code_of("dock_carbine"), 1) + Inventory.give(_p(sim, 1), ItemCatalog.get_def(ItemCatalog.code_of("dock_carbine")).ammo_code, 20) + _p(sim, 1).selected = 1 + _knock(sim, 1, 3) + var start: Vector3 = _p(sim, 1).position + var shots: int = 0 + for _tick: int in Tuning.TICK_RATE_HZ: + _step(sim, {1: PlayerCommand.BUTTON_FIRE | PlayerCommand.BUTTON_SPRINT | PlayerCommand.BUTTON_JUMP}, Vector2(0.0, 1.0)) + shots += _events(sim, "shot").size() + assert_true(_p(sim, 1).on_ground, "no jumping") + assert_eq(shots, 0, "no firing") + var crawled: float = _p(sim, 1).position.distance_to(start) + assert_near(crawled, Tuning.DOWNED_CRAWL_SPEED, 0.1, "a second of crawling, sprint held") + assert_true(_p(sim, 1).crouching, "low to the ground") + _step(sim, {1: PlayerCommand.BUTTON_FIRE | PlayerCommand.BUTTON_BUILD}) + assert_eq(sim.structures.pieces.size(), 0, "no building") + + +func test_a_teammate_holding_interact_revives_after_the_revive_time() -> void: + var sim: Simulation = _sim() + _knock(sim, 1, 3) + for _tick: int in REVIVE_TICKS - 1: + _step(sim, {2: PlayerCommand.BUTTON_INTERACT}) + assert_true(_p(sim, 1).downed) + assert_eq(_p(sim, 1).revive_ticks, REVIVE_TICKS - 1) + assert_eq(_p(sim, 1).reviver, 2) + _step(sim, {2: PlayerCommand.BUTTON_INTERACT}) + assert_false(_p(sim, 1).downed, "back up") + assert_eq(_p(sim, 1).health, Tuning.REVIVE_HEALTH) + var revived: Array[Dictionary] = _events(sim, "revived") + assert_eq(revived.size(), 1) + assert_eq(revived[0]["by"], 2) + + +func test_letting_go_or_moving_away_starts_the_revive_over() -> void: + var sim: Simulation = _sim() + _knock(sim, 1, 3) + for _tick: int in 60: + _step(sim, {2: PlayerCommand.BUTTON_INTERACT}) + _step(sim) + assert_eq(_p(sim, 1).revive_ticks, 0, "let go") + _p(sim, 2).position = _p(sim, 1).position + Vector3(Tuning.REVIVE_RANGE + 0.5, 0.0, 0.0) + for _tick: int in REVIVE_TICKS + 5: + _step(sim, {2: PlayerCommand.BUTTON_INTERACT}) + assert_true(_p(sim, 1).downed, "out of reach") + assert_eq(_p(sim, 1).revive_ticks, 0) + + +func test_an_opponent_cannot_revive_and_a_downed_player_cannot_revive() -> void: + var sim: Simulation = _sim() + _knock(sim, 1, 3) + _knock(sim, 4, 2) + for _tick: int in REVIVE_TICKS + 5: + _step(sim, {3: PlayerCommand.BUTTON_INTERACT, 4: PlayerCommand.BUTTON_INTERACT}) + assert_true(_p(sim, 1).downed, "3 is an opponent") + assert_true(_p(sim, 3).health > 0 and not _p(sim, 3).downed) + + +func test_a_downed_player_bleeds_out_credited_to_who_downed_them() -> void: + var sim: Simulation = _sim() + _knock(sim, 1, 3) + var ticks: int = 0 + while not _p(sim, 1).eliminated and ticks < 2000: + _step(sim) + ticks += 1 + assert_true(_p(sim, 1).eliminated) + assert_near(ticks, Tuning.DOWNED_HEALTH * Tuning.DOWNED_BLEED_INTERVAL_TICKS, Tuning.DOWNED_BLEED_INTERVAL_TICKS, "about 30 s") + var out: Array[Dictionary] = _events(sim, "eliminated") + assert_eq(out.size(), 1) + assert_eq(out[0]["by"], 3) + assert_eq(out[0]["cause"], "weapon") + + +func test_hits_on_a_downed_player_finish_them() -> void: + var sim: Simulation = _sim() + _knock(sim, 1, 3) + Weapons.damage_player(sim, _p(sim, 1), Tuning.DOWNED_HEALTH, 4) + _step(sim) + assert_true(_p(sim, 1).eliminated) + assert_eq(_events(sim, "eliminated")[0]["by"], 4) + + +func test_the_team_is_out_when_both_are_down_or_out() -> void: + var sim: Simulation = _sim() + _knock(sim, 1, 3) + assert_true(_p(sim, 1).downed) + _knock(sim, 2, 4) + assert_true(_p(sim, 2).eliminated, "nobody left to down for") + assert_true(_p(sim, 1).eliminated, "and nobody left to revive 1") + assert_eq(_events(sim, "eliminated").size(), 2) + var credited: Dictionary = {} + for event: Dictionary in _events(sim, "eliminated"): + credited[event["player"]] = event["by"] + assert_eq(credited, {1: 3, 2: 4}) + + +func test_teammates_falling_together_are_both_out() -> void: + var sim: Simulation = _sim() + _p(sim, 1).health = 0 + _p(sim, 2).health = 0 + _step(sim) + assert_true(_p(sim, 1).eliminated and _p(sim, 2).eliminated) + assert_false(_p(sim, 1).downed or _p(sim, 2).downed) + + +func test_no_friendly_damage_from_any_weapon() -> void: + var sim: Simulation = _sim() + assert_eq(Weapons.damage_player(sim, _p(sim, 2), 30, 1), 0, "teammate") + assert_eq(_p(sim, 2).health, Tuning.PLAYER_MAX_HEALTH) + assert_eq(Weapons.damage_player(sim, _p(sim, 3), 30, 1), 30, "opponent") + assert_eq(Weapons.damage_player(sim, _p(sim, 1), 10, 1), 10, "yourself, as with your own keg") + # A keg thrown into the team: the teammate beside the blast takes nothing. + var keg: int = ItemCatalog.code_of("powder_keg") + var def: ItemDef = ItemCatalog.get_def(keg) + var before: int = _p(sim, 2).health + Explosives.blast(sim, 1, def, 0, _p(sim, 2).position + Vector3(0.0, 0.3, 0.0)) + assert_eq(_p(sim, 2).health, before, "no blast damage to a teammate") + assert_true(_p(sim, 3).health < Tuning.PLAYER_MAX_HEALTH - 30, "the opponent a metre further on is hurt") + + +func test_a_downed_player_in_the_sea_still_drowns() -> void: + var sim: Simulation = _sim() + _knock(sim, 1, 3) + sim.set_sea_level(5.0) + for _tick: int in 3: + _step(sim) + assert_true(_p(sim, 1).swimming) + var ticks: int = 0 + while not _p(sim, 1).eliminated and ticks < 1200: + _step(sim) + ticks += 1 + assert_true(_p(sim, 1).eliminated, "drowning takes the downed health") + assert_true(ticks < Tuning.DOWNED_HEALTH * Tuning.DOWNED_BLEED_INTERVAL_TICKS, "sooner than bleeding out") + + +func test_the_hash_tells_downed_and_revive_progress_apart() -> void: + var a: Simulation = _sim() + var b: Simulation = _sim() + assert_eq(a.state_hash(), b.state_hash()) + _p(a, 1).downed = true + assert_ne(a.state_hash(), b.state_hash()) + _p(b, 1).downed = true + _p(b, 1).revive_ticks = 3 + assert_ne(a.state_hash(), b.state_hash()) + + +# Match: team placement. + +func _rules() -> MatchRules: + var rules: MatchRules = MatchRules.immediate() + rules.max_players = 6 + rules.results_ticks = 2 + rules.team_size = Tuning.DUO_TEAM_SIZE + return rules + + +func _duos_match() -> Match: + var m: Match = Match.new(4242, _rules()) + m.sim = Simulation.new(4242, SimGround.flat(20.0)) + m.join(1) + m.step() + assert_eq(m.phase, Match.DROP) + var index: int = 0 + for handle: int in m.participants: + var player: SimEntity = m.sim.entities.find(m.entity_of[handle]) + player.drop_state = Drop.NONE + player.position = Vector3(100.0 + index * 4.0, 20.0, 100.0) + player.velocity = Vector3.ZERO + player.on_ground = true + index += 1 + m.sim.drop.finished = true + m.step() + assert_eq(m.phase, Match.PLAY) + return m + + +func _mp(m: Match, handle: int) -> SimEntity: + return m.sim.entities.find(m.entity_of[handle]) + + +func _place_of(m: Match, handle: int) -> int: + for record: Dictionary in m.placements: + if record["handle"] == handle: + return int(record["place"]) + return 0 + + +func test_match_puts_each_pair_on_a_team_in_the_simulation() -> void: + var m: Match = _duos_match() + var hs: Array[int] = m.participants.duplicate() + assert_eq(hs.size(), 6) + for index: int in hs.size(): + assert_eq(m.team_of[hs[index]], index / 2) + assert_eq(_mp(m, hs[index]).team, index / 2) + + +func test_match_keeps_a_downed_team_alive_and_places_the_pair_together() -> void: + var m: Match = _duos_match() + var hs: Array[int] = m.participants.duplicate() + _mp(m, hs[0]).health = 0 + _mp(m, hs[0]).last_attacker = m.entity_of[hs[2]] + _mp(m, hs[0]).last_cause = SimEntity.CAUSE_WEAPON + m.step() + assert_true(_mp(m, hs[0]).downed) + assert_eq(_place_of(m, hs[0]), 0, "down isn't placed") + assert_true(m.alive().has(hs[0]), "still in the match") + var downs: Array[Dictionary] = [] + for event: Dictionary in m.events: + if event["type"] == "downed": + downs.append(event) + assert_eq(downs.size(), 1) + assert_eq(downs[0]["by"], hs[2]) + assert_true(bool(m.kill_feed[-1].get("downed", false)), "the down is in the feed") + assert_eq(m.stats[hs[2]]["eliminations"], 0, "a down isn't an elimination yet") + # The teammate falls: both are out, sharing the place below the two teams left. + _mp(m, hs[1]).health = 0 + _mp(m, hs[1]).last_attacker = m.entity_of[hs[4]] + _mp(m, hs[1]).last_cause = SimEntity.CAUSE_WEAPON + m.step() + assert_eq(_place_of(m, hs[0]), 5) + assert_eq(_place_of(m, hs[1]), 5) + assert_eq(m.stats[hs[2]]["eliminations"], 1, "credited to who downed them") + assert_eq(m.stats[hs[4]]["eliminations"], 1) + assert_eq(m.phase, Match.PLAY) + # One of the next team goes down, then the other: the last team wins, both of them. + _mp(m, hs[2]).health = 0 + m.step() + assert_true(_mp(m, hs[2]).downed) + assert_eq(m.phase, Match.PLAY, "a downed player keeps the team in it") + _mp(m, hs[3]).health = 0 + m.step() + assert_eq(m.phase, Match.RESULTS) + assert_eq(m.winners, [hs[4], hs[5]] as Array[int]) + assert_eq(_place_of(m, hs[2]), 3) + assert_eq(_place_of(m, hs[3]), 3) + + +func test_match_tie_break_prefers_a_standing_team_over_a_downed_one() -> void: + var m: Match = _duos_match() + var hs: Array[int] = m.participants.duplicate() + # Teams 0 and 1 left, team 2 out. + _mp(m, hs[4]).health = 0 + _mp(m, hs[5]).health = 0 + m.step() + _mp(m, hs[0]).health = 0 + m.step() + assert_true(_mp(m, hs[0]).downed) + _mp(m, hs[1]).health = 1 + _mp(m, hs[2]).health = 1 + _mp(m, hs[3]).health = 1 + assert_eq(m._tie_break([hs[0], hs[2]] as Array[int]), hs[2], "standing beats downed, despite more health") diff --git a/test/sim/test_duos.gd.uid b/test/sim/test_duos.gd.uid new file mode 100644 index 0000000..c49546c --- /dev/null +++ b/test/sim/test_duos.gd.uid @@ -0,0 +1 @@ +uid://b2cresp6auksd diff --git a/test/sim/test_match.gd b/test/sim/test_match.gd index 76ee03f..897b870 100644 --- a/test/sim/test_match.gd +++ b/test/sim/test_match.gd @@ -48,8 +48,9 @@ func _saw(m: Match, type: String) -> bool: ## The state a fresh simulation for match `index` should have just after it starts. func _reference_hash(m: Match, index: int, players: int) -> String: var sim: Simulation = Simulation.new(m.match_seed(index)) - for _index: int in players: - sim.add_player() + for player_index: int in players: + # Solo: everyone on a team of their own, as Match sets them. + sim.set_team(sim.add_player(), player_index) sim.start_drop() sim.start_tide() sim.place_loot() diff --git a/test/sim/test_results.gd b/test/sim/test_results.gd index 60d32a9..a4fe60f 100644 --- a/test/sim/test_results.gd +++ b/test/sim/test_results.gd @@ -278,6 +278,11 @@ func test_teammates_spectate_their_living_team() -> void: var hs: Array[int] = m.participants.duplicate() _eliminate(m, hs[0]) m.step() + assert_true(_player(m, hs[0]).downed, "duos: down first (M7)") + assert_eq(m.spectate_target(hs[0]), 0, "a downed player isn't spectating") + _eliminate(m, hs[0]) + m.step() + assert_true(_player(m, hs[0]).eliminated, "finished off") assert_eq(m.spectate_target(hs[0]), hs[1], "with no eliminator, the teammate") diff --git a/test/ui/test_menus.gd b/test/ui/test_menus.gd index 3232adc..1aedabe 100644 --- a/test/ui/test_menus.gd +++ b/test/ui/test_menus.gd @@ -140,13 +140,17 @@ func test_settings_controls_change_and_save_the_settings() -> void: func test_practice_and_join_say_what_was_asked() -> void: var asked: Array = [] - menus.practice_requested.connect(func(bots: int, difficulty: int) -> void: asked.append(["practice", bots, difficulty])) + menus.practice_requested.connect(func(bots: int, difficulty: int, team_size: int) -> void: asked.append(["practice", bots, difficulty, team_size])) menus.join_requested.connect(func(host: String, port: int, player_name: String) -> void: asked.append(["join", host, port, player_name])) menus.show_screen("practice", false) menus._bots.value = 5 menus._difficulty.select(1) _press("practice", "Set out") - assert_eq(asked.pop_back(), ["practice", 5, 0]) + assert_eq(asked.pop_back(), ["practice", 5, 0, 1]) + menus._mode.select(1) + _press("practice", "Set out") + assert_eq(asked.pop_back(), ["practice", 5, 0, Tuning.DUO_TEAM_SIZE], "duos (M7)") + assert_eq(menus.settings.practice_team_size, Tuning.DUO_TEAM_SIZE) menus.show_screen("join", false) menus._name.text = "Wren" menus._address.text = "not a port:x" diff --git a/tools/duo_matches.gd b/tools/duo_matches.gd new file mode 100644 index 0000000..e9ad899 --- /dev/null +++ b/tools/duo_matches.gd @@ -0,0 +1,49 @@ +## Plays bot-only duos matches (M7) on a run of seeds: 12 teams of two bots. Checks +## every match ends with one winning team, bots went down and revived teammates, no hit +## between teammates did damage, and the ticks kept within budget. +## +## tools/godot.sh --script res://tools/duo_matches.gd -- [--seeds=10] [--first=1] +## +## Prints one JSON line per match and a summary. Exits 1 if a check fails. +extends SceneTree + + +func _init() -> void: + var count: int = 10 + var first: int = 1 + for arg: String in OS.get_cmdline_user_args(): + if arg.begins_with("--seeds="): + count = arg.trim_prefix("--seeds=").to_int() + elif arg.begins_with("--first="): + first = arg.trim_prefix("--first=").to_int() + var results: Array[Dictionary] = [] + var downs: int = 0 + var revives: int = 0 + var team_hits: int = 0 + var one_team: int = 0 + for seed_value: int in range(first, first + count): + var result: Dictionary = BotBatch.run_match(seed_value, Tuning.SOLO_PLAYERS, -1, false, Tuning.DUO_TEAM_SIZE) + result.erase("building") + results.append(result) + downs += int(result["downs"]) + revives += int(result["revives"]) + team_hits += int(result["team_hits"]) + one_team += 1 if int(result["winner_teams"]) == 1 else 0 + print(JSON.stringify({"seed": seed_value, "finished": result["finished"], "ticks": result["ticks"], + "winner_teams": result["winner_teams"], "downs": result["downs"], "revives": result["revives"], + "team_hits": result["team_hits"], "causes": result["causes"], "p99_us": result["timing"].get("p99_us", 0)})) + var total: Dictionary = BotBatch.summarise(results) + var problems: Array[String] = [] + if total["finished"] != count or one_team != count: + problems.append("%d of %d matches finished with one winning team" % [one_team, count]) + if downs == 0 or revives == 0: + problems.append("bots went down %d times and revived %d times; both should happen" % [downs, revives]) + if team_hits > 0: + problems.append("%d hits between teammates did damage" % team_hits) + if int(total["worst_p99_us"]) > ServerLoop.TICK_BUDGET_USEC: + problems.append("the worst match's p99 tick was %d us, over the %d us budget" % [total["worst_p99_us"], ServerLoop.TICK_BUDGET_USEC]) + for problem: String in problems: + print("duo-matches FAIL: %s" % problem) + if problems.is_empty(): + print("duo-matches: ok (%d matches, each won by one team, %d downs, %d revives, %.1f%% drowned, worst p99 %d us)" % [count, downs, revives, total["drown_share"] * 100.0, total["worst_p99_us"]]) + quit(0 if problems.is_empty() else 1) diff --git a/tools/duo_matches.gd.uid b/tools/duo_matches.gd.uid new file mode 100644 index 0000000..7684297 --- /dev/null +++ b/tools/duo_matches.gd.uid @@ -0,0 +1 @@ +uid://ddv3is8k7bg05 diff --git a/tools/duo_matches.sh b/tools/duo_matches.sh new file mode 100755 index 0000000..7b1bdf2 --- /dev/null +++ b/tools/duo_matches.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Plays bot-only duos matches on a run of seeds, under nice, and prints one JSON line per +# match, a summary and the verdict. See tools/duo_matches.gd for what is checked. +# +# tools/duo_matches.sh seeds 1 to 10 +# DUO_MATCH_SEEDS=5 DUO_MATCH_FIRST=40 tools/duo_matches.sh +set -uo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +count="${DUO_MATCH_SEEDS:-10}" +first="${DUO_MATCH_FIRST:-1}" +raw="$(nice -n 15 tools/godot.sh --script res://tools/duo_matches.gd -- --seeds="$count" --first="$first" 2>&1)" +code=$? +grep -E '^\{|^duo-matches' <<<"$raw" +if [[ "$code" -ne 0 ]] && ! grep -q '^duo-matches' <<<"$raw"; then + echo "duo-matches FAIL: the run exited $code" + tail -n 15 <<<"$raw" +fi +exit "$code"