diff --git a/CLAUDE.md b/CLAUDE.md index df2fdfd..10e8882 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,6 +39,8 @@ continuity. | `make match-captures` | Renders eight stages of that match from its command log (`captures/match_.png`), about 3 minutes. Needs Docker. Look at them. | | `make terrain-capture` | Renders the terrain crack check and a skirtless control in the capture container. The control must crack and the real terrain must not. Needs Docker. | | `tools/godot.sh -- --connect=HOST:PORT --autoplay --client-seconds=N` | Runs the client headless against a server for N seconds, played by its script, and prints one JSON line saying how far it got. `--offline` plays a server in the same process instead. On a real display, with no options, the game opens on its main menu (`AppShell`); see `src/app/client_config.gd`. | +| `make tutorial-check` | A12: the tutorial's scripted player (`TutorialPilot`) plays it from the barge to the end on 12 seeds through a real `ClientSession` and its offline server (about 40 s). `TUTORIAL_SEEDS`, `TUTORIAL_FIRST` change the seeds. `tidewall --tutorial --autoplay` does the same in one process in real time. | +| `make tutorial-captures` | Renders the tutorial's card at the move, build and tide steps and the first-launch welcome (`captures/tutorial_*.png`, `menu_welcome.png`, about 2 min). Needs Docker. Look at them. | | `make client-check` | Starts a server and a client as two processes, joins them over loopback UDP and checks the client plays (about a minute, real time). | | `tools/godot.sh -- --list-server [--port=N]` | Runs a list server (default UDP port 24660). Game servers started with `--listen --list=HOST[:PORT] --name=NAME` register with it; see `src/server/list_server.gd`. | | `tools/godot.sh -- --browse [--list=HOST[:PORT]] [--lan-target=IP] [--lan-port=N]` | Looks for servers on the LAN and in list servers and prints them as one JSON line. The join menu (A10) shows the same list. | diff --git a/Makefile b/Makefile index aeb9112..2a01e84 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 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 +.PHONY: tutorial-check tutorial-captures 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 @@ -139,6 +139,16 @@ match: import match-captures: import @tools/match_captures.sh +## A12: the tutorial's scripted player finishes it from the barge to the end on 12 +## seeds, through a real ClientSession and its offline server (about 40 s). +tutorial-check: import + @nice -n 15 $(GODOT) --script res://tools/tutorial_check.gd -- --seeds=$${TUTORIAL_SEEDS:-12} --first=$${TUTORIAL_FIRST:-1} + +## A12: the tutorial's card at three steps, and the welcome that offers it +## (captures/tutorial_*.png, menu_welcome.png, about 2 min). Needs Docker. Look at them. +tutorial-captures: import + @for scene in tutorial_move tutorial_build tutorial_tide menu_welcome; do tools/capture.sh $$scene captures/$$scene.png; done + ## Joins a real client process to a real server process over loopback UDP and checks ## it gets from the lobby into the match. About a minute, in real time. client-check: import @@ -167,7 +177,7 @@ hud-captures: import ## A10: every menu screen (captures/menu_*.png, about 5 min). Needs Docker. Look at them. menu-captures: import - @for scene in menu_main menu_practice menu_join menu_settings menu_settings_mouse menu_pause menu_results; do tools/capture.sh $$scene captures/$$scene.png; done + @for scene in menu_welcome menu_main menu_practice menu_join menu_settings menu_settings_mouse menu_pause menu_results; do tools/capture.sh $$scene captures/$$scene.png; done ## A11: the chart and minimap with the first tide forecast, and after it has risen ## (captures/chart_*.png, about 2 min). Needs Docker. Look at them. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5198fde..83c18c9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -523,8 +523,17 @@ game starts an offline match, or joins a server with `--connect`. Without a wind (`tools/godot.sh` is always headless) a mode has to be asked for. `--autoplay` puts a small script at the controls and `--client-seconds=N` quits after N seconds with one JSON line saying how far the client got, which is what `make client-check` reads. -There are no menus yet (N6, A10) and no HUD (A9): one line of text says when the -client is connecting, in the lobby or watching. +With a window and no mode, `AppShell` opens the menus (A10) and the HUD (A9) draws +over each match. + +The tutorial (A12, `--tutorial` or the menus) is an ordinary offline match under +`MatchRules.tutorial()`: one player, no bots, `last_team_wins` off so being alone +isn't a win, and `starting_kit` putting `Tuning.TUTORIAL_KIT` in hand. The server +rules are the only change to the game; the lesson itself is client-side. `Tutorial` +watches what the client already has (its predicted player, its copy of the world and +the FX it is sent) and moves on when each step is done; `TutorialCard` shows it on the +HUD with the player's own key names; `TutorialPilot` plays it through `ClientInput` +for `--autoplay`, the tests and `make tutorial-check`. ## Performance budgets diff --git a/docs/PLAY.md b/docs/PLAY.md index ace31ee..92b7394 100644 --- a/docs/PLAY.md +++ b/docs/PLAY.md @@ -35,8 +35,14 @@ Replace `1.0.0` with the version you downloaded. ## Starting a match -The game opens on its main menu. +The first time, the game offers the tutorial; after that it opens on its main menu. +- **Tutorial** is a few minutes on an island of your own: leave the barge and glide + down, walk and jump, cut materials with the boathook, build a wall, fire the dock + carbine you start with, and get above the line the tide will reach. A card under the + minimap says what to do with your own keys and moves on when you've done it. Nobody + else is there, so only the tide can end it. Leave it whenever you like from the pause + menu (Escape). - **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 @@ -45,6 +51,7 @@ The game opens on its main menu. You can also start straight into a match from a terminal: + ./tidewall --tutorial # the tutorial ./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 diff --git a/packaging/deb/man/tidewall.6 b/packaging/deb/man/tidewall.6 index d58fc2c..dc3fece 100644 --- a/packaging/deb/man/tidewall.6 +++ b/packaging/deb/man/tidewall.6 @@ -8,7 +8,8 @@ tidewall \- build-and-survive battle royale on a drowning island .RI [ "game options" ] .SH DESCRIPTION .B tidewall -starts the game on its main menu: practice offline against bots, find a +starts the game on its main menu (offering the tutorial the first time): learn the +game in the tutorial, practice offline against bots, find a server on the local network, or join one by address. The sea rises in phases and swallows the low ground; gather salvage, build, and be the last one standing. @@ -33,6 +34,10 @@ Start a practice match against bots at once. .TP .B \-\-duos With \-\-offline, play duos with the first bot as your crewmate. +.TP +.B \-\-tutorial +Start the tutorial at once: a short match alone that teaches the drop, gathering, +building, firing and the tide, using your own key bindings. .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 6ebc1f3..5fc1872 100644 --- a/src/app/app_shell.gd +++ b/src/app/app_shell.gd @@ -1,5 +1,5 @@ ## The game program on a display: the menus, and a ClientSession while a match is -## played. Practice and Join start a session; Escape in a match brings up the pause +## played. The first launch offers the tutorial (A12). Practice, Tutorial and Join start a session; Escape in a match brings up the pause ## menu (the match goes on: it's a live server, even offline); Leave ends the session ## and goes back to the main menu; when a match the player was in ends, the results ## screen shows where they placed. @@ -42,6 +42,7 @@ func _init(with: GameSettings = null, path: String = GameSettings.DEFAULT_PATH) menus.use_settings(settings, path) layer.add_child(menus) menus.practice_requested.connect(start_practice) + menus.tutorial_requested.connect(start_tutorial) menus.join_requested.connect(join) menus.resume_requested.connect(resume) menus.leave_requested.connect(leave) @@ -59,7 +60,7 @@ func _init(with: GameSettings = null, path: String = GameSettings.DEFAULT_PATH) func _ready() -> void: settings.apply_to_program(get_tree()) if session == null: - menus.show_screen("main", false) + menus.show_screen("main" if settings.tutorial_offered else "welcome", false) ## Starts an offline match against bots, solo or in duos (`team_size` 2, M7). @@ -70,6 +71,15 @@ func start_practice(bots: int, difficulty: int, team_size: int = 1) -> void: _begin(practice) +## Starts the tutorial (A12): an offline match alone, with its card on the HUD. +func start_tutorial() -> void: + var match_seed: int = int(Time.get_unix_time_from_system() * 1000.0) & 0x7FFFFFFF + var lesson: ClientSession = ClientSession.new() + lesson.use_settings(settings) + lesson.play_tutorial(match_seed) + _begin(lesson) + + ## Joins a server. Says so on the join screen if the connection can't be opened. func join(host: String, port: int, player_name: String) -> Error: var joining: ClientSession = ClientSession.new() @@ -137,6 +147,15 @@ func _begin(started: ClientSession) -> void: func _process(_delta: float) -> void: if session != null: watch_match() + watch_tutorial() + + +## Remembers once the tutorial has been finished. Called every frame. +func watch_tutorial() -> void: + if session.tutorial == null or not session.tutorial.finished() or settings.tutorial_done: + return + settings.tutorial_done = true + settings.save(settings_path) ## Counts this player's eliminations from the feed, and shows the results when a match diff --git a/src/app/client_config.gd b/src/app/client_config.gd index 95c087b..08984e6 100644 --- a/src/app/client_config.gd +++ b/src/app/client_config.gd @@ -2,6 +2,8 @@ ## ## tidewall the main menu (with a window) ## tidewall --offline an offline match against bots +## tidewall --tutorial the tutorial (A12), an offline match alone; with +## --autoplay its scripted player plays it through ## tidewall --connect=HOST[:PORT] join a server ## options: --name=NAME --seed=N --bots=N (offline) --duos (offline) --autoplay ## --client-seconds=N quit after N seconds, saying what happened @@ -27,6 +29,8 @@ 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 +## The tutorial (A12) with --tutorial. +var tutorial: bool = false var autoplay: bool = false ## Quit after this many seconds; 0 runs until the window is closed. var seconds: float = 0.0 @@ -45,7 +49,7 @@ var errors: Array[String] = [] ## Every option parse() knows, by name. const OPTIONS: Array[String] = [ - "--offline", "--autoplay", "--duos", "--browse", "--list", "--lan-port", "--lan-target", + "--offline", "--tutorial", "--autoplay", "--duos", "--browse", "--list", "--lan-port", "--lan-target", "--connect", "--name", "--seed", "--bots", "--client-seconds", ] @@ -73,6 +77,9 @@ static func parse(args: PackedStringArray) -> ClientConfig: match parts[0]: "--offline": config.asked = true + "--tutorial": + config.asked = true + config.tutorial = true "--autoplay": config.autoplay = true "--duos": @@ -126,6 +133,8 @@ static func parse(args: PackedStringArray) -> ClientConfig: 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.tutorial and (not config.host.is_empty() or config.browse or config.team_size > 1): + config.errors.append("--tutorial is played alone and offline: leave out --connect, --browse and --duos") 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/client_session.gd b/src/app/client_session.gd index e43ef27..dde33e4 100644 --- a/src/app/client_session.gd +++ b/src/app/client_session.gd @@ -46,6 +46,11 @@ var _status: Label = null var _fx_seen: int = 0 ## The hit marker and hurt flash (A7). var feedback: HitFeedback = HitFeedback.new() +## The tutorial (A12), when this session is one, its card on the HUD, and the script +## that plays it when nobody is at the keyboard (`input.autoplay`). +var tutorial: Tutorial = null +var tutorial_card: TutorialCard = null +var pilot: TutorialPilot = null func _init() -> void: @@ -66,12 +71,25 @@ func play_offline(match_seed: int, bots: int, rules: MatchRules = null, difficul local = LocalServer.new(match_seed, bots, rules, difficulty) +## Starts the tutorial (A12): an offline match of this player alone, under +## MatchRules.tutorial(), with the tutorial watching. Set `input.autoplay` first for +## the scripted player to play it. +func play_tutorial(match_seed: int) -> void: + local = LocalServer.new(match_seed, 0, MatchRules.tutorial()) + tutorial = Tutorial.new() + tutorial.bindings = settings.bindings + if input.autoplay: + pilot = TutorialPilot.new(tutorial, input) + + ## Takes the player's settings: their keys and mouse now, and graphics for each ## match's view. func use_settings(with: GameSettings) -> void: settings = with input.settings = with.mouse input.bindings = with.bindings + if tutorial != null: + tutorial.bindings = with.bindings if view != null: view.apply_settings(with) @@ -119,6 +137,8 @@ func pump(delta: float) -> void: phases.append(game.match_phase) if game.playing(): frames_playing += 1 + if tutorial != null: + tutorial.update(game, input, delta) mirror.sync(game) _show(delta) @@ -146,6 +166,10 @@ func _ready() -> void: chart.position = Vector2(-300.0, -300.0) chart.visible = false hud.add_child(chart) + if tutorial != null: + tutorial_card = TutorialCard.new() + tutorial_card.position = Vector2(18.0, 204.0) + hud.add_child(tutorial_card) if DisplayServer.get_name() != "headless" and not input.autoplay: Input.mouse_mode = Input.MOUSE_MODE_CAPTURED @@ -165,6 +189,8 @@ func _process(delta: float) -> void: state.hit = feedback.hit() state.hurt = feedback.hurt() hud.show_state(state) + if tutorial_card != null: + tutorial_card.show_tutorial(tutorial, game.playing()) _show_charts(delta) @@ -197,6 +223,8 @@ func _exit_tree() -> void: func _sample(tick: int) -> PlayerCommand: + if pilot != null: + return pilot.command(tick, game) if input.autoplay and game.world != null: return input.autoplay_command(tick, game.prediction.player, game.world.ground) return input.command(tick) diff --git a/src/app/main.gd b/src/app/main.gd index 9cca1ff..b1ee2fd 100644 --- a/src/app/main.gd +++ b/src/app/main.gd @@ -1,7 +1,7 @@ ## Application entry point. Picks the mode from the command line: ## ## tools/godot.sh -- --server [options] headless dedicated server (see ServerConfig) -## tidewall [options] the game: an offline match, or +## tidewall [options] the game: an offline match, the tutorial, or ## tidewall --connect=HOST[:PORT] a match on a server (see ClientConfig) ## tidewall --browse list the servers it can find ## tools/godot.sh -- --list-server a list server (see ListServerRunner) @@ -53,7 +53,9 @@ func _ready() -> void: return _session = ClientSession.new() _session.input.autoplay = _config.autoplay - if _config.host.is_empty(): + if _config.tutorial: + _session.play_tutorial(_config.match_seed if _config.has_seed else int(Time.get_unix_time_from_system() * 1000.0) & 0x7FFFFFFF) + elif _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, LocalServer.offline_rules(_config.bots, _config.team_size)) else: @@ -122,12 +124,15 @@ func _process(delta: float) -> void: for phase: int in _session.phases: phases.append(Match.PHASE_NAMES[phase]) var joined: bool = _session.local != null or _session.link.state == NetClient.JOINED - print(JSON.stringify({ + var report: Dictionary = { "event": "client", "joined": joined, "status": _session.status_text(), "phases": phases, "frames": _session.frames, "frames_playing": _session.frames_playing, "world_messages": _session.game.replica.applied, "bad_packets": _session.game.bad_packets, "corrections": _session.game.prediction.mispredictions, - })) + } + if _session.tutorial != null: + report["tutorial"] = _session.tutorial.step_name() + print(JSON.stringify(report)) _session.leave() _session = null get_tree().quit(0 if joined else 1) diff --git a/src/app/tutorial.gd b/src/app/tutorial.gd new file mode 100644 index 0000000..a84d20c --- /dev/null +++ b/src/app/tutorial.gd @@ -0,0 +1,203 @@ +## The tutorial (A12): a short run through the game on an island of your own. It +## watches the client's own view of the match (ClientGame, the predicted player and +## the FX the server sends) and moves on when each step is done, so it judges what the +## player actually did, through the same door as any match. +## +## The steps: leave the barge, glide down, walk and jump, cut materials with the +## boathook, place a wall, aim and fire the carbine you start with, and get above the +## line the tide will reach. Every instruction names the player's own key bindings. +## +## The match itself is an ordinary offline one under MatchRules.tutorial(): you alone, +## with nobody to end it but the tide. Skip it from the pause menu (Leave) at any time. +class_name Tutorial +extends RefCounted + +const LEAP: int = 0 +const GLIDE: int = 1 +const MOVE: int = 2 +const HARVEST: int = 3 +const BUILD: int = 4 +const FIRE: int = 5 +const TIDE: int = 6 +const DONE: int = 7 +const STEP_NAMES: Array[String] = ["leap", "glide", "move", "harvest", "build", "fire", "tide", "done"] +const TITLES: Array[String] = [ + "Leave the barge", "Glide down", "Find your feet", "Gather materials", + "Build a wall", "Aim and fire", "Beat the tide", "Ready to set out", +] + +## Walk this far from where you landed, and jump once. +const WALK_METRES: float = 12.0 +## Gather at least this much, and enough of one material for a wall. +const HARVEST_GOAL: int = 15 +## Stand this far above the tide line, on the ground, for this long. +const TIDE_MARGIN_METRES: float = 1.0 +const TIDE_HOLD_SECONDS: float = 2.0 + +var step: int = LEAP +## Seconds spent on each step, by index, for the scripted check's report. +var step_seconds: PackedFloat32Array = PackedFloat32Array() +var bindings: KeyBindings = KeyBindings.new() + +var _landed_at: Vector3 = Vector3.ZERO +var _walked: float = 0.0 +var _jumped: bool = false +var _was_on_ground: bool = true +var _gathered_from: int = -1 +var _gathered: int = 0 +var _fx_seen: int = 0 +var _chart_opened: bool = false +var _feet: float = NAN +var _tide_line: float = NAN +var _held_dry: float = 0.0 + + +func _init() -> void: + step_seconds.resize(STEP_NAMES.size()) + + +func finished() -> bool: + return step == DONE + + +func step_name() -> String: + return STEP_NAMES[step] + + +## Looks at the match as this client sees it, once a frame, and moves on when the +## step is done. `input` says whether the chart is open. +func update(game: ClientGame, input: ClientInput, delta: float) -> void: + step_seconds[step] += delta + var fresh: Array[Dictionary] = _fresh_fx(game) + if step == DONE or not game.playing(): + return + var me: SimEntity = game.prediction.player + match step: + LEAP: + if me.drop_state != Drop.ABOARD: + _advance() + GLIDE: + if me.drop_state == Drop.NONE: + _landed_at = me.position + _was_on_ground = me.on_ground + _advance() + MOVE: + _walked = maxf(_walked, Vector2(me.position.x - _landed_at.x, me.position.z - _landed_at.z).length()) + if _was_on_ground and not me.on_ground and me.velocity.y > 0.5 and not me.swimming: + _jumped = true + _was_on_ground = me.on_ground + if _walked >= WALK_METRES and _jumped: + _advance() + HARVEST: + var total: int = _total(me.materials) + if _gathered_from < 0: + _gathered_from = total + _gathered = maxi(total - _gathered_from, _gathered) + if _gathered >= HARVEST_GOAL and _most(me.materials) >= StructureSet.cost_of(StructureSet.WALL): + _advance() + BUILD: + for record: Dictionary in fresh: + if int(record["kind"]) == NetFx.PLACE and int(record["player"]) == me.id: + _advance() + break + FIRE: + for record: Dictionary in fresh: + if int(record["kind"]) == NetFx.IMPACT and int(record["player"]) == me.id \ + and int(record.get("item", -1)) >= 0 and int(record.get("item", -1)) != ItemCatalog.boathook().code \ + and int(record.get("hit", Weapons.HIT_NONE)) != Weapons.HIT_NONE: + _advance() + break + TIDE: + if input.map_open: + _chart_opened = true + _tide_line = tide_line(game.world.tide, game.world.tick) + _feet = me.position.y + var dry: bool = me.on_ground and not me.swimming and _feet >= _tide_line + TIDE_MARGIN_METRES + _held_dry = _held_dry + delta if dry else 0.0 + if _chart_opened and _held_dry >= TIDE_HOLD_SECONDS: + _advance() + + +## The level the tide will reach after the next rise: where you must stand to be safe +## for a while. Past the last phase, the last level. +static func tide_line(tide: Tide, tick: int) -> float: + var phase: int = mini(tide.phase_at(tick) + 1, Tide.phase_count() - 1) + return tide.levels[phase] + + +## What to do now, naming the player's keys. +func instruction() -> String: + match step: + LEAP: + return "You're aboard the barge, high over the island. When it's over land, press %s to leap." % _key("jump") + GLIDE: + return "Steer with %s %s %s %s as you fall. Press %s to open your sail, or it opens by itself near the ground. Aim for open ground." % [ + _key("forward"), _key("left"), _key("back"), _key("right"), _key("jump")] + MOVE: + return "Walk with %s %s %s %s and look with the mouse. Hold %s to sprint, press %s to jump." % [ + _key("forward"), _key("left"), _key("back"), _key("right"), _key("sprint"), _key("jump")] + HARVEST: + return "Press %s for the boathook. Walk up to driftwood, a rock or scrap and press %s to cut it." % [_key("slot_0"), _key("fire")] + BUILD: + return "Press %s for build mode. %s picks the wall, %s the material, and %s places it. %s again leaves build mode." % [ + _key("build"), _key("slot_0"), _key("material"), _key("fire"), _key("build")] + FIRE: + return "You carry a dock carbine. Press %s to hold it, hold %s to aim down the sights and press %s to fire at a rock, a tree or your wall. %s reloads." % [ + _key("slot_1"), _key("aim"), _key("fire"), _key("reload")] + TIDE: + return "The sea rises in stages and drowns whoever it catches. Press %s to open the chart and see the tide's next line, then climb above where it will reach after that." % _key("map") + _: + return "That's the whole of it. Others carry weapons too, and chests and crates hold more (%s opens and picks up). Press Escape and leave when you're ready, or stay and look around." % _key("interact") + + +## How far along the step is, or "" when there is nothing to count. +func progress() -> String: + match step: + MOVE: + return "Walked %d of %d m%s" % [mini(floori(_walked), int(WALK_METRES)), int(WALK_METRES), " · jumped" if _jumped else " · jump once"] + HARVEST: + return "Gathered %d of %d" % [mini(_gathered, HARVEST_GOAL), HARVEST_GOAL] + TIDE: + if is_nan(_tide_line): + return "" + var chart: String = "chart opened" if _chart_opened else "open the chart" + return "Your feet %.0f m · safe above %.0f m · %s" % [_feet, _tide_line + TIDE_MARGIN_METRES, chart] + return "" + + +## "Step N of M", counting the steps a player does. +func counter() -> String: + if step == DONE: + return "Tutorial complete" + return "Step %d of %d" % [step + 1, DONE] + + +func _advance() -> void: + step += 1 + + +func _key(action: String) -> String: + return "[%s]" % KeyBindings.describe(bindings.code_of(action)) + + +func _fresh_fx(game: ClientGame) -> Array[Dictionary]: + var fresh: int = mini(game.fx_received - _fx_seen, game.fx.size()) + _fx_seen = game.fx_received + var records: Array[Dictionary] = [] + if fresh > 0: + records = game.fx.slice(game.fx.size() - fresh) + return records + + +static func _total(carried: PackedInt32Array) -> int: + var sum: int = 0 + for amount: int in carried: + sum += amount + return sum + + +static func _most(carried: PackedInt32Array) -> int: + var best: int = 0 + for amount: int in carried: + best = maxi(best, amount) + return best diff --git a/src/app/tutorial.gd.uid b/src/app/tutorial.gd.uid new file mode 100644 index 0000000..ac2fcad --- /dev/null +++ b/src/app/tutorial.gd.uid @@ -0,0 +1 @@ +uid://ohf3eudp270x diff --git a/src/app/tutorial_pilot.gd b/src/app/tutorial_pilot.gd new file mode 100644 index 0000000..40b0525 --- /dev/null +++ b/src/app/tutorial_pilot.gd @@ -0,0 +1,297 @@ +## A scripted player for the tutorial (A12): it plays each step the way a person at the +## keyboard would, through ClientInput (the keys it holds, the actions it presses and +## where it looks), so a headless run proves the tutorial can be finished from start +## to end with the game's real controls. `--tutorial --autoplay` uses it, and so do the +## tests and `make tutorial-check`. +## +## It knows only what the client knows: its own predicted player and the client's copy +## of the world. +class_name TutorialPilot +extends RefCounted + +const TICKS: int = Tuning.TICK_RATE_HZ +## Looks for something to cut or shoot this far away. +const SEARCH_METRES: float = 60.0 +## Gives up on a target it makes no headway towards for this long. +const STUCK_SECONDS: float = 6.0 +## Fires from no farther than this. +const FIRE_METRES: float = 20.0 +## Climbs to ground at least this far above the tide line. +const CLIMB_MARGIN_METRES: float = 3.0 + +var tutorial: Tutorial +var input: ClientInput + +var _target: int = -1 +var _skipped: Dictionary = {} +var _goal: Vector3 = Vector3.INF +var _bad_goals: Array[Vector3] = [] +var _progress_at: Vector3 = Vector3.INF +var _progress_tick: int = 0 +var _best_distance: float = INF +var _build_turns: int = 0 +var _build_tick: int = -1 +var _map_tick: int = -1 +var _walk_yaw: float = 0.0 + + +func _init(for_tutorial: Tutorial, with_input: ClientInput) -> void: + tutorial = for_tutorial + input = with_input + + +## The command for `tick`, made by setting the input as a player's hands would. +func command(tick: int, game: ClientGame) -> PlayerCommand: + input.move = Vector2.ZERO + input.buttons = 0 + if game.world == null or not game.playing(): + return input.command(tick) + var me: SimEntity = game.prediction.player + var world: Simulation = game.world + if tutorial.step != Tutorial.BUILD and input.build_mode: + input.act("build") + match tutorial.step: + Tutorial.LEAP: + _face_centre(me) + if tick > 3 * TICKS and world.ground.terrain_height(me.position.x, me.position.z) > Tuning.ISLAND_BEACH_TOP + 4.0: + input.buttons = PlayerCommand.BUTTON_JUMP + Tutorial.GLIDE: + _face_centre(me) + input.move = Vector2(0.0, 1.0) + Tutorial.MOVE: + input.yaw = _walk_yaw + input.pitch = 0.0 + input.move = Vector2(0.0, 1.0) + if tick % (2 * TICKS) == 0: + input.buttons = PlayerCommand.BUTTON_JUMP + if _stuck(tick, me): + _walk_yaw += PI * 0.5 + Tutorial.HARVEST: + _harvest(tick, me, world) + Tutorial.BUILD: + _build(tick, me) + Tutorial.FIRE: + _fire(tick, me, world) + Tutorial.TIDE: + _climb(tick, me, world) + return input.command(tick) + + +func _face_centre(me: SimEntity) -> void: + var centre: float = Tuning.WORLD_SIZE_METRES * 0.5 + input.yaw = atan2(centre - me.position.x, centre - me.position.z) + input.pitch = deg_to_rad(-12.0) + + +## Selects slot `number` (0 the boathook) as the number key would. +func _hold_slot(number: int) -> void: + if input.slot != number: + input.act("slot_%d" % number) + + +## Walks up to the nearest standing prop and swings the boathook at it. +func _harvest(tick: int, me: SimEntity, world: Simulation) -> void: + _hold_slot(0) + if _target < 0 or not world.props.is_standing(_target): + _target = _nearest_prop(me, world) + _reset_progress(tick, me) + if _target < 0: + _wander(tick, me) + return + var box: AABB = world.props.boxes[_target] + var eye: Vector3 = Harvest.eye(me) + var centre: Vector3 = box.get_center() + var aim: Vector3 = Vector3(centre.x, clampf(eye.y, box.position.y + 0.2, box.end.y - 0.1), centre.z) + _look_at(eye, aim) + if PropSet._distance_to_box(box, eye) <= Harvest.reach() - 0.6: + input.buttons = PlayerCommand.BUTTON_FIRE + _reset_progress(tick, me) + return + input.pitch = 0.0 + input.move = Vector2(0.0, 1.0) + if tick % (2 * TICKS) == TICKS: + input.buttons = PlayerCommand.BUTTON_JUMP + if _stuck(tick, me, PropSet._distance_to_box(box, me.position)): + _skipped[_target] = true + _target = -1 + + +## Build mode, the wall, the material it has most of, and a press of fire; a quarter +## turn after each try that places nothing. +func _build(tick: int, me: SimEntity) -> void: + if not input.build_mode: + input.act("build") + if input.build_kind != StructureSet.WALL: + input.act("slot_%d" % StructureSet.WALL) + var best: int = 0 + for index: int in me.materials.size(): + if me.materials[index] > me.materials[best]: + best = index + if input.material != best: + input.act("material") + return + input.pitch = 0.0 + if _build_tick < 0: + _build_tick = tick + input.yaw = float(me.yaw) / PlayerCommand.YAW_STEPS * TAU + var since: int = tick - _build_tick + if since % TICKS == 0 and since > 0: + _build_turns += 1 + input.yaw += PI * 0.5 + if _build_turns % 4 == 0: + # No room here: step aside and try again. + input.move = Vector2(1.0, 0.0) + # Half a second to look at the ghost, then a press of fire, each try. + var phase: int = since % TICKS + if phase >= TICKS / 2 and phase < TICKS / 2 + 3: + input.buttons = PlayerCommand.BUTTON_FIRE + elif phase > TICKS / 2 + 3 and _build_turns % 4 == 0 and _build_turns > 0: + input.move = Vector2(1.0, 0.0) + + +## The carbine, aimed down the sights at the nearest prop in range, fired in taps. +func _fire(tick: int, me: SimEntity, world: Simulation) -> void: + _hold_slot(1) + if _target < 0 or not world.props.is_standing(_target): + _target = _nearest_prop(me, world) + _reset_progress(tick, me) + if _target < 0: + _wander(tick, me) + return + var box: AABB = world.props.boxes[_target] + var eye: Vector3 = Harvest.eye(me) + var centre: Vector3 = box.get_center() + _look_at(eye, Vector3(centre.x, clampf(eye.y, box.position.y + 0.3, box.end.y - 0.2), centre.z)) + if eye.distance_to(centre) <= FIRE_METRES: + input.buttons = PlayerCommand.BUTTON_AIM + if tick % 10 < 2: + input.buttons |= PlayerCommand.BUTTON_FIRE + if tick % (3 * TICKS) == 0 and tick > 0: + # A miss or a blocked line: try the next one. + _skipped[_target] = true + _target = -1 + return + input.pitch = 0.0 + input.move = Vector2(0.0, 1.0) + if _stuck(tick, me, eye.distance_to(centre)): + _skipped[_target] = true + _target = -1 + + +## Opens the chart for a moment, closes it, then walks to the nearest ground well above +## the tide line it must beat. +func _climb(tick: int, me: SimEntity, world: Simulation) -> void: + if _map_tick < 0: + _map_tick = tick + if not input.map_open: + input.act("map") + return + if input.map_open: + if tick - _map_tick >= TICKS: + input.act("map") + return + var line: float = Tutorial.tide_line(world.tide, world.tick) + Tutorial.TIDE_MARGIN_METRES + if me.position.y >= line + 0.5 and me.on_ground: + return + if _goal == Vector3.INF: + _goal = _high_ground(me, world, line + CLIMB_MARGIN_METRES) + _reset_progress(tick, me) + if _goal == Vector3.INF: + _wander(tick, me) + return + input.yaw = atan2(_goal.x - me.position.x, _goal.z - me.position.z) + input.pitch = 0.0 + input.move = Vector2(0.0, 1.0) + if tick % TICKS == 0: + input.buttons = PlayerCommand.BUTTON_JUMP | PlayerCommand.BUTTON_SPRINT + else: + input.buttons = PlayerCommand.BUTTON_SPRINT + var flat: float = Vector2(_goal.x - me.position.x, _goal.z - me.position.z).length() + if _stuck(tick, me, flat): + _bad_goals.append(_goal) + _goal = Vector3.INF + + +## The nearest point of the terrain at least `height` up, from rings around the player, +## leaving out goals already given up on. +func _high_ground(me: SimEntity, world: Simulation, height: float) -> Vector3: + for ring: int in range(1, 40): + var radius: float = float(ring) * 6.0 + var points: int = 8 + ring * 2 + for index: int in points: + var angle: float = TAU * float(index) / float(points) + var x: float = me.position.x + sin(angle) * radius + var z: float = me.position.z + cos(angle) * radius + if x < 0.0 or z < 0.0 or x > Tuning.WORLD_SIZE_METRES or z > Tuning.WORLD_SIZE_METRES: + continue + var y: float = world.ground.terrain_height(x, z) + if y < height: + continue + var spot: Vector3 = Vector3(x, y, z) + var refused: bool = false + for bad: Vector3 in _bad_goals: + if Vector2(bad.x - x, bad.z - z).length() < 15.0: + refused = true + if not refused: + return spot + return Vector3.INF + + +func _nearest_prop(me: SimEntity, world: Simulation) -> int: + var best: int = -1 + var best_distance: float = INF + for prop: int in world.props.near(me.position, SEARCH_METRES): + if _skipped.has(prop) or not world.props.is_standing(prop): + continue + var box: AABB = world.props.boxes[prop] + if box.position.y < world.sea_level + 0.5 or absf(box.position.y - me.position.y) > 6.0: + continue + var distance: float = PropSet._distance_to_box(box, me.position) + if distance < best_distance: + best_distance = distance + best = prop + return best + + +func _look_at(eye: Vector3, point: Vector3) -> void: + var to: Vector3 = point - eye + input.yaw = atan2(to.x, to.z) + input.pitch = atan2(to.y, Vector2(to.x, to.z).length()) + + +## Walks on in some direction when there's nothing near to go to. +func _wander(tick: int, me: SimEntity) -> void: + input.yaw = _walk_yaw + input.pitch = 0.0 + input.move = Vector2(0.0, 1.0) + if tick % (2 * TICKS) == 0: + input.buttons = PlayerCommand.BUTTON_JUMP + if _stuck(tick, me): + _walk_yaw += PI * 0.5 + + +func _reset_progress(tick: int, me: SimEntity) -> void: + _progress_at = me.position + _progress_tick = tick + _best_distance = INF + + +## True, once, after STUCK_SECONDS without headway: closer to the target by a metre +## when `distance` is given, else a few metres from where it was. +func _stuck(tick: int, me: SimEntity, distance: float = -1.0) -> bool: + if _progress_at == Vector3.INF: + _reset_progress(tick, me) + var moved: bool + if distance >= 0.0: + moved = distance < _best_distance - 1.0 + if moved: + _best_distance = distance + else: + moved = me.position.distance_to(_progress_at) > 3.0 + if moved: + _progress_at = me.position + _progress_tick = tick + elif tick - _progress_tick > roundi(STUCK_SECONDS * TICKS): + _reset_progress(tick, me) + return true + return false diff --git a/src/app/tutorial_pilot.gd.uid b/src/app/tutorial_pilot.gd.uid new file mode 100644 index 0000000..12b72d8 --- /dev/null +++ b/src/app/tutorial_pilot.gd.uid @@ -0,0 +1 @@ +uid://bbs8nxm0k8fed diff --git a/src/client/game_settings.gd b/src/client/game_settings.gd index 84f48e8..146796a 100644 --- a/src/client/game_settings.gd +++ b/src/client/game_settings.gd @@ -75,6 +75,9 @@ var practice_difficulty: int = -1: var practice_team_size: int = 1: set(value): practice_team_size = clampi(value, 1, Tuning.DUO_TEAM_SIZE) +## The tutorial (A12): offered on the first launch until answered, and finished once. +var tutorial_offered: bool = false +var tutorial_done: bool = false func shadow_distance() -> float: @@ -123,6 +126,8 @@ func save(path: String = DEFAULT_PATH) -> Error: config.set_value("practice", "bots", practice_bots) config.set_value("practice", "difficulty", practice_difficulty) config.set_value("practice", "team_size", practice_team_size) + config.set_value("tutorial", "offered", tutorial_offered) + config.set_value("tutorial", "done", tutorial_done) return config.save(path) @@ -150,6 +155,8 @@ static func load_from(path: String = DEFAULT_PATH) -> GameSettings: 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) + settings.tutorial_offered = _bool(config, "tutorial", "offered", settings.tutorial_offered) + settings.tutorial_done = _bool(config, "tutorial", "done", settings.tutorial_done) return settings diff --git a/src/client/hud/tutorial_card.gd b/src/client/hud/tutorial_card.gd new file mode 100644 index 0000000..8704337 --- /dev/null +++ b/src/client/hud/tutorial_card.gd @@ -0,0 +1,62 @@ +## The tutorial's card on the HUD (A12): a paper card under the minimap with the step +## counter, the step's title, what to do (naming the player's own keys) and how far +## along it is. Hidden until the player is in the match. Drawn like the HUD's other +## cards (Hud.draw_card); everything is words, so nothing relies on colour. +class_name TutorialCard +extends Control + +const WIDTH: float = 340.0 +const PADDING: float = 14.0 + +var _counter: Label +var _title: Label +var _body: Label +var _progress: Label +var _column: VBoxContainer + + +func _init() -> void: + name = "TutorialCard" + mouse_filter = Control.MOUSE_FILTER_IGNORE + _column = VBoxContainer.new() + _column.position = Vector2(PADDING, PADDING * 0.7) + _column.add_theme_constant_override("separation", 4) + _column.mouse_filter = Control.MOUSE_FILTER_IGNORE + add_child(_column) + _counter = _ink(Hud.FONT_SMALL, Palette.SEA_INK) + _title = _ink(Hud.FONT_TITLE, Palette.INK) + _body = _ink(Hud.FONT_BODY, Palette.INK) + _body.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + _body.custom_minimum_size = Vector2(WIDTH - PADDING * 2.0, 0.0) + _progress = _ink(Hud.FONT_SMALL, Palette.OCHRE_RED) + for label: Label in [_counter, _title, _body, _progress]: + _column.add_child(label) + visible = false + + +## Shows `tutorial`'s step, or hides the card while the player isn't in the match. +func show_tutorial(tutorial: Tutorial, playing: bool) -> void: + visible = tutorial != null and playing + if not visible: + return + _counter.text = tutorial.counter().to_upper() + _title.text = Tutorial.TITLES[tutorial.step] + _body.text = tutorial.instruction() + _progress.text = tutorial.progress() + _progress.visible = not _progress.text.is_empty() + var height: float = _column.get_combined_minimum_size().y + PADDING * 1.4 + if not size.is_equal_approx(Vector2(WIDTH, height)): + size = Vector2(WIDTH, height) + queue_redraw() + + +func _draw() -> void: + Hud.draw_card(self, Rect2(Vector2.ZERO, size)) + + +func _ink(font_size: int, colour: Color) -> Label: + var label: Label = Label.new() + label.add_theme_font_size_override("font_size", font_size) + label.add_theme_color_override("font_color", colour) + label.mouse_filter = Control.MOUSE_FILTER_IGNORE + return label diff --git a/src/client/hud/tutorial_card.gd.uid b/src/client/hud/tutorial_card.gd.uid new file mode 100644 index 0000000..b1bf925 --- /dev/null +++ b/src/client/hud/tutorial_card.gd.uid @@ -0,0 +1 @@ +uid://dimljb3jidhs8 diff --git a/src/server/command_log.gd b/src/server/command_log.gd index f32ee81..e4f0f85 100644 --- a/src/server/command_log.gd +++ b/src/server/command_log.gd @@ -20,7 +20,12 @@ const RECORD_SIZE: int = 8 + PlayerCommand.ENCODED_SIZE const MAX_RAW_BYTES: int = 64 * 1024 * 1024 const RULE_KEYS: Array[String] = [ "max_players", "min_players", "team_size", "lobby_ticks", "countdown_ticks", "results_ticks", "fill_with_bots", + "last_team_wins", "starting_kit", ] +## Rules added after logs were first written (A12): a log without them takes the default. +const OPTIONAL_RULE_KEYS: Array[String] = ["last_team_wins", "starting_kit"] +## Rules that are booleans. +const BOOL_RULE_KEYS: Array[String] = ["fill_with_bots", "last_team_wins", "starting_kit"] var session_seed: int = 0 ## Human participants, who join with handles 1 and up before the first tick. @@ -139,10 +144,12 @@ static func from_bytes(bytes: PackedByteArray) -> CommandLog: for key: String in RULE_KEYS: # A hand-edited or damaged file could hold any JSON here; int() of an array or # a dictionary is an error, so only numbers and booleans are read (H5). + if not rule_values.has(key) and OPTIONAL_RULE_KEYS.has(key): + continue if not rule_values.has(key) or not _is_number(rule_values[key]): return null - if key == "fill_with_bots": - result.rules.fill_with_bots = bool(rule_values[key]) + if BOOL_RULE_KEYS.has(key): + result.rules.set(key, bool(rule_values[key])) else: result.rules.set(key, int(rule_values[key])) result.rules.max_players = clampi(result.rules.max_players, 1, Tuning.SOLO_PLAYERS) diff --git a/src/sim/match.gd b/src/sim/match.gd index dd91b9f..2beec06 100644 --- a/src/sim/match.gd +++ b/src/sim/match.gd @@ -254,6 +254,8 @@ func _start() -> void: handle_of[entity_id] = handle team_of[handle] = index / size sim.set_team(entity_id, index / size) + if rules.starting_kit: + _give_kit(sim.entities.find(entity_id)) stats[handle] = {"eliminations": 0, "damage_dealt": 0, "damage_taken": 0} _match_size = participants.size() _roster = participants.duplicate() @@ -266,6 +268,13 @@ func _start() -> void: _check_finished() +## Tuning.TUTORIAL_KIT: a weapon with a full magazine and spare ammunition. +static func _give_kit(player: SimEntity) -> void: + var weapon: int = ItemCatalog.code_of(String(Tuning.TUTORIAL_KIT["weapon"])) + Inventory.give(player, weapon, 1) + Inventory.give(player, ItemCatalog.code_of(String(Tuning.TUTORIAL_KIT["ammo"])), int(Tuning.TUTORIAL_KIT["spare"])) + + ## Adds up damage between opponents and remembers each victim's last weapon. func _collect_damage() -> void: for event: Dictionary in sim.events: @@ -358,7 +367,9 @@ func _check_finished() -> void: for handle: int in living: teams[team_of[handle]] = true var timed_out: bool = sim.tide != null and sim.tide.stage_at(sim.tick) == Tide.OVER - if teams.size() > 1 and not timed_out: + # Without last_team_wins (the tutorial), one team standing plays on. + var enough: int = 1 if rules.last_team_wins else 0 + if teams.size() > enough and not timed_out: return winners.clear() if teams.size() >= 1: diff --git a/src/sim/match_rules.gd b/src/sim/match_rules.gd index f153b1d..a97e43f 100644 --- a/src/sim/match_rules.gd +++ b/src/sim/match_rules.gd @@ -16,6 +16,11 @@ var countdown_ticks: int = roundi(Tuning.MATCH_COUNTDOWN_SECONDS * Tuning.TICK_R var results_ticks: int = roundi(Tuning.MATCH_RESULTS_SECONDS * Tuning.TICK_RATE_HZ) ## Fill empty places with bots when the match starts. var fill_with_bots: bool = true +## The match ends when one team is left standing. The tutorial (A12) turns this off, +## so a player alone on the island plays on until the tide ends it. +var last_team_wins: bool = true +## Every player starts with Tuning.TUTORIAL_KIT in hand (A12). +var starting_kit: bool = false ## Rules for a server that skips the lobby: the match starts on the first tick. @@ -24,3 +29,15 @@ static func immediate() -> MatchRules: rules.lobby_ticks = 0 rules.countdown_ticks = 0 return rules + + +## Rules for the tutorial (A12): one player alone, straight onto the barge, with a +## weapon to learn on, and no ending until the tide's own. +static func tutorial() -> MatchRules: + var rules: MatchRules = MatchRules.immediate() + rules.max_players = 1 + rules.min_players = 1 + rules.fill_with_bots = false + rules.last_team_wins = false + rules.starting_kit = true + return rules diff --git a/src/sim/tuning.gd b/src/sim/tuning.gd index e409e19..44fa03c 100644 --- a/src/sim/tuning.gd +++ b/src/sim/tuning.gd @@ -56,6 +56,9 @@ const NET_CORRECTION_SNAP_METRES: float = 3.0 const SOLO_PLAYERS: int = 24 const DUO_TEAMS: int = 12 const DUO_TEAM_SIZE: int = 2 +## The tutorial (A12) starts its player with this weapon, its magazine full, and this +## much spare ammunition of its kind, to learn aiming and reloading on. +const TUTORIAL_KIT: Dictionary = {"weapon": "dock_carbine", "ammo": "cartridges", "spare": 60} const REVIVE_SECONDS: float = 6.0 # Duos: downed, revive and bleed-out (M7). See Simulation. diff --git a/src/ui/menus.gd b/src/ui/menus.gd index 56cfd23..ad00aff 100644 --- a/src/ui/menus.gd +++ b/src/ui/menus.gd @@ -1,5 +1,5 @@ -## The game's menus (A10), in the paper-and-ink motifs of docs/STYLE.md: the main menu, -## practice against bots, joining a server (with the LAN and list-server browser), +## The game's menus (A10), in the paper-and-ink motifs of docs/STYLE.md: the welcome +## that offers the tutorial on the first launch (A12), the main menu, practice against bots, joining a server (with the LAN and list-server browser), ## settings (controls, mouse, graphics, audio, display), the pause menu and the results. ## ## Menus only edit `settings` and say what the player asked for through signals; the @@ -10,13 +10,14 @@ class_name Menus extends Control signal practice_requested(bots: int, difficulty: int, team_size: int) +signal tutorial_requested signal join_requested(host: String, port: int, player_name: String) signal resume_requested signal leave_requested signal quit_requested signal settings_changed -const SCREENS: Array[String] = ["main", "practice", "join", "settings", "pause", "results"] +const SCREENS: Array[String] = ["welcome", "main", "practice", "join", "settings", "pause", "results"] const PANEL_WIDTH: float = 560.0 const FONT_TITLE: int = 40 const FONT_HEADING: int = 24 @@ -89,6 +90,7 @@ func _init() -> void: shade.mouse_filter = Control.MOUSE_FILTER_IGNORE shade.visible = false add_child(shade) + _build_welcome() _build_main() _build_practice() _build_join() @@ -337,6 +339,7 @@ func _build_main() -> void: notice.add_theme_color_override("font_color", Palette.OCHRE_RED) column.add_child(notice) _button(column, "Practice against bots", func() -> void: show_screen("practice")) + _button(column, "Tutorial", _start_tutorial) _button(column, "Join a server", func() -> void: show_screen("join")) _button(column, "Settings", func() -> void: show_screen("settings")) _button(column, "Quit", func() -> void: quit_requested.emit()) @@ -349,6 +352,28 @@ func _build_main() -> void: column.add_child(build) +## The first launch (A12): the tutorial, or straight on. Either answer is remembered, +## and the tutorial stays on the main menu. +func _build_welcome() -> void: + var column: VBoxContainer = _panel("welcome", "Welcome aboard") + var note: Label = _note(column) + note.text = "New to Tidewall? A short tutorial on an island of your own shows you how to drop, gather, build, fight and keep ahead of the tide. It takes a few minutes, and you can leave it whenever you like from the pause menu." + _button(column, "Start the tutorial", _start_tutorial) + _button(column, "Not now", func() -> void: + settings.tutorial_offered = true + save_settings() + show_screen("main", false)) + var later: Label = _note(column) + later.text = "The tutorial is always on the main menu." + later.modulate.a = 0.7 + + +func _start_tutorial() -> void: + settings.tutorial_offered = true + save_settings() + tutorial_requested.emit() + + func _build_practice() -> void: var column: VBoxContainer = _panel("practice", "Practice") _bots = SpinBox.new() diff --git a/test/app/test_tutorial.gd b/test/app/test_tutorial.gd new file mode 100644 index 0000000..1c5ad1b --- /dev/null +++ b/test/app/test_tutorial.gd @@ -0,0 +1,201 @@ +extends TestCase + +## A12: the tutorial. A match alone that only the tide ends, with a weapon to learn on; +## steps that judge what the player did from the client's own view; instructions that +## name the player's own keys; a scripted player that finishes it; and the menus that +## offer it on the first launch and keep it on the main menu. + +const PATH: String = "user://test_tutorial_settings.cfg" +const DT: float = 1.0 / Tuning.TICK_RATE_HZ + + +func after_each() -> void: + super.after_each() + DirAccess.remove_absolute(ProjectSettings.globalize_path(PATH)) + + +func test_a_tutorial_match_alone_plays_on_and_starts_with_the_kit() -> void: + var loop: ServerLoop = ServerLoop.new(5, 1, 0, MatchRules.tutorial()) + var flow: Match = loop.match_flow + for _tick: int in 3: + loop.run_tick() + assert_true(flow.in_match(), "one player alone isn't the last one standing in the tutorial") + var me: SimEntity = flow.sim.entities.find(int(flow.entity_of[flow.participants[0]])) + var weapon: int = ItemCatalog.code_of(String(Tuning.TUTORIAL_KIT["weapon"])) + assert_eq(Inventory.count_of(me, weapon), 1, "carries the kit's weapon") + assert_true(me.slot_rounds[0] > 0, "loaded") + assert_eq(Inventory.count_of(me, ItemCatalog.code_of(String(Tuning.TUTORIAL_KIT["ammo"]))), int(Tuning.TUTORIAL_KIT["spare"])) + for _tick: int in 20 * Tuning.TICK_RATE_HZ: + loop.run_tick() + assert_true(flow.in_match(), "still playing twenty seconds on") + + +func test_ordinary_rules_still_end_a_match_with_one_team_left() -> void: + var rules: MatchRules = MatchRules.immediate() + rules.max_players = 1 + rules.min_players = 1 + rules.fill_with_bots = false + var loop: ServerLoop = ServerLoop.new(5, 1, 0, rules) + for _tick: int in 3: + loop.run_tick() + assert_eq(loop.match_flow.phase, Match.RESULTS, "alone under the usual rules is a win at once") + assert_eq(loop.match_flow.winners.size(), 1) + + +func test_the_tutorial_ends_when_its_player_falls() -> void: + var loop: ServerLoop = ServerLoop.new(5, 1, 0, MatchRules.tutorial()) + var flow: Match = loop.match_flow + for _tick: int in 3: + loop.run_tick() + assert_true(flow.in_match()) + flow.leave(int(flow.participants[0])) + loop.run_tick() + assert_false(flow.in_match(), "nobody left standing ends it") + + +func test_instructions_name_the_players_own_keys() -> void: + var tutorial: Tutorial = Tutorial.new() + assert_true(tutorial.instruction().contains("[Space]"), tutorial.instruction()) + var keys: KeyBindings = KeyBindings.new() + assert_eq(keys.bind("jump", KEY_J), "") + tutorial.bindings = keys + assert_true(tutorial.instruction().contains("[J]"), "rebound jump shows: " + tutorial.instruction()) + for step: int in Tutorial.STEP_NAMES.size(): + tutorial.step = step + assert_false(tutorial.instruction().is_empty(), "step %s says what to do" % Tutorial.STEP_NAMES[step]) + assert_false(tutorial.instruction().contains("%"), "no unfilled format in %s" % Tutorial.STEP_NAMES[step]) + assert_eq(tutorial.counter(), "Tutorial complete") + + +func test_the_scripted_player_finishes_the_tutorial_through_the_client() -> void: + var result: Dictionary = preload("res://tools/tutorial_check.gd").play(3, 300.0) + assert_true(bool(result["finished"]), "finished: %s" % result) + for step: String in ["leap", "glide", "move", "harvest", "build", "fire", "tide"]: + assert_true(float(result["steps"][step]) > 0.0, "%s took some time: %s" % [step, result]) + + +func test_steps_wait_for_the_player_to_act() -> void: + var session: ClientSession = ClientSession.new() + session.play_tutorial(3) + # Nobody at the keys: the barge flies on, and the tutorial waits on its first step + # until the barge throws everyone off at the end of its route. + for _frame: int in 3 * Tuning.TICK_RATE_HZ: + session.pump(DT) + assert_true(session.game.playing()) + assert_eq(session.tutorial.step, Tutorial.LEAP) + assert_eq(session.game.prediction.player.drop_state, Drop.ABOARD) + session.free() + + +func test_settings_remember_the_offer_and_the_finish() -> void: + var settings: GameSettings = GameSettings.new() + assert_false(settings.tutorial_offered) + assert_false(settings.tutorial_done) + settings.tutorial_offered = true + settings.tutorial_done = true + assert_eq(settings.save(PATH), OK) + var loaded: GameSettings = GameSettings.load_from(PATH) + assert_true(loaded.tutorial_offered) + assert_true(loaded.tutorial_done) + + +func test_the_first_launch_offers_it_and_not_now_is_remembered() -> void: + var tree: SceneTree = Engine.get_main_loop() as SceneTree + var shell: AppShell = AppShell.new(GameSettings.new(), PATH) + shell.grab_mouse = false + tree.root.add_child(shell) + assert_eq(shell.menus.current, "welcome") + (shell.menus.buttons_of("welcome")["Not now"] as Button).pressed.emit() + assert_eq(shell.menus.current, "main") + assert_null(shell.session) + assert_true(GameSettings.load_from(PATH).tutorial_offered, "saved") + shell.free() + var again: AppShell = AppShell.new(GameSettings.load_from(PATH), PATH) + again.grab_mouse = false + tree.root.add_child(again) + assert_eq(again.menus.current, "main", "not offered twice") + again.free() + + +func test_the_tutorial_starts_from_the_welcome_and_the_main_menu() -> void: + var tree: SceneTree = Engine.get_main_loop() as SceneTree + for pair: Array in [["welcome", "Start the tutorial"], ["main", "Tutorial"]]: + var settings: GameSettings = GameSettings.new() + settings.tutorial_offered = pair[0] == "main" + var shell: AppShell = AppShell.new(settings, PATH) + shell.grab_mouse = false + tree.root.add_child(shell) + assert_eq(shell.menus.current, pair[0]) + var buttons: Dictionary = shell.menus.buttons_of(pair[0]) + assert_true(buttons.has(pair[1]), "%s has '%s'" % pair) + (buttons[pair[1]] as Button).pressed.emit() + assert_not_null(shell.session, "a tutorial began from %s" % pair[0]) + assert_not_null(shell.session.tutorial) + assert_not_null(shell.session.local, "offline") + assert_true(settings.tutorial_offered) + assert_false(shell.menus.visible) + shell.leave() + assert_eq(shell.menus.current, "main", "Leave skips it, back to the main menu") + shell.free() + + +func test_finishing_is_saved() -> void: + var tree: SceneTree = Engine.get_main_loop() as SceneTree + var settings: GameSettings = GameSettings.new() + settings.tutorial_offered = true + var shell: AppShell = AppShell.new(settings, PATH) + shell.grab_mouse = false + tree.root.add_child(shell) + shell.start_tutorial() + shell.session.tutorial.step = Tutorial.DONE + shell.watch_tutorial() + assert_true(GameSettings.load_from(PATH).tutorial_done) + shell.free() + + +func test_the_card_shows_the_step_once_playing() -> void: + var card: TutorialCard = TutorialCard.new() + (Engine.get_main_loop() as SceneTree).root.add_child(card) + var tutorial: Tutorial = Tutorial.new() + card.show_tutorial(tutorial, false) + assert_false(card.visible, "hidden before the match") + tutorial.step = Tutorial.BUILD + card.show_tutorial(tutorial, true) + assert_true(card.visible) + assert_true(card.size.y > 60.0, "sized to its words") + card.free() + + +func test_the_command_line_asks_for_it() -> void: + var config: ClientConfig = ClientConfig.parse(PackedStringArray(["--tutorial", "--autoplay", "--seed=4"])) + assert_true(config.is_valid(), str(config.errors)) + assert_true(config.tutorial and config.asked and config.autoplay) + assert_false(ClientConfig.parse(PackedStringArray(["--tutorial", "--connect=192.0.2.7"])).is_valid()) + assert_false(ClientConfig.parse(PackedStringArray(["--tutorial", "--duos"])).is_valid()) + assert_eq(ClientConfig.game_args(PackedStringArray(), PackedStringArray(["--tutorial"])), PackedStringArray(["--tutorial"])) + + +func test_command_logs_keep_the_new_rules_and_read_old_ones() -> void: + var log: CommandLog = CommandLog.new(7, 1, MatchRules.tutorial()) + var header: Dictionary = log.header() + assert_eq(header["rules"]["last_team_wins"], false) + assert_eq(header["rules"]["starting_kit"], true) + var back: CommandLog = CommandLog.from_bytes(log.to_bytes()) + assert_not_null(back) + assert_false(back.rules.last_team_wins) + assert_true(back.rules.starting_kit) + # A log written before A12 has neither rule, and reads with the defaults. + var old: Dictionary = header.duplicate(true) + old["rules"].erase("last_team_wins") + old["rules"].erase("starting_kit") + var head: PackedByteArray = JSON.stringify(old).to_utf8_buffer() + var out: StreamPeerBuffer = StreamPeerBuffer.new() + out.big_endian = false + out.put_data(CommandLog.MAGIC.to_ascii_buffer()) + out.put_u32(head.size()) + out.put_data(head) + out.put_u32(0) + var earlier: CommandLog = CommandLog.from_bytes(out.data_array) + assert_not_null(earlier, "an older log still reads") + assert_true(earlier.rules.last_team_wins) + assert_false(earlier.rules.starting_kit) diff --git a/test/app/test_tutorial.gd.uid b/test/app/test_tutorial.gd.uid new file mode 100644 index 0000000..533b825 --- /dev/null +++ b/test/app/test_tutorial.gd.uid @@ -0,0 +1 @@ +uid://s4xeekurih46 diff --git a/test/capture/menu_welcome.tscn b/test/capture/menu_welcome.tscn new file mode 100644 index 0000000..ae72631 --- /dev/null +++ b/test/capture/menu_welcome.tscn @@ -0,0 +1,9 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/menu_scene.gd" id="1"] + +[node name="CaptureMenu" type="Control"] +script = ExtResource("1") +screen = "welcome" +over_match = false +settings_tab = 0 diff --git a/test/capture/tutorial_build.tscn b/test/capture/tutorial_build.tscn new file mode 100644 index 0000000..d80e694 --- /dev/null +++ b/test/capture/tutorial_build.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/tutorial_scene.gd" id="1"] + +[node name="CaptureTutorial" type="Node3D"] +script = ExtResource("1") +step = "build" diff --git a/test/capture/tutorial_move.tscn b/test/capture/tutorial_move.tscn new file mode 100644 index 0000000..b00d0bf --- /dev/null +++ b/test/capture/tutorial_move.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/tutorial_scene.gd" id="1"] + +[node name="CaptureTutorial" type="Node3D"] +script = ExtResource("1") +step = "move" diff --git a/test/capture/tutorial_scene.gd b/test/capture/tutorial_scene.gd new file mode 100644 index 0000000..0f906e1 --- /dev/null +++ b/test/capture/tutorial_scene.gd @@ -0,0 +1,50 @@ +## Capture scenario for the tutorial (A12): the real ClientSession playing the tutorial +## offline, driven by its scripted player (TutorialPilot) until `step` begins, then held +## there so the HUD's tutorial card shows that step's instruction and progress. +## +## Stages: move (just landed), build (build mode on, the ghost showing) and tide (the +## last step, with the tide post and the line to beat). +extends Node3D + +const DT: float = 1.0 / Tuning.TICK_RATE_HZ +const LIMIT_FRAMES: int = 300 * Tuning.TICK_RATE_HZ + +@export var step: String = "move" +@export var match_seed: int = 3 + +var _session: ClientSession + + +func _ready() -> void: + _session = ClientSession.new() + _session.input.autoplay = true + _session.play_tutorial(match_seed) + add_child(_session) + _session.set_process(false) + var wanted: int = Tutorial.STEP_NAMES.find(step) + var frames: int = 0 + while frames < LIMIT_FRAMES and _session.tutorial.step < wanted: + _session.pump(DT) + frames += 1 + if _session.tutorial.step != wanted: + push_error("tutorial capture: never reached step '%s' (stopped at '%s')" % [step, _session.tutorial.step_name()]) + return + # A moment into the step: long enough for build mode to come on, too short for the + # script to finish it. + for _frame: int in 6: + _session.pump(DT) + if _session.tutorial.step != wanted: + push_error("tutorial capture: step '%s' was over before the picture" % step) + return + _session.input.map_open = false + _session.input.buttons = 0 + _session.hud.show_state(_session.hud_state()) + _session.view.settle() + _session._show_charts(DT) + _session.tutorial_card.show_tutorial(_session.tutorial, true) + + +func _process(_delta: float) -> void: + # The session is held still; only the card is laid out again as its labels settle. + if _session != null and _session.tutorial_card != null: + _session.tutorial_card.show_tutorial(_session.tutorial, true) diff --git a/test/capture/tutorial_scene.gd.uid b/test/capture/tutorial_scene.gd.uid new file mode 100644 index 0000000..77c2f3d --- /dev/null +++ b/test/capture/tutorial_scene.gd.uid @@ -0,0 +1 @@ +uid://cx5rndc8jqd8d diff --git a/test/capture/tutorial_tide.tscn b/test/capture/tutorial_tide.tscn new file mode 100644 index 0000000..e18fe26 --- /dev/null +++ b/test/capture/tutorial_tide.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/tutorial_scene.gd" id="1"] + +[node name="CaptureTutorial" type="Node3D"] +script = ExtResource("1") +step = "tide" diff --git a/test/ui/test_menus.gd b/test/ui/test_menus.gd index 1aedabe..72e2864 100644 --- a/test/ui/test_menus.gd +++ b/test/ui/test_menus.gd @@ -32,6 +32,14 @@ func _press(screen: String, text: String) -> void: (buttons[text] as Button).pressed.emit() +## Settings of a player who has already been offered the tutorial (A12), so the +## program opens on the main menu. +func _offered() -> GameSettings: + var settings: GameSettings = GameSettings.new() + settings.tutorial_offered = true + return settings + + func _key(keycode: Key) -> InputEventKey: var key: InputEventKey = InputEventKey.new() key.physical_keycode = keycode @@ -79,7 +87,7 @@ func test_focus_moves_through_the_main_menu_with_the_arrow_keys() -> void: await tree.process_frame var seen: Array[String] = [] var focused: Control = menus.get_viewport().gui_get_focus_owner() - for _step: int in 4: + for _step: int in 5: assert_not_null(focused) if focused == null: return @@ -89,7 +97,7 @@ func test_focus_moves_through_the_main_menu_with_the_arrow_keys() -> void: break next.grab_focus() focused = next - assert_eq(seen, ["Practice against bots", "Join a server", "Settings", "Quit"] as Array[String]) + assert_eq(seen, ["Practice against bots", "Tutorial", "Join a server", "Settings", "Quit"] as Array[String]) func test_rebinding_in_the_menu_detects_conflicts() -> void: @@ -185,7 +193,7 @@ func test_results_say_where_you_placed() -> void: func test_the_shell_goes_from_the_menu_to_a_match_and_back() -> void: menus.free() - var shell: AppShell = AppShell.new(GameSettings.new(), PATH) + var shell: AppShell = AppShell.new(_offered(), PATH) shell.grab_mouse = false tree.root.add_child(shell) assert_eq(shell.menus.current, "main") @@ -220,7 +228,7 @@ func test_the_shell_goes_from_the_menu_to_a_match_and_back() -> void: func test_the_shell_shows_results_when_a_match_you_played_ends() -> void: menus.free() - var shell: AppShell = AppShell.new(GameSettings.new(), PATH) + var shell: AppShell = AppShell.new(_offered(), PATH) shell.grab_mouse = false tree.root.add_child(shell) var rules: MatchRules = MatchRules.new() diff --git a/tools/tutorial_check.gd b/tools/tutorial_check.gd new file mode 100644 index 0000000..1305f8e --- /dev/null +++ b/tools/tutorial_check.gd @@ -0,0 +1,66 @@ +## A12: plays the tutorial from start to end with its scripted player (TutorialPilot), +## through a real ClientSession on its offline server, as fast as it will go, on each +## seed asked for. Each seed must reach the last step within the time limit, with no +## script or engine error. +## +## tools/godot.sh --script res://tools/tutorial_check.gd -- [--seeds=N] [--first=N] +## +## Prints one JSON line per seed (the seconds each step took, in game time) and a +## verdict. Exits 1 on any failure. +extends SceneTree + +## Game seconds a seed may take before it counts as stuck. +const LIMIT_SECONDS: float = 600.0 + + +func _init() -> void: + var seeds: int = 5 + var first: int = 1 + for arg: String in OS.get_cmdline_user_args(): + if arg.begins_with("--seeds=") and arg.trim_prefix("--seeds=").is_valid_int(): + seeds = maxi(arg.trim_prefix("--seeds=").to_int(), 1) + elif arg.begins_with("--first=") and arg.trim_prefix("--first=").is_valid_int(): + first = arg.trim_prefix("--first=").to_int() + else: + print("tutorial-check FAIL: unknown argument '%s'" % arg) + quit(2) + return + var errors: ErrorCounter = ErrorCounter.new() + OS.add_logger(errors) + var problems: Array[String] = [] + for seed_value: int in range(first, first + seeds): + var result: Dictionary = play(seed_value, LIMIT_SECONDS) + print(JSON.stringify(result)) + if not bool(result["finished"]): + problems.append("seed %d stopped at '%s'" % [seed_value, result["step"]]) + OS.remove_logger(errors) + if errors.count() > 0: + problems.append("%d script or engine errors, first: %s" % [errors.count(), errors.first()]) + for problem: String in problems: + print("tutorial-check FAIL: %s" % problem) + if problems.is_empty(): + print("tutorial-check: ok (%d seeds played from the barge to the end)" % seeds) + quit(0 if problems.is_empty() else 1) + + +## Plays one seed's tutorial with the pilot, a tick a frame, for up to `limit` game +## seconds. Returns {"seed", "finished", "step", "seconds", "steps": {name: seconds}}. +static func play(seed_value: int, limit: float) -> Dictionary: + var session: ClientSession = ClientSession.new() + session.input.autoplay = true + session.play_tutorial(seed_value) + var delta: float = 1.0 / Tuning.TICK_RATE_HZ + var frames: int = 0 + var most: int = roundi(limit * Tuning.TICK_RATE_HZ) + while frames < most and not session.tutorial.finished(): + session.pump(delta) + frames += 1 + var steps: Dictionary = {} + for index: int in Tutorial.DONE: + steps[Tutorial.STEP_NAMES[index]] = snappedf(session.tutorial.step_seconds[index], 0.1) + var result: Dictionary = { + "seed": seed_value, "finished": session.tutorial.finished(), "step": session.tutorial.step_name(), + "seconds": snappedf(float(frames) * delta, 0.1), "steps": steps, + } + session.free() + return result diff --git a/tools/tutorial_check.gd.uid b/tools/tutorial_check.gd.uid new file mode 100644 index 0000000..1b9d443 --- /dev/null +++ b/tools/tutorial_check.gd.uid @@ -0,0 +1 @@ +uid://cd1vc1pfoij08