From 1d92f49d960e75042c249a6cefe203e392148121 Mon Sep 17 00:00:00 2001 From: Forrest Date: Wed, 7 Oct 2026 21:33:54 -0400 Subject: [PATCH] Talking-head dialogue: DialogueDirector, DialogueBox, conversations and speakers Conversations saved in game/resources/dialogue/ play once at their night and phase in a paper box with talking heads; example: the morning of day 2. Co-Authored-By: Claude Opus 5.5 --- README.md | 22 + game/resources/dialogue/morning_day_2.tres | 38 ++ .../dialogue/speakers/little_green_alien.tres | 13 + .../dialogue/speakers/scarecrow.tres | 14 + game/scripts/campaign_controller.gd | 4 + game/scripts/campaign_debug.gd | 4 + game/scripts/conversation.gd | 36 ++ game/scripts/conversation.gd.uid | 1 + game/scripts/dialogue_box.gd | 459 ++++++++++++++++++ game/scripts/dialogue_box.gd.uid | 1 + game/scripts/dialogue_director.gd | 194 ++++++++ game/scripts/dialogue_director.gd.uid | 1 + game/scripts/dialogue_line.gd | 22 + game/scripts/dialogue_line.gd.uid | 1 + game/scripts/dialogue_speaker.gd | 51 ++ game/scripts/dialogue_speaker.gd.uid | 1 + game/scripts/farm_sim.gd | 8 +- game/scripts/main.gd | 4 + game/scripts/tutorial.gd | 3 +- game/tests/run_tests.gd | 1 + game/tests/test_dialogue.gd | 281 +++++++++++ game/tests/test_dialogue.gd.uid | 1 + 22 files changed, 1158 insertions(+), 2 deletions(-) create mode 100644 game/resources/dialogue/morning_day_2.tres create mode 100644 game/resources/dialogue/speakers/little_green_alien.tres create mode 100644 game/resources/dialogue/speakers/scarecrow.tres create mode 100644 game/scripts/conversation.gd create mode 100644 game/scripts/conversation.gd.uid create mode 100644 game/scripts/dialogue_box.gd create mode 100644 game/scripts/dialogue_box.gd.uid create mode 100644 game/scripts/dialogue_director.gd create mode 100644 game/scripts/dialogue_director.gd.uid create mode 100644 game/scripts/dialogue_line.gd create mode 100644 game/scripts/dialogue_line.gd.uid create mode 100644 game/scripts/dialogue_speaker.gd create mode 100644 game/scripts/dialogue_speaker.gd.uid create mode 100644 game/tests/test_dialogue.gd create mode 100644 game/tests/test_dialogue.gd.uid diff --git a/README.md b/README.md index dcbb82c..1400fe6 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,26 @@ pack (`assets/farm/ithappy/farm/prefabs/assets/`). "Start the day" ends it. Playtest findings and tuning notes: [`game/PLAYTEST.md`](game/PLAYTEST.md). +* **Talking heads** — `DialogueDirector` (`game/scripts/dialogue_director.gd`) plays every + `Conversation` saved in `game/resources/dialogue/` once, at its night and phase (`night` 2, + `phase` MORNING is the morning of day 2; `night` 18, `phase` NIGHT is night 18), `delay` seconds + in (the morning starts at once, and the morning sign waits until it's done). `DialogueBox` + shows it above the hotbar on a sheet of paper like the morning sign's: the speaker's name and + words on their side, and their picture standing behind the paper's top edge. Words are written + letter by letter while the head bobs (and flaps its mouth with `talk_frames`) and blips + (`voice`). To add one, in the editor's FileSystem dock: New Resource → `DialogueSpeaker` + per character (`game/resources/dialogue/speakers/`: name, portrait, side, name and text + color, font, size, italics, bold, speed, voice), then New Resource → `Conversation` in + `game/resources/dialogue/` (night, phase, delay, pause the game, auto-advance, and its lines: + `DialogueLine`, a speaker and text, with optional per-line face, color, size, italics, bold). + Text takes BBCode: `[i]`, `[b]`, `[color=#b02010]`, `[font_size=48]`, `[wave]`, `[shake]`. A + conversation pauses the game by default (in co-op the farm can't stop, so the player's + scarecrow stands still instead); one that doesn't takes no input and goes on by itself. A + retried night doesn't replay its conversations; a new vacation does. From code: + `sim.dialogue.play(conversation)`. Debug: F5 plays the current phase's again. The example + (`example_morning_day_2.tres`, the Scarecrow and a Little Green Alien) uses the HUD's painted + icons as placeholder portraits (`DialogueSpeaker.icon`) until real pictures are set. + * **Menus and saving** — `Main` (`game/scripts/main.gd`, `game/scenes/main.tscn`) hosts the farm under the menus. `MainMenu` is the title screen (Continue, New vacation, Settings, Quit) over the paused farm, with a camera circling it. `PauseMenu` (Escape / Start) pauses the whole tree @@ -291,6 +311,8 @@ pack (`assets/farm/ithappy/farm/prefabs/assets/`). | In build mode: build / rotate / pick / dismantle or leave | LMB / Z, C / 1-4, Tab / RMB | RT / d-pad left, right / d-pad down / B | | Repair a damaged structure (hold) | E | X | | Start the day (morning review) | Click, Enter | A | +| Talking heads: write the line / next line | Click, Enter, Space, E | A, X | +| Talking heads: skip the conversation | Backspace | Back | | Pause / resume | Escape | Start | | Hide the tips | Backspace | Back | | Mute / unmute your microphone (co-op) | M | - | diff --git a/game/resources/dialogue/morning_day_2.tres b/game/resources/dialogue/morning_day_2.tres new file mode 100644 index 0000000..12ff4ab --- /dev/null +++ b/game/resources/dialogue/morning_day_2.tres @@ -0,0 +1,38 @@ +[gd_resource type="Resource" script_class="Conversation" format=3 uid="uid://bvbmgb0ug3ofi"] + +[ext_resource type="Script" uid="uid://b8csl51l2cwpg" path="res://game/scripts/conversation.gd" id="1_conversation"] +[ext_resource type="Script" uid="uid://oluompq3r367" path="res://game/scripts/dialogue_line.gd" id="2_line"] +[ext_resource type="Resource" path="res://game/resources/dialogue/speakers/little_green_alien.tres" id="3_alien"] +[ext_resource type="Resource" path="res://game/resources/dialogue/speakers/scarecrow.tres" id="4_scarecrow"] + +[sub_resource type="Resource" id="Resource_line1"] +script = ExtResource("2_line") +speaker = ExtResource("3_alien") +text = "Greetings, creature from Planet 392823. You have something of ours and I would like it back!" + +[sub_resource type="Resource" id="Resource_line2"] +script = ExtResource("2_line") +speaker = ExtResource("4_scarecrow") +text = "Who said that? Is that a [i]talking vegetable[/i]?" + +[sub_resource type="Resource" id="Resource_line3"] +script = ExtResource("2_line") +speaker = ExtResource("3_alien") +text = "This planet has creatures of little intelligence I see...." + +[sub_resource type="Resource" id="Resource_line4"] +script = ExtResource("2_line") +speaker = ExtResource("4_scarecrow") +text = "Buzz off slime ball! These here crops belong to the Farmer." +italic = true + +[sub_resource type="Resource" id="Resource_eu5ag"] +script = ExtResource("2_line") +speaker = ExtResource("3_alien") +text = "Silly little fool!! Tonight we come for your crops, your animals, and [color=#b02010]everything in that shed[/color]. [shake]Mwahaha![/shake]" +metadata/_custom_type_script = "uid://oluompq3r367" + +[resource] +script = ExtResource("1_conversation") +night = 2 +lines = Array[ExtResource("2_line")]([SubResource("Resource_line1"), SubResource("Resource_line2"), SubResource("Resource_line3"), SubResource("Resource_line4"), SubResource("Resource_eu5ag")]) diff --git a/game/resources/dialogue/speakers/little_green_alien.tres b/game/resources/dialogue/speakers/little_green_alien.tres new file mode 100644 index 0000000..7ec2b06 --- /dev/null +++ b/game/resources/dialogue/speakers/little_green_alien.tres @@ -0,0 +1,13 @@ +[gd_resource type="Resource" script_class="DialogueSpeaker" format=3] + +[ext_resource type="Script" path="res://game/scripts/dialogue_speaker.gd" id="1_speaker"] +[ext_resource type="AudioStream" path="res://assets/audio/kenney/interface/pluck_001.ogg" id="2_voice"] + +[resource] +script = ExtResource("1_speaker") +display_name = "Little Green Alien" +icon = "thief" +portrait_height = 300.0 +voice = ExtResource("2_voice") +voice_pitch = 1.6 +voice_every = 3 diff --git a/game/resources/dialogue/speakers/scarecrow.tres b/game/resources/dialogue/speakers/scarecrow.tres new file mode 100644 index 0000000..6fba9cf --- /dev/null +++ b/game/resources/dialogue/speakers/scarecrow.tres @@ -0,0 +1,14 @@ +[gd_resource type="Resource" script_class="DialogueSpeaker" format=3] + +[ext_resource type="Script" path="res://game/scripts/dialogue_speaker.gd" id="1_speaker"] +[ext_resource type="AudioStream" path="res://assets/audio/kenney/interface/pluck_002.ogg" id="2_voice"] + +[resource] +script = ExtResource("1_speaker") +display_name = "Scarecrow" +icon = "portrait" +side = 1 +portrait_height = 300.0 +voice = ExtResource("2_voice") +voice_pitch = 0.8 +voice_every = 3 diff --git a/game/scripts/campaign_controller.gd b/game/scripts/campaign_controller.gd index 766c177..11b0d67 100644 --- a/game/scripts/campaign_controller.gd +++ b/game/scripts/campaign_controller.gd @@ -22,6 +22,8 @@ signal campaign_ended(outcome: Outcome) ## The dawn grace is over: listeners settle the night (enemies leave, loot on the ground returns) ## before its losses are recorded and the outcome is checked. signal night_ending +## A vacation starts: a new one (new_campaign) or a saved one continued (load_state). +signal started @export var config: GameConfig @@ -57,6 +59,7 @@ func _physics_process(delta: float) -> void: func new_campaign() -> void: state = FarmState.create(config) outcome = Outcome.CONTINUE + started.emit() _enter(Phase.MORNING) @@ -106,6 +109,7 @@ func advance_phase() -> void: func load_state(saved: FarmState) -> void: state = saved outcome = Outcome.CONTINUE + started.emit() _enter(Phase.MORNING) diff --git a/game/scripts/campaign_debug.gd b/game/scripts/campaign_debug.gd index 092ce01..76ba524 100644 --- a/game/scripts/campaign_debug.gd +++ b/game/scripts/campaign_debug.gd @@ -11,6 +11,7 @@ extends CanvasLayer ## F8: run from the editor, Godot stops the game on F8 (its Stop shortcut) ## N start the night early (only when GameConfig.allow_early_night is on) ## R after Game Over: retry the night; after the farmers return: new vacation +## F5 play this phase's talking-head conversations again (DialogueDirector) ## F6 end the current phase now ## F7 cycle game speed 1x / 5x / 20x ## F9 debug: scarecrow to 0 HP @@ -73,6 +74,9 @@ func _unhandled_input(event: InputEvent) -> void: unlock_all() KEY_N: campaign.start_night_early() + KEY_F5: + if sim != null and sim.dialogue != null: + sim.dialogue.replay() KEY_F6: campaign.advance_phase() KEY_F7: diff --git a/game/scripts/conversation.gd b/game/scripts/conversation.gd new file mode 100644 index 0000000..f6edf8f --- /dev/null +++ b/game/scripts/conversation.gd @@ -0,0 +1,36 @@ +class_name Conversation +extends Resource +## A talking-head conversation: its lines (DialogueLine), shown one at a time in the DialogueBox, +## and when it plays. Saved in game/resources/dialogue/, it plays by itself (DialogueDirector) +## once, delay seconds into the phase of its night: the morning of day 2 is night 2, MORNING; +## night 18 is night 18, NIGHT. The morning isn't timed, so its conversations start at once +## (the morning sign waits until they're done). From code, sim.dialogue.play(conversation) shows +## one at any time. + +## The phases of a night (CampaignController.Phase, in the same order). +enum Phase { MORNING, DAY, DUSK, NIGHT, DAWN } +## Seconds a line stays when the game isn't paused and auto_advance is 0. +const AUTO_ADVANCE := 3.0 + +## Off: it never plays by itself (play() still shows it). +@export var enabled := true +@export_range(1, 99) var night := 1 +@export var phase: Phase = Phase.MORNING +## Seconds into the phase (timed phases only). +@export_range(0.0, 600.0, 0.5, "suffix:s") var delay := 0.0 +## Stops the farm while it's up, and the player goes through the lines. In co-op the farm can't +## stop: the player's scarecrow stands still instead. Off: the farm plays on, the box takes no +## input (the player is busy), and the lines go on by themselves. +@export var pause_game := true +## Seconds a line stays once it's written before the next one comes by itself; 0 waits for the +## player (AUTO_ADVANCE when the game isn't paused). +@export_range(0.0, 30.0, 0.1, "suffix:s") var auto_advance := 0.0 +@export var lines: Array[DialogueLine] = [] + + +## Seconds a written line stays before the next one comes by itself (INF: until the player goes +## on). +func line_hold() -> float: + if auto_advance > 0.0: + return auto_advance + return INF if pause_game else AUTO_ADVANCE diff --git a/game/scripts/conversation.gd.uid b/game/scripts/conversation.gd.uid new file mode 100644 index 0000000..426958e --- /dev/null +++ b/game/scripts/conversation.gd.uid @@ -0,0 +1 @@ +uid://b8csl51l2cwpg diff --git a/game/scripts/dialogue_box.gd b/game/scripts/dialogue_box.gd new file mode 100644 index 0000000..23da62a --- /dev/null +++ b/game/scripts/dialogue_box.gd @@ -0,0 +1,459 @@ +class_name DialogueBox +extends Control +## The talking-head box: a conversation (Conversation) one line at a time on a sheet of paper like +## the morning sign's (Sketch.paper, nailed at its top corners) above the hotbar, the speaker's +## name over their words on their side of it, and their picture (the talking head) standing behind +## the paper's top edge on that side. A new speaker's head rises from behind the paper (the last +## one's sinks back); while the words are written, letter by letter (a beat longer after a comma +## or a full stop), the head bobs, flaps its mouth (DialogueSpeaker.talk_frames), and blips +## (voice); then it breathes, and a pen arrow bobs in the corner. A line without a speaker is +## narration: words only. +## Click, [Enter / Space / E] or (A) writes the rest of the line, then goes on to the next; +## [Backspace / Back] skips the rest of the conversation. One that doesn't pause the game takes no +## input and goes on by itself (Conversation.line_hold). Works while the game is paused +## (DialogueDirector pauses it for a conversation); waits while blocked (a menu is up over it). + +signal finished(conversation: Conversation) + +## The paper's size and its gap above the screen's bottom (the hotbar is under it). +const WIDTH := 1360.0 +const HEIGHT := 350.0 +const BOTTOM := 118.0 +const SIDE_GAP := 40.0 +## The name's and words' inset from the paper's edges. +const MARGIN := Vector2(64.0, 30.0) +## A head stands this far in from the paper's side, its bottom TUCK behind the paper. +const HEAD_INSET := 30.0 +const TUCK := 44.0 +const RISE_TIME := 0.25 +const OPEN_TIME := 0.18 +## A beat after these letters, when a space or the end follows. +const PAUSES := {".": 0.32, "!": 0.32, "?": 0.32, "…": 0.32, ",": 0.14, ";": 0.14, ":": 0.14} +const TALK_FPS := 9.0 +const SEED := 701.0 + +## Optional: whether a menu is up over the box (it waits: no input, no writing). +var blocked: Callable +## The conversation up (null when none), and its line on the paper. +var conversation: Conversation +var index: int = -1 + +static var _narrator := DialogueSpeaker.new() +static var _variants := {} # "font id/slant/bold" -> FontVariation + +var _stage: Control +var _sheet: Control +var _name: Label +var _text: RichTextLabel +var _more: Control +var _voice: AudioStreamPlayer +var _heads: Array[Head] = [] +var _speaker: DialogueSpeaker +var _plain := "" +var _shown: int = 0 +var _speed := 0.0 +var _budget := 0.0 +var _wait := 0.0 +var _hold := 0.0 +var _letters: int = 0 +var _open := 0.0 +var _closing := false +var _time := 0.0 +var _focus_before: Control + + +## A speaker's head on the stage: rising in (risen 0 -> 1) or sinking away (leaving). +class Head: + var speaker: DialogueSpeaker + var face: Texture2D + var risen := 0.0 + var leaving := false + var talking := false + + +func _ready() -> void: + set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + process_mode = Node.PROCESS_MODE_ALWAYS + mouse_filter = Control.MOUSE_FILTER_IGNORE + _stage = Control.new() + _stage.clip_contents = true # a sunk head is out of sight below the paper's top + _stage.mouse_filter = Control.MOUSE_FILTER_IGNORE + _stage.draw.connect(_draw_heads) + add_child(_stage) + _sheet = Control.new() + _sheet.mouse_filter = Control.MOUSE_FILTER_IGNORE + _sheet.draw.connect(_draw_sheet) + add_child(_sheet) + _name = Label.new() + _name.mouse_filter = Control.MOUSE_FILTER_IGNORE + _sheet.add_child(_name) + _text = RichTextLabel.new() + _text.bbcode_enabled = true + _text.scroll_active = false + _text.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + _text.visible_characters_behavior = TextServer.VC_CHARS_AFTER_SHAPING # words don't jump lines as they're written + _text.mouse_filter = Control.MOUSE_FILTER_IGNORE + _sheet.add_child(_text) + _more = Control.new() + _more.mouse_filter = Control.MOUSE_FILTER_IGNORE + _more.size = Vector2(40.0, 40.0) + _more.draw.connect(_draw_more) + _sheet.add_child(_more) + _voice = AudioStreamPlayer.new() + _voice.bus = &"SFX" + add_child(_voice) + visible = false + + +## Shows conversation c from its first line, over whatever was up. Returns false (and shows +## nothing) when it has no lines. +func play(c: Conversation) -> bool: + if c == null or c.lines.is_empty(): + return false + conversation = c + _closing = false + visible = true + _take_input(c.pause_game) + _show_line(0) + _place() + return true + + +func is_playing() -> bool: + return conversation != null + + +func is_blocked() -> bool: + return blocked.is_valid() and bool(blocked.call()) + + +## Whether the line on the paper is all written. +func is_written() -> bool: + return _shown >= _plain.length() + + +## The words on the paper as written so far (no BBCode), for tests. +func written_text() -> String: + return _plain.substr(0, _shown) + + +func speaker_name() -> String: + return _name.text + + +## Writes the rest of the line, or goes on to the next one (after the last: closes). +func advance() -> void: + if conversation == null: + return + if not is_written(): + _shown = _plain.length() + _wait = 0.0 + _text.visible_characters = -1 + return + if index + 1 < conversation.lines.size(): + _show_line(index + 1) + else: + _finish() + + +## Skips the rest of the conversation. +func skip() -> void: + if conversation != null: + _finish() + + +## Takes the box away at once, without finished. +func stop() -> void: + if conversation != null: + _take_input(false) + conversation = null + _closing = false + _heads.clear() + _open = 0.0 + visible = false + + +func _finish() -> void: + var c := conversation + conversation = null + _closing = true # the paper fades and the head sinks, unless the next conversation starts now + _take_input(false) + finished.emit(c) + + +func _show_line(i: int) -> void: + index = i + var line := conversation.lines[i] + _speaker = line.speaker if line.speaker != null else _narrator + _style(line, _speaker) + _text.text = _bbcode(line, _speaker) + _text.visible_characters = 0 + _plain = _text.get_parsed_text() + _shown = 0 + _budget = 0.0 + _wait = 0.0 + _letters = 0 + _hold = conversation.line_hold() + _speed = line.letters_per_second if line.letters_per_second > 0.0 else _speaker.letters_per_second + if _speed <= 0.0: + advance() # all at once + _set_head(_speaker, line.portrait if line.portrait != null else _speaker.portrait) + + +func _style(line: DialogueLine, sp: DialogueSpeaker) -> void: + var font: Font = sp.font if sp.font != null else Sketch.font() + _name.text = sp.display_name + _name.visible = sp.display_name != "" + _name.add_theme_font_override("font", font) + _name.add_theme_font_size_override("font_size", sp.name_size) + _name.add_theme_color_override("font_color", sp.name_color) + _name.add_theme_constant_override("outline_size", 0) + _name.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT if sp.side == DialogueSpeaker.HeadSide.RIGHT else HORIZONTAL_ALIGNMENT_LEFT + _text.add_theme_font_override("normal_font", font) + _text.add_theme_font_override("italics_font", _variant(font, true, false)) + _text.add_theme_font_override("bold_font", _variant(font, false, true)) + _text.add_theme_font_override("bold_italics_font", _variant(font, true, true)) + var font_size := line.font_size if line.font_size > 0 else sp.font_size + for key: String in ["normal_font_size", "italics_font_size", "bold_font_size", "bold_italics_font_size"]: + _text.add_theme_font_size_override(key, font_size) + _text.add_theme_color_override("default_color", line.text_color if line.text_color.a > 0.0 else sp.text_color) + _text.add_theme_constant_override("line_separation", 2) + match sp.align: + DialogueSpeaker.Align.LEFT: + _text.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT + DialogueSpeaker.Align.CENTER: + _text.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + DialogueSpeaker.Align.RIGHT: + _text.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT + _: + _text.horizontal_alignment = _name.horizontal_alignment + + +static func _bbcode(line: DialogueLine, sp: DialogueSpeaker) -> String: + var t := line.text + if line.italic or sp.italic: + t = "[i]%s[/i]" % t + if line.bold or sp.bold: + t = "[b]%s[/b]" % t + return t + + +## The font slanted (italics) and / or heavier (bold), for fonts without those faces (the +## handwritten one has neither). +static func _variant(base: Font, slant: bool, bold: bool) -> Font: + var key := "%d/%s/%s" % [base.get_instance_id(), slant, bold] + if not _variants.has(key): + var v := FontVariation.new() + v.base_font = base + if slant: + v.variation_transform = Transform2D(Vector2(1.0, 0.25), Vector2(0.0, 1.0), Vector2.ZERO) + if bold: + v.variation_embolden = 0.8 + _variants[key] = v + return _variants[key] + + +## The speaker's head takes the stage (a new speaker's rises, the last one's sinks), unless +## they're already on it; a line can change their face. +func _set_head(sp: DialogueSpeaker, face: Texture2D) -> void: + var current := _current_head() + if current != null and current.speaker == sp: + current.face = face + return + if current != null: + current.leaving = true + if face == null and sp.icon == "": + return # narration, or nobody to show + var h := Head.new() + h.speaker = sp + h.face = face + _heads.append(h) + + +func _current_head() -> Head: + for i in range(_heads.size() - 1, -1, -1): + if not _heads[i].leaving: + return _heads[i] + return null + + +func _take_input(on: bool) -> void: + mouse_filter = Control.MOUSE_FILTER_STOP if on else Control.MOUSE_FILTER_IGNORE + focus_mode = Control.FOCUS_ALL if on else Control.FOCUS_NONE # (NONE lets the focus go) + if on: + var had := get_viewport().gui_get_focus_owner() + if had != self: + _focus_before = had + grab_focus() # keys come here first: Enter doesn't press the morning sign's button under it + elif is_instance_valid(_focus_before) and _focus_before.is_visible_in_tree() and _focus_before.focus_mode != Control.FOCUS_NONE: + _focus_before.grab_focus() + _focus_before = null + + +func _process(delta: float) -> void: + if not visible or is_blocked(): + return + _time += delta + _open = move_toward(_open, 0.0 if _closing else 1.0, delta / OPEN_TIME) + var staying: Array[Head] = [] + for h in _heads: + var going := h.leaving or _closing + h.risen = move_toward(h.risen, 0.0 if going else 1.0, delta / RISE_TIME) + if h.risen > 0.0 or not going: + staying.append(h) + _heads = staying + if _closing: + if _open <= 0.0 and _heads.is_empty(): + visible = false + else: + if conversation.pause_game and not has_focus(): + grab_focus() # back from a menu over it + _write(delta) + _place() + + +## Writes letters at the speaker's speed (with a beat after a comma or a full stop), and goes +## on by itself once the line's been up long enough (Conversation.line_hold). +func _write(delta: float) -> void: + var head := _current_head() + var total := _plain.length() + if _shown >= total: + if head != null: + head.talking = false + _hold -= delta + if _hold <= 0.0: + advance() + return + if head != null: + head.talking = _wait <= 0.0 + if _wait > 0.0: + _wait -= delta + return + _budget += delta * _speed + while _budget >= 1.0 and _shown < total: + _budget -= 1.0 + _shown += 1 + var ch := _plain[_shown - 1] + if ch != " " and ch != "\n": + _letters += 1 + if _speaker.voice != null and (_letters - 1) % _speaker.voice_every == 0: + _voice.stream = _speaker.voice + _voice.pitch_scale = _speaker.voice_pitch * randf_range(0.92, 1.08) + _voice.volume_db = _speaker.voice_volume_db + _voice.play() + var beat: float = PAUSES.get(ch, 0.0) + if beat > 0.0 and (_shown == total or _plain[_shown] == " " or _plain[_shown] == "\n"): + _wait = beat + _budget = 0.0 + break + _text.visible_characters = _shown if _shown < total else -1 + + +## Lays the paper out over the hotbar (sliding up and fading in as it opens) and the stage above +## it, down to TUCK under the paper's top edge. +func _place() -> void: + var r := _sheet_rect() + var k := _ease(_open) + _sheet.position = r.position + Vector2(0.0, (1.0 - k) * 30.0) + _sheet.size = r.size + _sheet.modulate.a = k + _stage.position = Vector2.ZERO + _stage.size = Vector2(size.x, r.position.y + TUCK) + var name_h := _name.get_minimum_size().y if _name.visible else 0.0 + var inner := r.size.x - 2.0 * MARGIN.x + _name.position = MARGIN + _name.size = Vector2(inner, name_h) + var top := MARGIN.y + name_h + (8.0 if _name.visible else 0.0) + _text.position = Vector2(MARGIN.x, top) + _text.size = Vector2(inner, r.size.y - top - 36.0) + _more.position = Vector2(r.size.x - 50.0 - _more.size.x, r.size.y - 30.0 - _more.size.y) + _more.visible = conversation != null and conversation.pause_game and is_written() + _stage.queue_redraw() + _more.queue_redraw() + + +func _sheet_rect() -> Rect2: + var w := minf(WIDTH, size.x - 2.0 * SIDE_GAP) + return Rect2((size.x - w) * 0.5, size.y - BOTTOM - HEIGHT, w, HEIGHT) + + +static func _ease(t: float) -> float: + return 1.0 - pow(1.0 - clampf(t, 0.0, 1.0), 3.0) + + +func _gui_input(event: InputEvent) -> void: + if _press(event): + accept_event() + + +func _unhandled_input(event: InputEvent) -> void: + if _press(event): + get_viewport().set_input_as_handled() + + +## A press that goes on (or skips), while the box takes input. Returns whether it was used. +func _press(event: InputEvent) -> bool: + if conversation == null or not conversation.pause_game or event.is_echo() or is_blocked(): + return false + if event.is_action_pressed("hide_tips"): + skip() + return true + var mb := event as InputEventMouseButton + if (mb != null and mb.pressed and mb.button_index == MOUSE_BUTTON_LEFT) or event.is_action_pressed("ui_accept") \ + or event.is_action_pressed("interact"): + advance() + return true + return false + + +## The sheet of paper, nailed at its top corners as on the morning sign. +func _draw_sheet() -> void: + var r := Rect2(Vector2.ZERO, _sheet.size) + Sketch.paper(_sheet, r, SEED) + for x: float in [30.0, r.size.x - 30.0]: + Sketch.nail(_sheet, Vector2(x, 26.0)) + + +## The heads, their feet TUCK under the paper's top edge: rising or sinking, bobbing while they +## talk (their mouth flapping when they have talk frames), breathing when they're done. +func _draw_heads() -> void: + var r := _sheet_rect() + for h in _heads: + var sp := h.speaker + var face := _frame(h) + var tall := sp.portrait_height + var wide := tall * face.get_size().aspect() if face != null else tall + var x := r.position.x + HEAD_INSET if sp.side == DialogueSpeaker.HeadSide.LEFT else r.end.x - HEAD_INSET - wide + var lift := 0.0 + var tilt := 0.0 + var stretch := 1.0 + if h.talking: + lift = absf(sin(_time * 10.0)) * 8.0 + tilt = sin(_time * 5.0) * 0.03 + else: + stretch = 1.0 + sin(_time * 2.2) * 0.008 + var foot := Vector2(x + wide * 0.5, _stage.size.y + (1.0 - _ease(h.risen)) * (tall + 20.0) - lift) + sp.portrait_offset + if face != null: + _stage.draw_set_transform(foot, tilt, Vector2(-1.0 if sp.flip else 1.0, stretch)) + _stage.draw_texture_rect(face, Rect2(-wide * 0.5, -tall, wide, tall), false) + _stage.draw_set_transform_matrix(Transform2D.IDENTITY) + else: + Sketch.icon(_stage, sp.icon, Rect2(foot - Vector2(wide * 0.5, tall * stretch), Vector2(wide, tall * stretch))) + + +## The head's picture now: its face, or while it talks (with its usual face) its mouth flaps. +func _frame(h: Head) -> Texture2D: + var sp := h.speaker + if not h.talking or sp.talk_frames.is_empty() or h.face != sp.portrait: + return h.face + var k := int(_time * TALK_FPS) % (sp.talk_frames.size() + 1) + return h.face if k == 0 else sp.talk_frames[k - 1] + + +## The pen arrow in the corner when the line is written and the player goes on. +func _draw_more() -> void: + var ink: Color = _text.get_theme_color("default_color") + var c := _more.size * 0.5 + Vector2(0.0, sin(_time * 5.0) * 4.0) + var tip := PackedVector2Array([c + Vector2(-13.0, -8.0), c + Vector2(13.0, -8.0), c + Vector2(0.0, 11.0)]) + _more.draw_colored_polygon(tip, Color(ink, 0.85)) + Sketch.outline(_more, tip, ink, 2.0, SEED + 9.0, 0.8, 1) diff --git a/game/scripts/dialogue_box.gd.uid b/game/scripts/dialogue_box.gd.uid new file mode 100644 index 0000000..66be70c --- /dev/null +++ b/game/scripts/dialogue_box.gd.uid @@ -0,0 +1 @@ +uid://cmgdtiix0rsho diff --git a/game/scripts/dialogue_director.gd b/game/scripts/dialogue_director.gd new file mode 100644 index 0000000..beb225a --- /dev/null +++ b/game/scripts/dialogue_director.gd @@ -0,0 +1,194 @@ +class_name DialogueDirector +extends Node +## Plays the talking-head conversations (Conversation) at their time. Every enabled Conversation +## saved in game/resources/dialogue/ plays once, delay seconds into its night's phase (the +## morning of day 2, night 18, ...), in the DialogueBox over the HUD; several due at once play one +## after another (by delay, then file name). One that pauses the game stops the farm while it's +## up (in co-op, where the farm doesn't stop, this machine's scarecrow stands still instead). A +## retried night doesn't play its conversations again; a new or continued vacation does. The +## morning sign (ReviewPanel) waits, hidden, until the morning's conversations are done. Nothing +## starts while a menu is up (the shops, or Main's: DialogueBox.blocked) or the vacation is over, +## and a new morning (or a retry) takes down whatever was up. play() shows a conversation from +## code at any time; replay() (debug: F5) plays this phase's again. + +const DIR := "res://game/resources/dialogue/" + +var sim: FarmSim +var box: DialogueBox +## The conversations that play by themselves, by file name. +var conversations: Array[Conversation] = [] + +var _queue: Array[Conversation] = [] # this phase's, not played yet, by delay +var _asked: Array[Conversation] = [] # play() while another was up +var _played := {} # Conversation -> true, this night +var _night: int = 0 +var _paused := false +var _froze := false + + +## Puts the box in hud_layer (over the HUD) and plays the conversations saved in dir. +func setup(p_sim: FarmSim, hud_layer: Node, dir: String = DIR) -> void: + sim = p_sim + box = DialogueBox.new() + box.name = "DialogueBox" + hud_layer.add_child(box) + box.finished.connect(_on_finished) + conversations = load_all(dir) + var c := sim.campaign + c.started.connect(func() -> void: _played.clear()) + c.phase_changed.connect(_on_phase) + c.campaign_ended.connect(func(_o: CampaignController.Outcome) -> void: stop()) + _on_phase(c.state.phase, c.state.phase) + + +## The enabled conversations saved in dir (not its subfolders), by file name. +static func load_all(dir: String) -> Array[Conversation]: + var out: Array[Conversation] = [] + if not DirAccess.dir_exists_absolute(dir): + return out + var files := Array(ResourceLoader.list_directory(dir)) + files.sort() + for f: String in files: + if f.ends_with("/"): + continue + var c := load(dir.path_join(f)) as Conversation # (speakers and the like aren't) + if c != null and c.enabled: + out.append(c) + return out + + +func is_playing() -> bool: + return box != null and box.is_playing() + + +## The conversations of night n's phase that haven't played (this night), by delay, then file name. +func due(n: int, phase: CampaignController.Phase) -> Array[Conversation]: + var out: Array[Conversation] = [] + for c in conversations: + if c.night == n and int(c.phase) == int(phase) and not _played.has(c): + out.append(c) + var order := func(a: Conversation, b: Conversation) -> bool: + return a.delay < b.delay or (a.delay == b.delay and conversations.find(a) < conversations.find(b)) + out.sort_custom(order) + return out + + +## Shows conversation c now, or after the one that's up. +func play(c: Conversation) -> void: + if is_playing(): + _asked.append(c) + return + _played[c] = true + _hold(c.pause_game) + if box.play(c): + _sign(false) + else: + _release() + + +## Debug: plays this phase's conversations again, now. +func replay() -> void: + var s := sim.campaign.state + for c in conversations: + if c.night == s.night and int(c.phase) == int(s.phase): + _played.erase(c) + var again := due(s.night, s.phase) + _queue.clear() + for c in again: + play(c) + + +## Takes down whatever is up and forgets what was due. +func stop() -> void: + _queue.clear() + _asked.clear() + if box != null: + box.stop() + _release() + _sign(true) + + +## Main, back from a menu that let the game go on: a conversation that's up holds it again. +func hold() -> void: + if is_playing(): + _hold(box.conversation.pause_game) + + +func _exit_tree() -> void: + if _paused: + get_tree().paused = false # the farm's going away with its conversation up + + +func _process(_delta: float) -> void: + if _queue.is_empty() or is_playing() or box.is_blocked() or sim.campaign.is_over() or sim._menu_open(): + return + if _elapsed() >= _queue[0].delay: + play(_queue.pop_front()) + + +## Seconds into the phase (INF in the untimed morning: its conversations start at once). +func _elapsed() -> float: + var c := sim.campaign + if not c.is_timed(c.state.phase): + return INF + return c.phase_length(c.state.phase) - c.state.phase_time_left + + +func _on_phase(phase: CampaignController.Phase, _previous: CampaignController.Phase) -> void: + var n := sim.campaign.state.night + if phase == CampaignController.Phase.MORNING: + stop() # a new day, or a retry + if n != _night: + _played.clear() + _night = n + _queue = due(n, phase) + + +func _on_finished(_c: Conversation) -> void: + _release() + if not _asked.is_empty(): + play(_asked.pop_front()) + elif not _queue.is_empty() and _elapsed() >= _queue[0].delay: + play(_queue.pop_front()) # straight on, without a tick of the farm between them + else: + _sign(true) + + +## The morning sign steps aside while a conversation is up, and comes back (with the focus on +## Start the day) after it. +func _sign(show: bool) -> void: + var review := sim.review_panel if sim != null else null + if review == null: + return + if show: + review.refresh() + elif review.visible: + review.visible = false + review.mouse_filter = Control.MOUSE_FILTER_IGNORE + + +## Stops the farm for a conversation that pauses the game: the whole tree solo, this machine's +## scarecrow in co-op. +func _hold(pause: bool) -> void: + if not pause: + return + if sim.coop != null and sim.coop.is_active(): + if not sim.local_frozen: + sim.freeze_local(true) + _froze = true + else: + get_tree().paused = true + _paused = true + + +## Lets the farm go on, unless a menu is up (Main's pause or freeze is its own). +func _release() -> void: + var menu := box != null and box.is_blocked() + if _paused: + _paused = false + if not menu: + get_tree().paused = false + if _froze: + _froze = false + if sim.local_frozen and not menu: + sim.freeze_local(false) diff --git a/game/scripts/dialogue_director.gd.uid b/game/scripts/dialogue_director.gd.uid new file mode 100644 index 0000000..f42e47b --- /dev/null +++ b/game/scripts/dialogue_director.gd.uid @@ -0,0 +1 @@ +uid://bcu5kh8ecg8th diff --git a/game/scripts/dialogue_line.gd b/game/scripts/dialogue_line.gd new file mode 100644 index 0000000..081dfc1 --- /dev/null +++ b/game/scripts/dialogue_line.gd @@ -0,0 +1,22 @@ +class_name DialogueLine +extends Resource +## One thing said in a conversation (Conversation): who says it (DialogueSpeaker) and what. The +## text takes BBCode for a word or two: [i]italics[/i], [b]bold[/b], [color=#b02010]red[/color], +## [font_size=48]big[/font_size], [wave]wavy[/wave], [shake]shaky[/shake]. The look settings +## change the whole line from the speaker's. + +@export var speaker: DialogueSpeaker +@export_multiline var text := "" + +@export_group("Look (over the speaker's)") +## Another face for this line (an angry one, say); empty: the speaker's portrait. +@export var portrait: Texture2D +## Transparent: the speaker's text color. +@export var text_color := Color(0.0, 0.0, 0.0, 0.0) +## 0: the speaker's. +@export_range(0, 120) var font_size := 0 +## The whole line in italics or bold (also when the speaker's words aren't). +@export var italic := false +@export var bold := false +## 0: the speaker's speed. +@export_range(0.0, 200.0, 1.0, "suffix:letters/s") var letters_per_second := 0.0 diff --git a/game/scripts/dialogue_line.gd.uid b/game/scripts/dialogue_line.gd.uid new file mode 100644 index 0000000..a6b5660 --- /dev/null +++ b/game/scripts/dialogue_line.gd.uid @@ -0,0 +1 @@ +uid://oluompq3r367 diff --git a/game/scripts/dialogue_speaker.gd b/game/scripts/dialogue_speaker.gd new file mode 100644 index 0000000..6f69ad7 --- /dev/null +++ b/game/scripts/dialogue_speaker.gd @@ -0,0 +1,51 @@ +class_name DialogueSpeaker +extends Resource +## Someone who talks in a conversation (Conversation, shown by DialogueBox): their name, their +## picture (the talking head, standing behind the box's top edge), the side of the box they stand +## on, and how their name and words look. Save one per character (game/resources/dialogue/ +## speakers/) and use it in every line they say; a line (DialogueLine) can change the look of its +## own words, and its text takes BBCode ([i]...[/i], [color=red], ...). + +enum HeadSide { LEFT, RIGHT } +## Where the words sit on the paper: on the speaker's side (as their name is), or set. +enum Align { SIDE, LEFT, CENTER, RIGHT } + +@export var display_name := "" +## The talking head (a picture with a transparent background), scaled to portrait_height. +@export var portrait: Texture2D +## Optional mouth flaps: shown in turn with portrait while the words are being written. +@export var talk_frames: Array[Texture2D] = [] +## Placeholder art while there's no portrait: one of Sketch.ICONS ("portrait" is the scarecrow, +## "thief" an alien, "breaker" a robot, "crow", "ufo"). +@export var icon := "" +@export var side: HeadSide = HeadSide.LEFT + +@export_group("Portrait") +@export_range(60.0, 800.0, 1.0, "suffix:px") var portrait_height := 360.0 +## Nudges the head from its place (+x right, +y down). +@export var portrait_offset := Vector2.ZERO +## Mirrors the picture (to face the other way). +@export var flip := false + +@export_group("Name") +@export var name_color := Sketch.PAPER_INK +@export_range(8, 120) var name_size := 50 + +@export_group("Words") +## Empty: the handwritten font of the morning sign (Sketch.font()). +@export var font: Font +@export var text_color := Sketch.PAPER_INK +@export_range(8, 120) var font_size := 36 +@export var italic := false +@export var bold := false +@export var align: Align = Align.SIDE +## How fast the words are written; 0 shows each line at once. +@export_range(0.0, 200.0, 1.0, "suffix:letters/s") var letters_per_second := 45.0 + +@export_group("Voice") +## A short blip played as the words are written (none: silent). +@export var voice: AudioStream +@export_range(0.25, 4.0, 0.01) var voice_pitch := 1.0 +@export_range(-40.0, 12.0, 0.5, "suffix:dB") var voice_volume_db := -10.0 +## A blip every this many letters. +@export_range(1, 10) var voice_every := 2 diff --git a/game/scripts/dialogue_speaker.gd.uid b/game/scripts/dialogue_speaker.gd.uid new file mode 100644 index 0000000..b414e3e --- /dev/null +++ b/game/scripts/dialogue_speaker.gd.uid @@ -0,0 +1 @@ +uid://c1dai0qffqkmi diff --git a/game/scripts/farm_sim.gd b/game/scripts/farm_sim.gd index 49c5a86..c904585 100644 --- a/game/scripts/farm_sim.gd +++ b/game/scripts/farm_sim.gd @@ -24,7 +24,8 @@ extends Node ## simulated there, the host's state is applied instead (replica = true), and player, scarecrow, ## combat, and interactions are that machine's own scarecrow's (player 2's). ## FarmAudio plays every sound, Tutorial shows the first -## day's and night's tips, and FarmersReturn plays the ending. Debug: T / G / H send in a +## day's and night's tips, DialogueDirector the talking-head conversations (game/resources/ +## dialogue/), and FarmersReturn plays the ending. Debug: T / G / H send in a ## thief / a crow / a fence breaker at any time. const SCARECROW_RADIUS := 0.4 @@ -83,6 +84,7 @@ var replica_step: Callable var coop: CoopSession var audio: FarmAudio var tutorial: Tutorial +var dialogue: DialogueDirector var ending: FarmersReturn ## Flow-field rebuild after a structure change: running, and stats of the last one. var rebuilding := false @@ -320,6 +322,10 @@ func _ready() -> void: tutorial.name = "Tutorial" hud.get_parent().add_child(tutorial) tutorial.setup(self) + dialogue = DialogueDirector.new() + dialogue.name = "Dialogue" + add_child(dialogue) + dialogue.setup(self, hud.get_parent()) # its box over the tips and the morning sign if end_panel != null: end_panel.get_parent().move_child(end_panel, -1) # over the banners and the tips audio = FarmAudio.new() diff --git a/game/scripts/main.gd b/game/scripts/main.gd index f1f4896..cfad0d0 100644 --- a/game/scripts/main.gd +++ b/game/scripts/main.gd @@ -63,6 +63,8 @@ func _ready() -> void: sim.end_panel.menu_requested.connect(to_menu) if sim.tutorial != null: sim.tutorial.enabled = settings.show_tips + if sim.dialogue != null: + sim.dialogue.box.blocked = func() -> bool: return screen != Screen.PLAYING main_menu.continue_requested.connect(continue_vacation) main_menu.new_requested.connect(_ask_new_vacation) main_menu.settings_requested.connect(_open_settings) @@ -188,6 +190,8 @@ func resume() -> void: get_tree().paused = false if sim.local_frozen: sim.freeze_local(false) + if sim.dialogue != null: + sim.dialogue.hold() # a conversation that was up stops the farm again func restart_night() -> void: diff --git a/game/scripts/tutorial.gd b/game/scripts/tutorial.gd index 00208f4..8ec6a08 100644 --- a/game/scripts/tutorial.gd +++ b/game/scripts/tutorial.gd @@ -92,7 +92,8 @@ func _process(delta: float) -> void: if sim == null: return var s := sim.campaign.state - if not enabled or dismissed or s.night != 1 or sim.campaign.is_over() or sim._menu_open(): + if not enabled or dismissed or s.night != 1 or sim.campaign.is_over() or sim._menu_open() \ + or (sim.dialogue != null and sim.dialogue.is_playing()): _show("") return _check_done() diff --git a/game/tests/run_tests.gd b/game/tests/run_tests.gd index 5d1951e..32bed4a 100644 --- a/game/tests/run_tests.gd +++ b/game/tests/run_tests.gd @@ -24,6 +24,7 @@ const SUITES := [ "res://game/tests/test_flow.gd", "res://game/tests/test_coop.gd", "res://game/tests/test_look.gd", + "res://game/tests/test_dialogue.gd", ] const TICK := 1.0 / 60.0 ## Points on the farm's edge (FarmZones.edge) for tests that send an enemy in from a known side: diff --git a/game/tests/test_dialogue.gd b/game/tests/test_dialogue.gd new file mode 100644 index 0000000..ab0be54 --- /dev/null +++ b/game/tests/test_dialogue.gd @@ -0,0 +1,281 @@ +extends RefCounted +## The talking-head conversations on the real farm: every conversation saved in game/resources/ +## dialogue/ is sound; the box (DialogueBox) writes a line letter by letter (a beat after a full +## stop), goes on and skips by input, styles the words (speaker, line, BBCode), and puts each +## speaker's head on their side; the director (DialogueDirector) plays a conversation at its +## night's phase and delay, pauses the farm for it and lets it go after, puts the morning sign +## aside meanwhile, doesn't replay it on a retry but does on a new vacation, +## takes it down on a new morning, plays several in order, waits under a menu, and lets one that +## doesn't pause the game go on by itself. + +const P := CampaignController.Phase +const DT := 1.0 / 60.0 + +var r: GameTestRunner +var sim: FarmSim +var c: CampaignController +var director: DialogueDirector +var box: DialogueBox +var alien: DialogueSpeaker +var scarecrow: DialogueSpeaker + + +func run(p_r: GameTestRunner) -> void: + r = p_r + _saved() + var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D + r.root.add_child(farm) + await r.process_frame + await r.physics_frame + sim = farm.get_node("FarmSim") as FarmSim + sim.set_physics_process(false) + c = sim.campaign + director = sim.dialogue + r.check(director != null and director.box != null and director.box.get_parent() == farm.get_node("Hud"), + "the farm has a dialogue director, its box in the HUD") + if director == null: + farm.queue_free() + return + box = director.box + director.conversations.clear() # this suite's own conversations only + alien = _speaker("Little Green Alien", DialogueSpeaker.HeadSide.LEFT, "thief") + scarecrow = _speaker("Scarecrow", DialogueSpeaker.HeadSide.RIGHT, "portrait") + _writing() + _input() + _style() + await _triggers() + _order_and_menus() + _not_paused() + director.stop() + r.paused = false + farm.queue_free() + await r.process_frame + + +## Every conversation saved with the game loads, has lines with words, and plays within the vacation. +func _saved() -> void: + var all := DialogueDirector.load_all(DialogueDirector.DIR) + var nights: int = (load("res://game/resources/game_config.tres") as GameConfig).campaign_nights + var bad: Array[String] = [] + for conv in all: + if conv.lines.is_empty() or conv.night < 1 or conv.night > nights: + bad.append(conv.resource_path) + for line in conv.lines: + if line == null or line.text.strip_edges() == "": + bad.append(conv.resource_path) + r.check(bad.is_empty(), "every saved conversation has lines with words and plays within the vacation (bad: %s)" % [bad]) + r.check(DialogueDirector.load_all("res://game/resources/dialogue/speakers/").is_empty(), + "a speaker's file isn't taken for a conversation") + + +func _writing() -> void: + var conv := _conversation(1, P.MORNING, 0.0, [_line(alien, "Hi. There"), _line(scarecrow, "Hello!")]) + alien.letters_per_second = 10.0 + r.check(box.play(conv) and box.is_playing() and box.visible and box.written_text() == "" and box.speaker_name() == "Little Green Alien", + "play() puts the first line up, nothing written yet, under the speaker's name") + r.check(not box.play(_conversation(1, P.MORNING, 0.0, [])) and box.conversation == conv, "a conversation without lines isn't shown") + _frames(0.25) + r.check(box.written_text() == "Hi", "letters come at the speaker's speed (10 a second: '%s' after 0.25 s)" % box.written_text()) + _frames(0.2) + var at_stop := box.written_text() + _frames(0.2) + r.check(at_stop == "Hi." and box.written_text() == "Hi.", "a beat after a full stop ('%s', still '%s' 0.2 s on)" % [at_stop, box.written_text()]) + _frames(0.5) + r.check(box.written_text().begins_with("Hi. T"), "then the words go on ('%s')" % box.written_text()) + box.advance() + r.check(box.is_written() and box.written_text() == "Hi. There" and box.index == 0, "going on mid-line writes the rest of it") + box.advance() + r.check(box.index == 1 and box.speaker_name() == "Scarecrow", "going on again: the next line, the next speaker") + r.check(box._heads.size() == 2 and box._heads[0].leaving and box._heads[1].speaker == scarecrow, + "the new speaker's head comes up; the last one's goes down") + var done: Array[Conversation] = [] + box.finished.connect(func(f: Conversation) -> void: done.append(f), CONNECT_ONE_SHOT) + box.advance() + box.advance() + r.check(done.size() == 1 and done[0] == conv and not box.is_playing(), "after the last line the conversation is finished") + _frames(0.6) + r.check(not box.visible and box._heads.is_empty(), "and the box fades away, the head sinking") + alien.letters_per_second = 45.0 + + +func _input() -> void: + var conv := _conversation(1, P.MORNING, 0.0, [_line(alien, "One"), _line(alien, "Two"), _line(alien, "Three")]) + box.play(conv) + r.check(box.mouse_filter == Control.MOUSE_FILTER_STOP and box.has_focus(), "a conversation that pauses the game takes the clicks and the keys") + var click := InputEventMouseButton.new() + click.button_index = MOUSE_BUTTON_LEFT + click.pressed = true + box._gui_input(click) + r.check(box.is_written() and box.index == 0, "a click writes the rest of the line") + box._gui_input(_action("ui_accept")) + r.check(box.index == 1, "Enter (ui_accept) goes on to the next") + box.blocked = func() -> bool: return true + box._gui_input(_action("ui_accept")) + box._gui_input(_action("ui_accept")) + _frames(1.0) + r.check(box.index == 1 and box.written_text() == "", "under a menu (blocked) it takes no input and writes nothing") + box.blocked = Callable() + box._gui_input(_action("hide_tips")) + r.check(not box.is_playing(), "Backspace (hide_tips) skips the rest of the conversation") + r.check(box.mouse_filter == Control.MOUSE_FILTER_IGNORE and not box.has_focus(), "and lets the clicks and keys go again") + box.stop() + + +func _style() -> void: + var line := _line(scarecrow, "I [b]said[/b] go.") + line.italic = true + line.font_size = 50 + line.text_color = Color.RED + box.play(_conversation(1, P.MORNING, 0.0, [line, _line(null, "The wind blows.")])) + var t := box._text + r.check(t.text == "[i]I [b]said[/b] go.[/i]" and box._plain == "I said go.", "a line in italics, its BBCode kept ('%s')" % t.text) + r.check(t.get_theme_font_size("normal_font_size") == 50 and t.get_theme_color("default_color") == Color.RED, + "a line's size and color over the speaker's") + r.check(t.get_theme_font("italics_font") is FontVariation and (t.get_theme_font("italics_font") as FontVariation).base_font == Sketch.font(), + "italics are the handwritten font, slanted") + r.check(box._name.horizontal_alignment == HORIZONTAL_ALIGNMENT_RIGHT and t.horizontal_alignment == HORIZONTAL_ALIGNMENT_RIGHT, + "a speaker on the right has their name and words on the right") + _frames(0.5) + var head := box._current_head() + var r_sheet := box._sheet_rect() + r.check(head != null and head.speaker == scarecrow and head.risen == 1.0 and r_sheet.size.x == DialogueBox.WIDTH + and absf(r_sheet.end.y - (box.size.y - DialogueBox.BOTTOM)) < 0.01, "their head is up, the paper over the hotbar") + box.advance() + box.advance() + r.check(box.speaker_name() == "" and not box._name.visible and box._current_head() == null, "a line without a speaker: words only") + box.stop() + + +func _triggers() -> void: + var morning := _conversation(2, P.MORNING, 0.0, [_line(alien, "Morning.")]) + var night := _conversation(2, P.NIGHT, 5.0, [_line(scarecrow, "Night.")]) + director.conversations.assign([morning, night]) + c.new_campaign() + _tick() + r.check(not box.is_playing(), "night 1: nothing to say") + _to_morning(2) + await r.process_frame # the morning sign takes the focus (deferred) + await r.process_frame + _tick() + r.check(box.conversation == morning and r.paused, "the morning of day 2: its conversation, the farm paused") + r.check(box.has_focus() and not sim.review_panel.visible, "the morning sign waits; the box has the keys (Enter doesn't start the day)") + box.skip() + r.check(not r.paused and not director.is_playing() and sim.review_panel.visible, "done: the farm goes on, the morning sign is back") + await r.process_frame + r.check(sim.review_panel._start.has_focus(), "with Start the day focused") + c.retry_night() + _tick() + r.check(not box.is_playing(), "a retry doesn't play it again") + c.begin_day() + c.advance_phase() + c.advance_phase() + _tick() + r.check(c.state.phase == P.NIGHT and not box.is_playing(), "the night's conversation waits for its delay") + c.state.phase_time_left = c.phase_length(P.NIGHT) - 5.5 + _tick() + r.check(box.conversation == night and r.paused, "5 s into night 2: it plays") + c.retry_night() + r.check(not box.is_playing() and not r.paused, "a new morning (here a retry) takes it down") + c.new_campaign() + _to_morning(2) + _tick() + r.check(box.conversation == morning, "a new vacation plays them again") + director.stop() + + +func _order_and_menus() -> void: + var late := _conversation(3, P.MORNING, 2.0, [_line(alien, "Second.")]) + var early := _conversation(3, P.MORNING, 1.0, [_line(alien, "First.")]) + var asked := _conversation(1, P.MORNING, 0.0, [_line(scarecrow, "Asked.")]) + director.conversations.assign([late, early]) + _to_morning(3) + _tick() + r.check(box.conversation == early, "several at once: by delay") + director.play(asked) + box.skip() + r.check(box.conversation == asked and r.paused, "play() while one is up: right after it, the farm still paused") + box.skip() + r.check(box.conversation == late, "then the rest") + box.skip() + r.check(not director.is_playing() and not r.paused, "then the farm goes on") + director.conversations.assign([_conversation(4, P.MORNING, 0.0, [_line(alien, "Wait.")])]) + box.blocked = func() -> bool: return true + _to_morning(4) + _tick() + r.check(not box.is_playing(), "under Main's menus nothing starts") + box.blocked = Callable() + sim.upgrade_panel.is_open = true + _tick() + r.check(not box.is_playing(), "nor while a shop is open") + sim.upgrade_panel.is_open = false + _tick() + r.check(box.is_playing(), "after them, it does") + box.skip() + director.replay() + r.check(box.is_playing(), "replay() plays this phase's again") + director.stop() + + +func _not_paused() -> void: + var conv := _conversation(5, P.MORNING, 0.0, [_line(alien, "Busy?"), _line(alien, "Never mind.")]) + conv.pause_game = false + director.conversations.assign([conv]) + _to_morning(5) + _tick() + r.check(box.conversation == conv and not r.paused and box.mouse_filter == Control.MOUSE_FILTER_IGNORE and not box.has_focus(), + "one that doesn't pause the game takes no clicks or keys") + box._gui_input(_action("ui_accept")) + r.check(box.index == 0, "Enter is the game's") + _frames(0.5 + Conversation.AUTO_ADVANCE) + r.check(box.index == 1, "its lines go on by themselves") + _frames(0.5 + Conversation.AUTO_ADVANCE) + r.check(not box.is_playing(), "and it ends by itself") + + +func _to_morning(n: int) -> void: + var s := c.state + s.night = n + s.nights_survived = n - 1 + c.load_state(s) + + +## The director's frame (it starts what's due). +func _tick() -> void: + director._process(DT) + + +## The box's frames for seconds. +func _frames(seconds: float) -> void: + for i in roundi(seconds / DT): + box._process(DT) + + +func _action(name: String) -> InputEventAction: + var e := InputEventAction.new() + e.action = StringName(name) + e.pressed = true + return e + + +static func _speaker(n: String, side: DialogueSpeaker.HeadSide, icon: String) -> DialogueSpeaker: + var sp := DialogueSpeaker.new() + sp.display_name = n + sp.side = side + sp.icon = icon + return sp + + +static func _line(sp: DialogueSpeaker, text: String) -> DialogueLine: + var l := DialogueLine.new() + l.speaker = sp + l.text = text + return l + + +static func _conversation(n: int, phase: CampaignController.Phase, delay: float, lines: Array[DialogueLine]) -> Conversation: + var conv := Conversation.new() + conv.night = n + conv.phase = int(phase) as Conversation.Phase + conv.delay = delay + conv.lines = lines + return conv diff --git a/game/tests/test_dialogue.gd.uid b/game/tests/test_dialogue.gd.uid new file mode 100644 index 0000000..4038766 --- /dev/null +++ b/game/tests/test_dialogue.gd.uid @@ -0,0 +1 @@ +uid://2v2ctiydeo6v