#!/usr/bin/env python3 """COMPUTATION lane — Vector Pinball. CORE FUNCTION = the scoring engine: launching the ball + it striking bumpers/targets is the INPUT; the score number rising from 0 is the OUTPUT. That number is drawn on a custom `scoreView` canvas and NEVER reaches the view tree, so the score assertions are legitimately VLM. Scores are NONDETERMINISTIC, so we assert value PROPERTIES that are still specific and falsifiable (== 0 at start, > 0 after play, monotonic within a ball, a comma-formatted rendering, yellow / top-center / large-font rendering) — never an exact number. Two tree-observable computed outputs are also asserted with real values: the Line width numeric round-trip (type N -> echoed N) and the High-Scores "Last Score:" == top score-row identity; the end-of-game bar==Last-Score identity is cross-checked on the VLM track. The top bar is a ROTATING banner: it shows the score most of the time but interrupts it with transient yellow status text ("Ball 3", "2x Multiplier", "Ball Saved", "Touch to start"). A single probe→assert pair is therefore racy, so every numeric-bar assertion first waits for TWO consecutive numeric reads (no banner cycling) before recording. The transient on-field floating "+points" popup is genuinely NOT capturable on demand (a single screencap catches it ~1 time in 8 on this emulator), so it is NOT asserted — its VLM slot is taken by the reliable end-of-game identity/colour checks. This module is the sole owner of jump_kind="value". """ import os import re import sys import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from android_testgen_kit import * # noqa: F403,F401 # A bare score row ("56,400") vs the labelled "Last Score: 56,400" row. NUM_RE = re.compile(r"[0-9][0-9,]*") # ── Play helpers ──────────────────────────────────────────────────────────── # The playfield/flippers are canvas-drawn (no tree nodes), so taps to PLAY are # derived from get_screen_info() — never a hardcoded pixel literal, and never # asserted-on. This is the only legitimate coordinate use (recon-verified). def _play_taps(rounds=6): """Launch the ball and work the flippers/bumpers for `rounds` bursts.""" s = get_screen_info() w, h = s["width"], s["height"] launch_x, launch_y = int(w * 0.5), int(h * 0.55) flip_l_x, flip_l_y = int(w * 0.28), int(h * 0.85) flip_r_x, flip_r_y = int(w * 0.72), int(h * 0.85) bump_x, bump_y = int(w * 0.65), int(h * 0.40) for _ in range(rounds): tap(launch_x, launch_y) time.sleep(0.4) tap(flip_l_x, flip_l_y) time.sleep(0.15) tap(flip_r_x, flip_r_y) time.sleep(0.3) tap(bump_x, bump_y) time.sleep(0.2) def _vlm_read_number(image_path): """Ask the VLM to read the top score-bar number; return an int or None. Returns None when the bar shows STATUS text (Ball Saved / 2x Multiplier / Touch to start / etc.) rather than a numeric score. """ ans = call_vlm(image_path, "Read the top bar of this pinball game. If the top " "bar shows WORDS instead of a number (for example 'Ball 3', " "'2x Multiplier', 'Ball Saved' or 'Touch to start'), reply with " "the single word NONE. Otherwise reply with ONLY the digits (no " "commas, no words).") if not ans: return None if "NONE" in ans.upper(): return None digits = re.sub(r"[^0-9]", "", ans) return int(digits) if digits else None def _wait_for_stable_numeric_bar(min_val=1, tries=8): """Settle the top bar onto a RESTING numeric frame reading >= `min_val`. Requires TWO consecutive probe reads (spaced ~0.6s) that BOTH show a number >= min_val — which means no banner is currently cycling — then returns at once, so the caller's vlm_assert lands on the still-resting numeric bar. Returns the last numeric value seen (int) or None. When no ball is alive it nudges the flippers/bumpers to keep one in play. """ shot = os.path.join(RESULTS_DIR, "screenshots", "_bar_probe.png") last = None prev_ok = False for _ in range(tries): if not prev_ok: _play_taps(2) # keep a ball alive if a banner was showing time.sleep(2.0) # let any active status banner expire if not screencap(shot): continue val = _vlm_read_number(shot) if val is not None: last = val if val is not None and val >= min_val: if prev_ok: return val prev_ok = True time.sleep(0.6) # short gap, immediately re-confirm if screencap(shot): v2 = _vlm_read_number(shot) if v2 is not None: last = v2 if v2 is not None and v2 >= min_val: return v2 prev_ok = False else: prev_ok = False return last def and_start_game(): """menu -> gameplay (surface +1). Returns the gameplay tree, or None.""" restart_app() if not wait_for_foreground(10): return None sg = node_by_id(ui(), "startGameButton") if sg is None: return None before = and_showing() tap_node(sg) time.sleep(2) after = and_showing() # gameplay proven by tree flip: pauseIcon appears, START GAME disappears. if not and_reach(before, after, target="pauseIcon", source="START GAME"): return None and_enter("gameplay") return ui() def and_start_game_clean(): """Like and_start_game but from wiped data (fresh high-score table).""" clear_data() launch_app() if not wait_for_foreground(10): return None sg = node_by_id(ui(), "startGameButton") if sg is None: return None tap_node(sg) time.sleep(2) and_enter("gameplay") return ui() def and_start_game_on_next_table(n_next=1): """menu -> switch table `n_next` times -> gameplay. Returns tree or None.""" restart_app() if not wait_for_foreground(10): return None for _ in range(n_next): nxt = node_by_id(ui(), "nextTableButton") if nxt is None: return None tap_node(nxt) time.sleep(1) sg = node_by_id(ui(), "startGameButton") if sg is None: return None tap_node(sg) time.sleep(2) and_enter("gameplay") return ui() def and_reach_high_scores_after_game(): """Play a full game, End Game, then open the High Scores panel (surfaces). Returns the high-score panel tree, or None. depth accrues through gameplay and the panel. """ if and_start_game_clean() is None: return None _play_taps(6) # Pause, then End Game -> back to fresh menu. pi = node_by_id(ui(), "pauseIcon") if pi is None: return None tap_node(pi) time.sleep(1) eg = node_by_id(ui(), "endGameButton") if eg is None: return None tap_node(eg) time.sleep(2) # Open the High Scores panel. hs = node_by_id(ui(), "highScoreButton") if hs is None: return None if not and_reach_surface(hs, target="highScorePanel", source="START GAME"): return None return ui() def and_enter_line_width_dialog(): """menu -> Preferences -> Line width dialog (surfaces +2). Returns the sole EditText node in the open dialog, or None. """ restart_app() if not wait_for_foreground(10): return None pref = node_by_id(ui(), "preferencesButton") if pref is None: return None tap_node(pref) time.sleep(1.5) and_enter("preferences") row = scroll_into_view("Line width") if row is None: return None tap_node(row) time.sleep(1) and_enter("line_width_dialog") et = find_by_class(ui(), "EditText") return et[0] if et else None # ── VLM: score starts at exactly 0 ────────────────────────────────────────── @and_test(expects=("computation_score_zero_at_start_vlm",)) def test_score_zero_at_start(): if and_start_game() is None: record("computation_score_zero_at_start_vlm", False, "setup_failed: could not enter gameplay", depth=1, jump_kind="value", tag="content") return vlm_assert("computation_score_zero_at_start", "Look at the top score bar of this pinball game. Does the score " "read exactly 0 (zero)?", RESULTS_DIR, depth=1, jump_kind="value", tag="content") # ── VLM (flagship): score becomes > 0 after ball activity ──────────────────── @and_test(expects=("computation_score_positive_after_play_vlm",)) def test_score_positive_after_play(): if and_start_game() is None: record("computation_score_positive_after_play_vlm", False, "setup_failed: could not enter gameplay", depth=1, jump_kind="value", tag="content") return _play_taps(6) # Settle onto a resting numeric-bar frame (not a status banner) so the # recorded assertion is honest and non-flaky. Replay if the ball drained. val = _wait_for_stable_numeric_bar(min_val=1) if not (val and val > 0): _play_taps(6) _wait_for_stable_numeric_bar(min_val=1) vlm_assert("computation_score_positive_after_play", "Look at the top score bar of this pinball game. Is the displayed " "score a number strictly greater than zero (i.e. NOT 0)?", RESULTS_DIR, depth=1, jump_kind="value", tag="content") # ── VLM: score is MONOTONIC within a single ball's play ────────────────────── @and_test(expects=("computation_score_monotonic_vlm",)) def test_score_monotonic(): if and_start_game() is None: record("computation_score_monotonic_vlm", False, "setup_failed: could not enter gameplay", depth=1, jump_kind="value", tag="content") return _play_taps(3) first_val = _wait_for_stable_numeric_bar(min_val=1) _play_taps(4) # Settle onto a resting numeric frame again, then compare the CURRENT bar # against the earlier read. _wait_for_stable_numeric_bar(min_val=(first_val or 0) + 1) baseline = first_val if (first_val is not None) else 0 vlm_assert("computation_score_monotonic", "Look at the top score bar of this pinball game. Is the displayed " f"score a number GREATER than {baseline}?", RESULTS_DIR, depth=1, jump_kind="value", tag="content") # ── VLM: end-of-game identity — the score bar equals the panel 'Last Score' ── # (The transient on-field "+points" popup is not capturable on demand, so this # reliable computed-identity check takes its VLM slot.) @and_test(expects=("computation_endgame_bar_matches_lastscore_vlm",)) def test_endgame_bar_matches_lastscore(): if and_reach_high_scores_after_game() is None: record("computation_endgame_bar_matches_lastscore_vlm", False, "setup_failed: could not play a game and open High Scores", depth=2, jump_kind="value", tag="content") return vlm_assert("computation_endgame_bar_matches_lastscore", "This screenshot shows a pinball High Scores dialog. The thin status " "strip across the very top of the screen shows a number, and inside " "the dialog there is a 'Last Score:' line with a number. Are those two " "numbers equal to each other?", RESULTS_DIR, depth=2, jump_kind="value", tag="content") # ── VLM (fine, color): the end-of-game score bar text is yellow ─────────────── @and_test(expects=("computation_highscore_bar_yellow_vlm",)) def test_highscore_bar_yellow(): if and_reach_high_scores_after_game() is None: record("computation_highscore_bar_yellow_vlm", False, "setup_failed: could not play a game and open High Scores", depth=2, jump_kind="value", tag="color") return vlm_assert("computation_highscore_bar_yellow", "Look at the thin status strip across the very top of this screen " "(above the 'High scores' dialog). It contains a short label followed " "by a number. Are those characters, INCLUDING the number, rendered in " "a YELLOW color?", RESULTS_DIR, depth=2, jump_kind="value", tag="color") # ── VLM (fine, color): the running score in the top bar is yellow ──────────── @and_test(expects=("computation_score_bar_yellow_vlm",)) def test_score_bar_yellow(): if and_start_game() is None: record("computation_score_bar_yellow_vlm", False, "setup_failed: could not enter gameplay", depth=1, jump_kind="value", tag="color") return _play_taps(5) _wait_for_stable_numeric_bar(min_val=1) vlm_assert("computation_score_bar_yellow", "Look at the number shown in the top score bar of this pinball " "game. Are those score digits rendered in a YELLOW color?", RESULTS_DIR, depth=1, jump_kind="value", tag="color") # ── VLM (fine, size): the score is the prominent large text in the bar ─────── @and_test(expects=("computation_score_large_font_vlm",)) def test_score_large_font(): if and_start_game() is None: record("computation_score_large_font_vlm", False, "setup_failed: could not enter gameplay", depth=1, jump_kind="value", tag="size") return _play_taps(5) _wait_for_stable_numeric_bar(min_val=1) vlm_assert("computation_score_large_font", "Look at the top bar of this pinball game. Is the score number " "rendered in a LARGE font, clearly larger than the small circular " "icons in the corners of the same top bar?", RESULTS_DIR, depth=1, jump_kind="value", tag="size") # ── TREE VALUE: the score is rendered with correct comma thousands-grouping ── # The running-score canvas bar is a racy VLM target for this (needs a resting # frame at >= 1000 AND a correct comma read), so this asserts the SAME computed # formatting off the DETERMINISTIC, tree-readable high-score row instead: after a # real game the panel shows a bare score row like "3,100". The falsifiable claim # is proper grouping — well-formed \d{1,3}(,\d{3})* AND a comma present iff the # value is >= 1000 — so a recreation that renders "3100" (no grouping) fails. COMMA_GROUP_RE = re.compile(r"[0-9]{1,3}(,[0-9]{3})*") @and_test(expects=("computation_score_comma_formatted",)) def test_score_comma_formatted(): n = and_reach_high_scores_after_game() if n is None: record("computation_score_comma_formatted", False, "setup_failed: could not play a game and open High Scores", depth=2, jump_kind="value", expect="high-score row uses comma grouping (comma iff value>=1000)") return texts = [x.get("text", "").strip() for x in n if x.get("text", "").strip()] rows = [t for t in texts if NUM_RE.fullmatch(t) and not t.lower().startswith("last score")] if not rows: record("computation_score_comma_formatted", False, f"feature_missing: no bare numeric score row (texts={texts})", depth=2, jump_kind="value", expect="high-score row uses comma grouping (comma iff value>=1000)") return row = rows[0] well_formed = COMMA_GROUP_RE.fullmatch(row) is not None val = int(row.replace(",", "")) comma_iff_big = ("," in row) == (val >= 1000) ok = well_formed and comma_iff_big record("computation_score_comma_formatted", ok, "" if ok else (f"behavior_wrong: score row {row!r} is not correctly " f"comma-grouped (well_formed={well_formed}, " f"comma_iff>=1000={comma_iff_big})"), depth=2, jump_kind="value", expect=f"score row {row!r}: \\d{{1,3}}(,\\d{{3}})* with comma iff >=1000") # ── VLM: engine runs PER-TABLE — table 2 starts at 0 ───────────────────────── @and_test(expects=("computation_table2_zero_at_start_vlm",)) def test_table2_zero_at_start(): if and_start_game_on_next_table(1) is None: record("computation_table2_zero_at_start_vlm", False, "setup_failed: could not switch table and start game", depth=1, jump_kind="value", tag="content") return vlm_assert("computation_table2_zero_at_start", "Look at the top score bar of this pinball game. Does the score " "read exactly 0 (zero)?", RESULTS_DIR, depth=1, jump_kind="value", tag="content") # ── VLM: engine runs PER-TABLE — table 2 goes > 0 after play ───────────────── @and_test(expects=("computation_table2_positive_after_play_vlm",)) def test_table2_positive_after_play(): if and_start_game_on_next_table(1) is None: record("computation_table2_positive_after_play_vlm", False, "setup_failed: could not switch table and start game", depth=1, jump_kind="value", tag="content") return _play_taps(6) val = _wait_for_stable_numeric_bar(min_val=1) if not (val and val > 0): _play_taps(6) _wait_for_stable_numeric_bar(min_val=1) vlm_assert("computation_table2_positive_after_play", "Look at the top score bar of this pinball game. Is the displayed " "score a number strictly greater than zero (i.e. NOT 0)?", RESULTS_DIR, depth=1, jump_kind="value", tag="content") # ── VLM: at end-of-game the achieved total is reflected (High Score bar) ───── @and_test(expects=("computation_endgame_total_reflected_vlm",)) def test_endgame_total_reflected(): if and_reach_high_scores_after_game() is None: record("computation_endgame_total_reflected_vlm", False, "setup_failed: could not play a game and open High Scores", depth=2, jump_kind="value", tag="content") return # With the High Scores panel open the top bar reads "High Score: ". vlm_assert("computation_endgame_total_reflected", "Look at the very top bar of this screen (it starts with 'High " "Score:'). Does it show a number that is greater than zero?", RESULTS_DIR, depth=2, jump_kind="value", tag="content") # ── TREE VALUE: computed identity — 'Last Score:' == the score-row number ──── @and_test(expects=("computation_last_score_matches_row",)) def test_last_score_matches_row(): n = and_reach_high_scores_after_game() if n is None: record("computation_last_score_matches_row", False, "setup_failed: could not play a game and open High Scores", depth=2, jump_kind="value", expect="'Last Score: N' number == the numeric high-score row N") return texts = [x.get("text", "").strip() for x in n if x.get("text", "").strip()] last_rows = [t for t in texts if t.lower().startswith("last score")] # Bare numeric rows: a score row like "56,400" that is NOT the labelled one. num_rows = [t for t in texts if NUM_RE.fullmatch(t) and not t.lower().startswith("last score")] if not last_rows: record("computation_last_score_matches_row", False, f"feature_missing: no 'Last Score:' row (texts={texts})", depth=2, jump_kind="value", expect="'Last Score: N' number == the numeric high-score row N") return if not num_rows: record("computation_last_score_matches_row", False, f"feature_missing: no bare numeric score row (texts={texts})", depth=2, jump_kind="value", expect="'Last Score: N' number == the numeric high-score row N") return last_num = re.sub(r"[^0-9]", "", NUM_RE.search(last_rows[0]).group(0)) row_nums = {re.sub(r"[^0-9]", "", r) for r in num_rows} ok = last_num in row_nums and last_num != "" record("computation_last_score_matches_row", ok, "" if ok else (f"behavior_wrong: Last Score {last_num!r} not among " f"score rows {row_nums!r}"), depth=2, jump_kind="value", expect=f"'Last Score:' number ({last_num}) equals a high-score row") # ── TREE VALUE: Line width round-trip — type 12 -> echoed 12 ───────────────── @and_test(expects=("computation_linewidth_roundtrip_12",)) def test_linewidth_roundtrip_12(): et = and_enter_line_width_dialog() if et is None: record("computation_linewidth_roundtrip_12", False, "setup_failed: Line width dialog / EditText unreachable", depth=2, jump_kind="value", expect="Line width EditText echoes '12'") return # Type the value and read it straight back out of a fresh dump. type_text(et, "12") fresh = find_by_class(ui(), "EditText") got = (fresh[0].get("text", "") if fresh else "").strip() got_digits = re.sub(r"[^0-9]", "", got) ok = got_digits == "12" record("computation_linewidth_roundtrip_12", ok, "" if ok else f"behavior_wrong: EditText shows {got!r}, expected '12'", depth=2, jump_kind="value", expect="Line width EditText echoes '12'") # ── TREE VALUE: Line width accepts 0 (the documented default) -> echoed 0 ──── @and_test(expects=("computation_linewidth_roundtrip_0",)) def test_linewidth_roundtrip_0(): et = and_enter_line_width_dialog() if et is None: record("computation_linewidth_roundtrip_0", False, "setup_failed: Line width dialog / EditText unreachable", depth=2, jump_kind="value", expect="Line width EditText echoes '0'") return type_text(et, "0") fresh = find_by_class(ui(), "EditText") got = (fresh[0].get("text", "") if fresh else "").strip() got_digits = re.sub(r"[^0-9]", "", got) ok = got_digits == "0" record("computation_linewidth_roundtrip_0", ok, "" if ok else f"behavior_wrong: EditText shows {got!r}, expected '0'", depth=2, jump_kind="value", expect="Line width EditText echoes '0'") TESTS = [ test_score_zero_at_start, test_score_positive_after_play, test_score_monotonic, test_endgame_bar_matches_lastscore, test_highscore_bar_yellow, test_score_bar_yellow, test_score_large_font, test_score_comma_formatted, test_table2_zero_at_start, test_table2_positive_after_play, test_endgame_total_reflected, test_last_score_matches_row, test_linewidth_roundtrip_12, test_linewidth_roundtrip_0, ] if __name__ == "__main__": if not device_online(): print("Device offline — aborting; a whole module of setup_failed usually " "means the emulator/tunnel dropped, not that the app is broken.") run_suite(TESTS, "computation")