harvest/game/tests/mobile/buttons_test.gd
Forrest e435b76aa2 #38: touch action buttons
TouchButtons (phones only, Main adds it beside TouchSticks): Pause, Fear, Bomb,
Patch, Use (word from the new read-only Interactions.focus_info()) and Build,
round Sketch buttons that press the existing actions for at least one physics
tick, shown only when they can do something and hidden whenever the tree is
paused or a menu, panel or sign is up. Columns follow TouchSticks.move_on_right
(now a variable); both join "touch_controls" with apply_settings (Swap sticks),
which Main calls at startup; Prompts.move_side() reads the live sticks. Stick
fingers keep their drags over buttons. New Sketch icons: fear, patch, use,
build, pause. Test: game/tests/mobile/buttons_test.gd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:25:57 -04:00

495 lines
21 KiB
GDScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

extends RefCounted
## #38, the touch buttons (TouchButtons) by touch, through the game's entry scene (main.tscn, with
## test save and settings paths) on a 19.5:9 phone (2340x1080) with a simulated notch and home
## indicator (MobilePort.preview_insets):
## * On a phone Main adds them beside the sticks. Each is inside the safe area, at least the
## minimum target, clear of the HUD's widgets (the radar's too, once owned; the build bar in
## build mode), of #39's hit targets, and of each other; Fear, Bomb, and Patch on the attack
## side, Use and Build on the move side, Pause beside the day widget.
## * They show only when they can do something: none at the main menu, in the morning sign, in a
## conversation that pauses the farm, in the pause menu, or with a shop's menu up; by day Pause,
## Fear, and Build; Use only with something in reach (its word from Interactions.focus_info);
## Bomb once owned; Patch when hurt with straw; Build not at night.
## * Each does what its key does, by touch: Fear starts its cooldown (its ring); holding Patch
## heals after patch_time (its ring fills); holding Use gathers at a point (its ring fills);
## tapping Use by day opens the shed's shop, and the workbench's once it's granted; Build enters
## build mode ("Done") and leaves it; Bomb throws along the attack stick's last aim; Pause
## opens the pause menu and lets a held button go. A quick tap (down and up at once) counts.
## * A touch on a shown button starts no stick; one where a hidden button would be does; a stick
## finger sliding over a shown button keeps steering, and doesn't press it.
## * apply_settings with Swap sticks (as GameSettings.apply will call it, group touch_controls):
## the move stick, the button columns, and the tips' side (Prompts.move_side) swap, and back.
## * Desktop (forced 0): no TouchButtons (nor sticks), and fire keeps its mouse button.
## The InputMap's mouse buttons for fire and offhand (TouchSticks erases them) are put back.
const Touch := preload("res://game/tests/mobile/touch.gd")
const SAVE := "user://test_buttons_save.json"
const SETTINGS := "user://test_buttons_settings.cfg"
const PHONE := Vector2i(2340, 1080)
const INSETS := [140.0, 0.0, 140.0, 60.0]
const AWAY := Vector3(-11.0, 0.0, 13.0) # nothing in reach there (as in the other suites)
const PAUSE := TouchButtons.PAUSE
const FEAR := TouchButtons.FEAR
const BOMB := TouchButtons.BOMB
const PATCH := TouchButtons.PATCH
const USE := TouchButtons.USE
const BUILD := TouchButtons.BUILD
## #39's hit targets at this phone's scale (its notes): the hotbar's slots, the backpack, and the
## tip box's ×; and the dialogue's Skip (only up while a conversation pauses the farm).
const HUD_TARGETS: Array[Rect2] = [Rect2(533.0, 584.0, 267.0, 72.0), Rect2(26.0, 542.0, 108.0, 108.0),
Rect2(1063.0, 215.0, 60.0, 60.0)]
const SKIP := Rect2(1193.0, 496.0, 118.0, 68.0)
const TALK := "res://game/resources/dialogue/morning_day_2.tres"
const ACTIONS: Array[StringName] = [&"fear", &"offhand", &"patch", &"interact", &"build_mode", &"fire", &"move_left",
&"move_right", &"move_forward", &"move_back", &"aim_left", &"aim_right", &"aim_up", &"aim_down"]
var t: GameTestRunner
var main: Main
var sim: FarmSim
var buttons: TouchButtons
var sticks: TouchSticks
func run(p_t: GameTestRunner) -> void:
t = p_t
_clean()
var bindings := {}
for action: StringName in [&"fire", &"offhand"]:
bindings[action] = InputMap.action_get_events(action)
var size := t.root.size
var factor := t.root.content_scale_factor
MobilePort.forced = 1
MobilePort.preview_insets = INSETS
t.root.size = PHONE
main = await _start()
sim = main.sim
buttons = main.farm.get_node_or_null("Hud/TouchButtons") as TouchButtons
sticks = main.farm.get_node_or_null("Hud/TouchSticks") as TouchSticks
t.check(buttons != null and sticks != null, "a phone: Main adds TouchButtons beside TouchSticks")
if buttons != null and sticks != null:
await _buttons()
await _stop()
for action: StringName in bindings:
InputMap.action_erase_events(action)
for e: InputEvent in bindings[action]:
InputMap.action_add_event(action, e)
for action in ACTIONS:
Input.action_release(action)
_clean()
MobilePort.forced = 0
MobilePort.preview_insets = []
t.root.size = size
t.root.content_scale_factor = factor
main = await _start()
t.check(main.farm.get_node_or_null("Hud/TouchButtons") == null and main.farm.get_node_or_null("Hud/TouchSticks") == null,
"desktop: no touch buttons or sticks")
var mouse_fire := InputMap.action_get_events("fire").filter(func(e: InputEvent) -> bool: return e is InputEventMouseButton)
t.check(not mouse_fire.is_empty(), "desktop: fire keeps its mouse button")
await _stop()
MobilePort.forced = -1
t.root.size = size
t.root.content_scale_factor = factor
_clean()
func _clean() -> void:
for p in [SAVE, SAVE + ".tmp", SETTINGS]:
if FileAccess.file_exists(p):
DirAccess.remove_absolute(ProjectSettings.globalize_path(p))
func _start() -> Main:
var m := (load("res://game/scenes/main.tscn") as PackedScene).instantiate() as Main
m.save_path = SAVE
m.settings_path = SETTINGS
t.root.add_child(m)
await t.process_frame
await t.process_frame
return m
func _stop() -> void:
main.queue_free()
t.paused = false
await t.process_frame
await t.process_frame
func _physics(n: int) -> void:
for k in n:
await t.physics_frame
## A few physics ticks, then two frames (the buttons update in _process).
func _settle(ticks: int = 3) -> void:
await _physics(ticks)
await t.process_frame
await t.process_frame
func _pad(id: StringName) -> TouchButtons.Pad:
return buttons.pad(id)
func _at(id: StringName) -> Vector2:
return _pad(id).get_global_rect().get_center()
## The buttons shown, in TouchButtons.ALL's order.
func _shown() -> Array:
var out := []
for id in TouchButtons.ALL:
if _pad(id).visible:
out.append(id)
return out
## A quick tap on a button: down and up in the same instant.
func _tap(id: StringName, finger := 7) -> void:
Touch.tap(finger, _at(id))
func _held() -> Array:
return ACTIONS.filter(func(a: StringName) -> bool: return Input.is_action_pressed(a))
## Puts the scarecrow beside a node (inside reach), trying four sides, until its hands focus it as
## kind. Returns whether they do.
func _go_to(n: Node3D, reach: float, kind: String) -> bool:
for dir: Vector3 in [Vector3(0, 0, 1), Vector3(1, 0, 0), Vector3(-1, 0, 0), Vector3(0, 0, -1)]:
sim.player.global_position = Vector3(n.global_position.x, 0.0, n.global_position.z) + dir * reach * 0.6
await _settle(4)
if sim.interactions.focus == n and sim.interactions.focus_info().get("kind", "") == kind:
return true
return false
func _away() -> void:
sim.player.global_position = AWAY
await _settle(4)
func _buttons() -> void:
t.check(buttons.mouse_filter == Control.MOUSE_FILTER_IGNORE and _pad(FEAR).mouse_filter == Control.MOUSE_FILTER_STOP,
"the buttons are STOP Controls in an IGNORE one")
await t.process_frame
t.check(_shown().is_empty(), "at the main menu no button shows (%s)" % [_shown()])
main.new_vacation(false)
await _settle()
t.check(_shown().is_empty(), "the morning sign: no buttons (%s)" % [_shown()])
sim.campaign.advance_phase() # morning -> day
await _talk_if_any()
await _away()
t.check(_shown() == [PAUSE, FEAR, BUILD], "by day with nothing in reach: Pause, Fear, Build (%s)" % [_shown()])
await _talk()
_layout("by day")
sim.campaign.state.upgrades["radar"] = 1
await _settle(1)
_layout("with the radar")
sim.campaign.state.upgrades.erase("radar")
await _fear()
await _build()
await _gather()
await _shops()
await _patch()
await _bomb()
await _blocking()
await _swap()
await _pause()
await _night()
t.check(_held().is_empty(), "nothing left held (%s)" % [_held()])
## A conversation that pauses the farm (day 2's morning one, played now): no buttons while it's
## up, so its paper and Skip get the touches; then skipped.
func _talk() -> void:
sim.dialogue.play(load(TALK) as Conversation)
await t.process_frame
await t.process_frame
t.check(t.paused and sim.dialogue.box.conversation != null and sim.dialogue.box.conversation.pause_game,
"a conversation that pauses the farm is up")
t.check(_shown().is_empty() and not _pad(PAUSE).get_rect().intersects(SKIP),
"while it's up no button shows, so its paper and Skip get the touches (%s)" % [_shown()])
sim.dialogue.box.skip()
await t.process_frame
await t.process_frame
t.check(not t.paused and _shown().has(PAUSE), "skipped: the buttons are back")
## The layout: inside the safe area, at least the minimum target, round, clear of the HUD's
## widgets, #39's targets, and each other; each column on its side; Pause beside the day widget.
func _layout(what: String) -> void:
buttons.layout()
var safe := MobilePort.safe_rect(buttons)
var target := MobilePort.minimum_target(buttons)
var keep := buttons.reserved()
keep.append_array(HUD_TARGETS)
var inside := true
var big := true
var clear := true
var apart := true
var why := ""
var rects := {}
for id in TouchButtons.ALL:
var r := _pad(id).get_rect()
rects[id] = r
inside = inside and safe.grow(0.01).encloses(r)
big = big and r.size.x >= target - 0.01 and is_equal_approx(r.size.x, r.size.y)
for k in keep:
if r.intersects(k):
clear = false
why += " %s over %s;" % [id, k]
for i in TouchButtons.ALL.size():
for j in range(i + 1, TouchButtons.ALL.size()):
if (rects[TouchButtons.ALL[i]] as Rect2).intersects(rects[TouchButtons.ALL[j]]):
apart = false
why += " %s over %s;" % [TouchButtons.ALL[i], TouchButtons.ALL[j]]
t.info("%s: canvas %s, safe %s, buttons %s" % [what, buttons.size, safe, rects])
t.check(t.root.content_scale_factor > 1.5, "%s: at the phone's scale (%.2f)" % [what, t.root.content_scale_factor])
t.check(inside, "%s: every button inside the safe area %s" % [what, safe])
t.check(big, "%s: each round and at least the minimum target (%.0f px; Fear %s)" % [what, target, rects[FEAR]])
t.check(clear, "%s: clear of the HUD's widgets and #39's targets%s" % [what, why])
t.check(apart, "%s: clear of each other%s" % [what, why])
var mid := buttons.size.x * 0.5
var sides := true
for id in TouchButtons.ATTACK_COLUMN:
sides = sides and ((rects[id] as Rect2).get_center().x > mid) != buttons.move_on_right
for id in TouchButtons.MOVE_COLUMN:
sides = sides and ((rects[id] as Rect2).get_center().x > mid) == buttons.move_on_right
var order: bool = (rects[FEAR] as Rect2).end.y <= (rects[BOMB] as Rect2).position.y \
and (rects[BOMB] as Rect2).end.y <= (rects[PATCH] as Rect2).position.y and (rects[USE] as Rect2).end.y <= (rects[BUILD] as Rect2).position.y
t.check(sides and order, "%s: Fear, Bomb, Patch down the %s edge; Use, Build down the %s edge" % [what,
"left" if buttons.move_on_right else "right", "right" if buttons.move_on_right else "left"])
var day := sim.phase_hud.widget_rect()
var p: Rect2 = rects[PAUSE]
t.check(p.end.x <= day.position.x and p.end.y > day.position.y and p.position.y < day.end.y and p.position.y < buttons.size.y * 0.2,
"%s: Pause at the top edge, beside the day widget (%s; the widget %s)" % [what, p, day])
func _fear() -> void:
var kit := sim.scarecrow
var used: Array[int] = []
kit.fear_used.connect(func(_p: Vector3, _n: int) -> void: used.append(0))
t.check(_pad(FEAR).lit and _pad(FEAR).word == "Fear", "Fear is lit while it's ready")
_tap(FEAR)
await _settle()
t.check(used.size() == 1 and kit.fear_left > 0.0, "a quick tap on Fear scares, once, and starts its cooldown (%.1f s left)" % kit.fear_left)
t.check(not Input.is_action_pressed("fear") and not _pad(FEAR).held(), "and lets fear go")
var ring := _pad(FEAR).ring
t.check(not _pad(FEAR).lit and ring >= 0.0 and ring < 0.25, "Fear's ring shows the recharge (%.2f)" % ring)
kit.fear_left = 0.0
func _build() -> void:
t.check(_pad(BUILD).visible and _pad(BUILD).word == "Build", "Build by day")
_tap(BUILD)
await _settle()
t.check(sim.build.active and _pad(BUILD).word == TouchButtons.DONE, "a tap on Build enters build mode; it says Done")
t.check(not _pad(USE).visible, "no Use in build mode")
_layout("in build mode")
_tap(BUILD)
await _settle()
t.check(not sim.build.active and _pad(BUILD).word == "Build", "a tap on Done leaves it")
t.check(not Input.is_action_pressed("build_mode"), "build_mode let go")
func _gather() -> void:
var it := sim.interactions
var node: GatherNode = null
for n in it.nodes:
if it.charges(n) > 0 and not sim.zones.zone_at(n.global_position).outside:
node = n
break
var ok := false
if node != null:
ok = await _go_to(node, node.reach, "gather")
t.check(ok,"the scarecrow stands at a gather point (%s)" % (node.name if node != null else "none"))
if not ok:
return
t.check(_pad(USE).visible and _pad(USE).word == "Gather" and not _pad(USE).dim, "at a gather point by day: Use, 'Gather'")
var got: Array[int] = []
it.gathered.connect(func(_m: String, amount: int, _n: GatherNode) -> void: got.append(amount))
var at := _at(USE)
var half := roundi(sim.config.gather_time * Engine.physics_ticks_per_second * 0.5)
Touch.touch(3, at, true)
await _settle(half)
t.check(it.gathering == node and _pad(USE).ring > 0.25 and _pad(USE).ring < 0.75,
"holding Use gathers; its ring fills (%.2f)" % _pad(USE).ring)
await _settle(half + 10)
t.check(got.size() >= 1, "holding Use gathers at a point (+%s %s)" % [got, node.material])
Touch.touch(3, at, false)
await _settle()
t.check(not Input.is_action_pressed("interact") and it.gathering == null, "lifting the finger stops gathering")
func _shops() -> void:
var it := sim.interactions
var counter := it.shed_counter
var ok := await _go_to(counter, counter.reach, "shed")
t.check(ok and _pad(USE).visible and _pad(USE).word == "Shop", "at the shed counter by day: Use, 'Shop' (workbench not granted yet: %s)"
% (not sim.structures.has_workbench()))
_tap(USE)
await _settle()
t.check(sim.shed_panel.is_open, "a tap on Use there opens the shed's shop")
t.check(_shown().is_empty() and not Input.is_action_pressed("interact"), "with a shop's menu up no button shows (%s), interact let go" % [_shown()])
sim.shed_panel.close()
sim.structures.grant_workbench()
ok = await _go_to(it.workbench, it.workbench.reach, "workbench")
t.check(ok and _pad(USE).visible and _pad(USE).word == "Workbench", "at the granted workbench: Use, 'Workbench'")
_tap(USE)
await _settle()
t.check(sim.upgrade_panel.is_open and _shown().is_empty(), "a tap on Use there opens the workbench's menu")
sim.upgrade_panel.close()
await _away()
func _patch() -> void:
var s := sim.campaign.state
var kit := sim.scarecrow
s.resources.shed["straw"] = 0
s.resources.pouch_of(kit.slot)["straw"] = 0
s.scarecrow_hp = s.scarecrow_max_hp - 1
await _settle(1)
t.check(not _pad(PATCH).visible, "no Patch when hurt without straw")
s.resources.shed["straw"] = 10
s.scarecrow_hp = s.scarecrow_max_hp
await _settle(1)
t.check(not _pad(PATCH).visible, "nor at full health")
s.scarecrow_hp = s.scarecrow_max_hp - 1
await _settle(1)
t.check(_pad(PATCH).visible and _pad(PATCH).ring < 0.0, "hurt with straw: Patch")
var patched: Array[int] = []
kit.patched.connect(func(hp: int) -> void: patched.append(hp))
var at := _at(PATCH)
var half := roundi(sim.config.patch_time * Engine.physics_ticks_per_second * 0.5)
Touch.touch(2, at, true)
await _settle(half)
t.check(kit.patching and patched.is_empty() and _pad(PATCH).ring > 0.3 and _pad(PATCH).ring < 0.7,
"holding Patch patches up; its ring fills (%.2f)" % _pad(PATCH).ring)
await _settle(half + 10)
t.check(patched.size() == 1 and s.scarecrow_hp == s.scarecrow_max_hp, "holding Patch heals after %.1f s (HP %d/%d)"
% [sim.config.patch_time, s.scarecrow_hp, s.scarecrow_max_hp])
t.check(not _pad(PATCH).visible and not Input.is_action_pressed("patch"), "at full health Patch hides and lets go, finger still down")
Touch.touch(2, at, false)
await _settle()
func _bomb() -> void:
t.check(not _pad(BOMB).visible, "no Bomb before pumpkin bombs are owned")
sim.campaign.state.upgrades["pumpkin_bomb"] = 1
await _settle()
t.check(_pad(BOMB).visible and _pad(BOMB).lit, "Bomb once they're owned, lit (one in hand)")
# Aim with the attack stick (screen right), then let it go: the aim stays.
var w := sticks.size
var left := Vector2(w.x * 0.3, w.y * 0.45)
Touch.touch(1, left, true)
Touch.drag(1, left, left + Vector2(TouchSticks.RADIUS, 0.0))
await _physics(12)
Touch.touch(1, left + Vector2(TouchSticks.RADIUS, 0.0), false)
await _settle()
var aim := sim.combat.aim
var throws: Array[Vector3] = []
sim.combat.threw.connect(func(to: Vector3) -> void: throws.append(to))
_tap(BOMB)
await _settle(4)
var p := sim.player.global_position
t.check(throws.size() == 1, "a quick tap on Bomb throws one (%d)" % throws.size())
if throws.size() == 1:
var to := Vector2(throws[0].x - p.x, throws[0].z - p.z)
var want := clampf(ScarecrowCombat.GAMEPAD_THROW, sim.config.bomb_min_range, sim.config.bomb_range)
t.check(to.normalized().dot(aim) > 0.95 and absf(to.length() - want) < 0.75,
"along the attack stick's last aim, %.1f m out (dot %.2f)" % [to.length(), to.normalized().dot(aim)])
var ring := _pad(BOMB).ring
t.check(not Input.is_action_pressed("offhand") and not _pad(BOMB).lit and ring >= 0.0 and ring < 0.3,
"offhand let go; Bomb's ring shows the recharge (%.2f)" % ring)
func _blocking() -> void:
# A touch on a shown button is the button's: no stick.
var at := _at(BUILD)
Touch.touch(4, at, true)
await t.process_frame
t.check(sticks.finger[TouchSticks.Stick.MOVE] == -1 and sticks.finger[TouchSticks.Stick.ATTACK] == -1 and _pad(BUILD).held(),
"a touch on a shown button (Build) is the button's: no stick starts")
Touch.touch(4, at, false)
await _settle()
_tap(BUILD) # (back out of build mode)
await _settle()
t.check(not sim.build.active, "(out of build mode again)")
# Where a hidden button would be, the stick's.
t.check(not _pad(USE).visible, "Use hidden (nothing in reach)")
var use_at := _at(USE)
Touch.touch(4, use_at, true)
await t.process_frame
t.check(sticks.finger[TouchSticks.Stick.MOVE] == 4, "a touch where a hidden button (Use) would be starts the move stick")
# That finger slides over a shown button (Build): it still steers, and Build isn't pressed.
Touch.drag(4, use_at, at)
await t.process_frame
var tilt := sticks.tilt[TouchSticks.Stick.MOVE]
t.check(tilt.length() > 0.3 and tilt.normalized().dot((at - use_at).normalized()) > 0.99 and not _pad(BUILD).held(),
"sliding the stick's finger over Build keeps steering (tilt %s); Build stays up" % tilt)
Touch.touch(4, at, false)
await _settle()
t.check(sticks.finger[TouchSticks.Stick.MOVE] == -1 and not sim.build.active, "lifting it there lets the stick go, and Build wasn't pressed")
func _swap() -> void:
var s := GameSettings.new()
s.swap_sticks = true
t.call_group(TouchSticks.GROUP, &"apply_settings", s)
await _settle(1)
t.check(not sticks.move_on_right and not buttons.move_on_right, "Swap sticks: the sticks and the buttons have the move stick on the left")
t.check(Prompts.move_side() == "left" and Prompts.attack_side() == "right", "and the tips say so (Prompts.move_side)")
var w := sticks.size
var left := Vector2(w.x * 0.3, w.y * 0.45)
Touch.touch(0, left, true)
await t.process_frame
t.check(sticks.finger[TouchSticks.Stick.MOVE] == 0, "a finger on the left half is the move stick now")
Touch.touch(0, left, false)
await _settle()
_layout("swapped")
sim.campaign.state.upgrades["radar"] = 1
await _settle(1)
_layout("swapped, with the radar")
sim.campaign.state.upgrades.erase("radar")
s.swap_sticks = false
t.call_group(TouchSticks.GROUP, &"apply_settings", s)
await _settle(1)
t.check(sticks.move_on_right and buttons.move_on_right and Prompts.move_side() == "right"
and sticks.side_of(Vector2(w.x * 0.75, w.y * 0.5)) == TouchSticks.Stick.MOVE, "and back")
_layout("swapped back")
func _pause() -> void:
# Hold Fear, then tap Pause with another finger.
var at := _at(FEAR)
Touch.touch(5, at, true)
await _settle(2)
t.check(Input.is_action_pressed("fear") and _pad(FEAR).held(), "holding Fear holds fear")
_tap(PAUSE, 6)
await t.process_frame
await t.process_frame
t.check(main.screen == Main.Screen.PAUSED and main.pause_menu.visible and t.paused, "a tap on Pause opens the pause menu")
t.check(not Input.is_action_pressed("fear") and not _pad(FEAR).held(), "the pause lets the held button go")
t.check(_shown().is_empty(), "paused: no buttons (%s)" % [_shown()])
Touch.touch(5, at, false)
main.resume()
await _settle()
t.check(_shown().has(PAUSE) and not Input.is_action_pressed("fear"), "resumed: the buttons are back, nothing held")
sim.scarecrow.fear_left = 0.0
func _night() -> void:
sim.campaign.advance_phase() # day -> dusk
sim.campaign.advance_phase() # dusk -> night
await _talk_if_any()
await _settle()
t.check(not sim.campaign.is_daytime() and not _pad(BUILD).visible and _pad(FEAR).visible and _pad(PAUSE).visible,
"at night: no Build; Fear and Pause (%s)" % [_shown()])
func _talk_if_any() -> void:
for k in 10:
await t.process_frame
if t.paused and main.screen == Main.Screen.PLAYING and sim.dialogue != null and sim.dialogue.box.conversation != null:
sim.dialogue.box.skip()