"""Shared Common Shop / Tactical Shop grid logic. Ported from baas-reference module/shop/shop_utils.py's get_item_position/ ensure_choose/buy pattern -- the checkbox-select-then-bulk-buy grid shared by both shop tabs in the live client. Adapted from the reference's color+template item-state scan to this project's fixed-grid-position + price-OCR-verify design: unlike story_sweep, the reference's own item-identification here isn't OCR at all -- it indexes into self.static_config.common_shop_price_list, a table sourced from an external resource this repo doesn't have. So a locally pixel-scanned, name-commented position table (config.COMMON_SHOP_TARGETS / config.TACTICAL_SHOP_TARGETS) is the faithful local equivalent, not a shortcut around OCR the reference uses. Price-digit OCR -- something the reference doesn't even do per-item -- is layered on top as an extra safety net against catalog drift, consistent with this project's verify-before-spend pattern elsewhere (mailbox/cafe/story_sweep). **Position turned out not to be fixed** (found live 2026-08-01, see config.SHOP_PRICE_OCR_OFFSET's comment and script_error.md): Common Shop sinks a sold-out item to the bottom of its (scrollable) grid and shifts everything after it up, so a fixed (row, col) -> item mapping silently drifts the moment anything sells out. `select_targets_by_name` below replaces position-based identification with OCR'd item-name matching for Common Shop specifically -- genuinely closer to the reference's own item-identity-based (not position-based) design intent, just using a local OCR read instead of the reference's external price-list index, for the same "don't have that external table" reason the module docstring above already gives. Tactical Shop (`select_targets`, unchanged) has never shown this symptom -- one row, two items, no observed reordering -- so it stays on the simpler position-based path rather than migrating speculatively. """ import difflib from ba_auto import detector, navigation # _match_name's last-resort fallback for OCR text with an internal inserted/ # dropped character that breaks plain substring containment (see that # function's own docstring for the live incident and real similarity scores # this was calibrated against). SIMILARITY_THRESHOLD = 0.75 def _checkbox_center(config, row, col): return config.SHOP_ITEM_COL_X[col], config.SHOP_ITEM_ROW_Y[row] def _checkbox_region(config, row, col): x, y = _checkbox_center(config, row, col) return (x - 15, y - 15, x + 15, y + 15) def _price_rect(config, row, col): x, y = _checkbox_center(config, row, col) x1, y1, x2, y2 = config.SHOP_PRICE_OCR_OFFSET return (x + x1, y + y1, x + x2, y + y2) def _name_rect(config, row, col): x, y = _checkbox_center(config, row, col) x1, y1, x2, y2 = config.SHOP_NAME_OCR_OFFSET return (x + x1, y + y1, x + x2, y + y2) def _is_checked(driver, config, row, col): lo, hi = config.SHOP_CHECKED_RGB return detector.region_contains_color(_checkbox_region(config, row, col), lo, hi) def _is_purchasable(driver, config, row, col): """A sold-out/greyed buy button reads flat grey (B-R within +/-2 of 0, no color tint at all); a live/purchasable one carries a strong blue tint (B-R of +120 to +127) -- regardless of the button's own shimmer animation, which swings its raw brightness a lot but not its tint (see config.SHOP_BUTTON_PROBE_OFFSET's own comment for the live A/B that found this; an earlier brightness-only check was fooled by it).""" x, y = _checkbox_center(config, row, col) dx, dy = config.SHOP_BUTTON_PROBE_OFFSET r, g, b = driver.color_at(x + dx, y + dy) return (b - r) > config.SHOP_BUTTON_PURCHASABLE_MIN_BLUE_TINT def select_targets(driver, config, targets): """OCR-verify each target's price, then click its checkbox and confirm it registers as checked. Returns (selected, skipped); a price mismatch or an unconfirmed checkbox skips just that target rather than aborting the whole run (mirrors story_sweep's per-target skip-not-abort design). Re-reads the price up to config.SHOP_PRICE_OCR_RETRIES times, stopping early on the first read that matches expected_price -- a real live run misread one target's price by a single stray digit while every other target (including other 6-digit prices) read correctly in the same run, so a single bad frame shouldn't skip a real purchase. A genuine catalog change still reads the same (wrong) value across every retry and gets skipped as before. See config.SHOP_PRICE_OCR_RETRIES's own comment. """ selected = [] skipped = [] for row, col, name, expected_price in targets: price = None for attempt in range(1, config.SHOP_PRICE_OCR_RETRIES + 1): price = detector.read_int(_price_rect(config, row, col)) if price == expected_price: break if attempt < config.SHOP_PRICE_OCR_RETRIES: driver.wait(0.3) if price != expected_price: print(f"[shop] '{name}' price read as {price}, expected {expected_price} -- skipping (catalog may have changed)") skipped.append((name, "price_mismatch")) continue x, y = _checkbox_center(config, row, col) driver.click(x, y) driver.wait(0.3) if not _is_checked(driver, config, row, col): print(f"[shop] '{name}' checkbox did not register as checked -- skipping") skipped.append((name, "checkbox_not_confirmed")) continue selected.append((name, expected_price)) return selected, skipped def _match_name(name_text, remaining): """Resolve an OCR'd cell name to the single `remaining` target it refers to, preferring an exact match over a substring one. Real bug (2026-09-17): Common Shop's own tier-naming convention nests a shorter tier name inside a longer one -- "上級強化珠" (Advanced) is literally a substring of "最上級強化珠" (Highest), same for "上級レポート"/"最上級レポート". The original substring-only match (`next(n for n in remaining if n in name_text or name_text in n)`) had no preference for an exact match, so scanning a "最上級強化珠" card while "上級強化珠" was still also in `remaining` could resolve to the WRONG (shorter) target purely because it happened to iterate first in dict order -- the subsequent price check then compared against the wrong target's price, always mismatched, and permanently skipped the real card every single run. Confirmed live: 最上級強化珠 sat available at its exact listed price for hours across three separate real runs, never once bought, while shorter-named siblings bought fine. An exact match is checked first and always wins outright. The substring fallback (for a genuinely imperfect OCR read missing/adding a stray character at the START or END) still exists, but picks the LONGEST candidate -- the more specific name -- to minimize the same class of collision. **Real live under-match, 2026-09-24**: even with a clean, purchasable, correctly-priced card on screen, several targets still went unmatched every single pass, forcing an unnecessary scroll (and from there into the separate scroll-misalignment failure -- see _grid_looks_aligned). Root-caused with a per-cell verbose trace against the live game: the OCR noise wasn't just a prefix/suffix character any more -- it was an INTERNAL corruption breaking contiguity, e.g. '初級レポート' (12,500) read as '初級レポボート' (a phantom character inserted mid-string) and '中級強化珠' (40,000) read as '中級化珠' (a real character, '強', dropped from the middle) -- both stable/repeatable across several consecutive fresh screenshots of the same still-unclicked cell, not a one-off flake. Neither direction of plain substring containment can ever match these: the target string literally does not appear contiguously inside the corrupted OCR text, or vice versa. A separate case, '中級レポート' read as '。 日 中級レポー ト', had a plain space inserted before the final character -- also breaks substring containment, but is fixed for free by stripping whitespace before any comparison (real target names never contain spaces). Fixed with a two-stage fallback: (1) strip whitespace before every comparison stage above; (2) if plain substring containment still finds nothing, fall back to whole-string similarity (difflib.SequenceMatcher ratio) against every remaining candidate, taking the best match if it clears SIMILARITY_THRESHOLD. Confirmed against this incident's own real corrupted readings: '初級レポボート' vs '初級レポート' scores ~0.92, '中級化珠' vs '中級強化珠' scores ~0.89 -- both comfortably above threshold, while unrelated/heavily-garbled reads (e.g. a genuinely different item's name, or a cell read as pure noise) score well below it in the same live samples. This is a fallback of last resort, not a replacement for the stages above: an exact or clean substring match is always preferred, and this project's usual price-match safety net still guards the actual purchase regardless of which stage resolved the name. """ if not name_text: return None normalized = "".join(name_text.split()) if normalized in remaining: return normalized candidates = [n for n in remaining if n in normalized or normalized in n] if candidates: return max(candidates, key=len) best_name, best_ratio = None, 0.0 for n in remaining: ratio = difflib.SequenceMatcher(None, normalized, n).ratio() if ratio > best_ratio: best_name, best_ratio = n, ratio return best_name if best_ratio >= SIMILARITY_THRESHOLD else None def _scan_current_view(driver, config, remaining): """One pass over the currently-visible grid (no scrolling), buying at most one still-wanted target and returning its name, or None if nothing in `remaining` matched anywhere on screen right now. Deliberately stops and returns after the FIRST successful buy rather than continuing the row/col loop -- see select_targets_by_name's docstring for why: buying can reflow the grid mid-pass, and continuing with the old loop's positions after that happens is exactly what caused a real live under-purchase (2026-09-17). """ n_rows = len(config.SHOP_ITEM_ROW_Y) n_cols = len(config.SHOP_ITEM_COL_X) for row in range(n_rows): for col in range(n_cols): name_text = detector.read_text(_name_rect(config, row, col), lang="jpn") match = _match_name(name_text, remaining) if match is None: continue price = detector.read_int(_price_rect(config, row, col)) if price != remaining[match]: continue if not _is_purchasable(driver, config, row, col): continue x, y = _checkbox_center(config, row, col) driver.click(x, y) driver.wait(0.3) if not _is_checked(driver, config, row, col): print(f"[shop] '{match}' checkbox did not register as checked -- skipping") continue # Extra settle time before the caller's next rescan -- a real # live run (2026-09-17) still missed two further targets that # were confirmed sitting available minutes later, even with the # same-pass reflow fix above; the checkbox itself registers # "checked" well before the grid's own reflow/collapse animation # visually finishes resettling every other card's position, so # an immediate rescan can OCR a still-mid-transition frame and # misread a genuinely-present target as absent. driver.wait(config.SHOP_REFLOW_SETTLE_WAIT) return match return None def _grid_looks_aligned(driver, config): """True if at least one of the 8 fixed grid cells currently reads purchasable -- a cheap proxy for "the fixed SHOP_ITEM_ROW_Y/ SHOP_ITEM_COL_X crops are actually landing on real cards right now", not a torn mid-scroll frame. Real live bug (2026-09-21): a real cron run of Common Shop logged 4-5 of 8 configured targets as "not found available at its expected price" -- '中級強化珠' among them -- even though a read-only diagnostic probe against the very same live screen, moments apart, found it sitting unscrolled at the top of the grid with its correct name, correct price, and a purchasable buy button. Root-caused with a before/after screenshot of a single select_targets_by_name scroll call: the grid visibly moved by something closer to 1.5-2 rows, not the clean single row SHOP_SCROLL_STEP_CLICKS's own docstring assumed -- landing on a frame with card titles cut off above the viewport and buy buttons sitting nowhere near their calibrated offsets. Every fixed-offset OCR/color read against that frame came back empty or garbled, and _is_purchasable read False for all 8 cells (vs. 7-8/8 True on a genuinely aligned frame, e.g. the very first unscrolled screenshot of the same run) -- so the scan silently treated a real, available item as gone rather than as "my own crop coordinates are pointing at nothing right now". Not foolproof: a row that is genuinely, simultaneously sold out across all 8 visible cells would also read this way. Accepted as an unlikely edge case, consistent with this module's other scan heuristics (e.g. select_targets_by_name's own "screenshot unchanged" bottom-of-list check has a similar blind spot). """ n_rows = len(config.SHOP_ITEM_ROW_Y) n_cols = len(config.SHOP_ITEM_COL_X) return any( _is_purchasable(driver, config, row, col) for row in range(n_rows) for col in range(n_cols) ) def _ensure_grid_aligned(driver, config): """After a scroll, confirm the grid landed row-aligned (see _grid_looks_aligned); if not, nudge back up in small steps until it is, or give up after config.SHOP_SCROLL_REALIGN_MAX_NUDGES attempts. Returns True once aligned (including if it already was), False if every nudge was exhausted without recovering. """ if _grid_looks_aligned(driver, config): return True for _ in range(config.SHOP_SCROLL_REALIGN_MAX_NUDGES): driver.scroll(*config.SHOP_SCROLL_POINT, "up", clicks=config.SHOP_SCROLL_REALIGN_NUDGE_CLICKS) driver.wait(0.3) if _grid_looks_aligned(driver, config): return True return False def select_targets_by_name(driver, config, targets, *, balance_rect): """Name-OCR-based sibling of select_targets, for grids where a bought (or sold-out) item sinks to the bottom and shifts everything else's position (see this module's own docstring and config.SHOP_PRICE_OCR_OFFSET's comment for the live incident this was built from). `targets` is a list of (name, expected_price) pairs, no row/col. Scans from the top of the (scrollable) grid, two rows per screenshot, OCR-reading each cell's item name. A cell is bought only if its name matches a not-yet-found target AND its price OCR matches that target's exact expected_price -- so an escalated repeat-purchase tier of the same item (confirmed live: exactly 2x price once the base tier sells out) is deliberately never matched, same "skip rather than overspend" call the user made for this project's other targets -- AND its buy button reads purchasable (not sold out). Scrolls by exactly one row (config.SHOP_SCROLL_STEP_CLICKS) between reads and stops once every target is found, the grid stops producing new content (real bottom), or config.SHOP_NAME_SCAN_MAX_STEPS is hit, whichever comes first. Matches by substring either direction rather than exact equality, same tolerance-for-a-stray-character margin story_sweep's own OCR text matching uses (`"掃討" in text`) -- a clean short UI label is usually exact, but this doesn't hard-fail on one stray/missing character. **Real live under-purchase, 2026-09-17**: a real cron run bought only 4 of 8 configured targets, logging the other 4 as "not found available" -- but hours later, with nothing else having touched the account, those exact 4 items were sitting unbought at their exact expected prices right at the top of the (unscrolled) grid. Root-caused (with the user's own pasted log as the key evidence, cross-checked against the successfully bought items' prices summing exactly to the run's own logged total spend) to a same-pass reflow bug: the OLD version of this function kept iterating its row/col loop with the SAME screenshot-implied positions after a successful buy, even though buying an item collapses its grid slot and shifts every later item forward -- so a still-wanted item that got shifted into an already-visited position was silently skipped for that pass, and the outer loop's unconditional forward-only scroll then moved the viewport away from it, orphaning it for the rest of the run. Fixed by re-scanning the CURRENT (unscrolled) view from scratch via `_scan_current_view` after every single successful buy -- each call re-reads every cell fresh, so a reflow can't leave a stale match unnoticed. Scrolling only happens once a full pass finds nothing left to buy on the current screen. **Real live false-unavailable, 2026-09-22**: a real cron run logged all 8 targets as "not found available" within 3 seconds of opening the tab -- far too fast for a real multi-row OCR scan, and a stark outlier against every other run's 5-10+ second scan time. Root-caused live by reproducing the same account state interactively: an in-game "network access problem" dialog (a real, first-party modal, distinct from anything this project's own code triggers) can appear over the shop grid at essentially any point -- confirmed live when one appeared while manually replaying this exact function's own logic step by step. Once up, it dims the whole grid behind it, so every fixed-offset OCR/color read comes back empty or garbled, and a STATIC dialog doesn't animate frame to frame -- so the very next iteration's "screenshot unchanged" check fires almost immediately, misreporting every remaining target as genuinely unavailable in a couple of seconds flat, exactly matching the live log. Fixed by checking `navigation.is_modal_open` (the same screen-dimming probe used throughout this project, e.g. `navigation.return_to_home`'s own `_not_home` check) at the top of each scan pass, before trusting anything read from that frame. Deliberately does NOT try to dismiss the dialog itself: this specific dialog's own "OK" button logs all the way out to the title screen, and a different unrecognized modal could hide something worse (e.g. a real-currency confirm) -- guessing a keypress here trades a loud, honest stop for a silent misreport, or worse, an unintended action. Skipped targets get a distinct 'blocked_by_modal' reason instead of the normal "not found available", so a run cut short this way is never confused with the genuinely-benign sold-out/escalated-price case in the log or by anyone reading it later. **Real live OCR instability, 2026-09-24**: even with the fixes above, the exact same still-visible, still-purchasable, still-unscrolled cell would sometimes read cleanly and sometimes come back corrupted -- confirmed live across five consecutive selection-only test runs (never clicking Buy, so free to repeat) that which of the 8 targets failed to match varied run to run, not a fixed set tied to one item's name. A single full-pass "nothing matched" was previously treated as proof the remaining targets weren't in the current view at all, immediately triggering a scroll -- compounding the problem, since scrolling has its own separate fragility (see _grid_looks_aligned). First fix attempt: retry a "nothing matched" pass up to `config.SHOP_NO_MATCH_RETRIES` times, waiting between attempts, before giving up and scrolling. **That in-place retry turned out not to work, confirmed live the same session**: reading the exact same still-unclicked cell 5 times in a row without leaving the shop tab gave the identical wrong text every time (e.g. '中級化珠' for '中級強化珠', all 5 reads) -- the corruption is stable for as long as the tab stays open, not a per-frame flake, so re-reading in place can never see anything different. Fully leaving and re-entering the shop tab, by contrast, gave a DIFFERENT reading on 4 of 5 attempts in the same live test (one of them exactly correct) -- proving the render itself resets on each fresh tab-open, even though it doesn't change while sitting on it. Fixed by escalating to a full return-to-home-and-reopen cycle (bounded by `config.SHOP_REOPEN_MAX_ATTEMPTS`) once the in-place retries are exhausted, before ever falling back to scrolling -- most of that live test's reopen variants (e.g. '中級衝化珠', '中級測化珠', both a single substituted character) already clear `_match_name`'s fuzzy-similarity threshold on their own, so a reopen or two is normally enough. A successful match resets `reopen_attempts` back to 0, so a later, unrelated stuck target still gets its own full budget. **Real live under-purchase, 2026-09-24, same day**: leaving the shop tab does not just reset the render -- it also unchecks every checkbox already ticked this call, since checked state lives in the tab's own UI, not the account, until Buy is actually clicked. The first version of the reopen fix above didn't account for this: a real cron-triggered run logged all 8 targets as matched (zero skips, `selected` summing to the full 1,211,500) after one reopen mid-scan, yet the real purchase only deducted 125,000 -- exactly one target's price, the one found right after that reopen. Every target confirmed-checked *before* the reopen had silently gone back to unchecked in the live game, but `selected` still listed them as done, so confirm_purchase clicked Buy against a cart that was actually down to one item. Confirmed via the account's own real credit balance delta. **First fix (moving already-selected entries back into `remaining` on every reopen) was correct but pathological**: it eliminated the under-purchase, but since a reopen now had to re-earn EVERY target checked so far, not just the one that got stuck, one flaky match anywhere could force the whole session to redo several already-solved targets -- confirmed live: a real run cycled through 20+ consecutive reopens (each one individually reasonable) chasing a shrinking-then- growing batch, and burned enough wall-clock time doing so that it eventually collided with a real scheduled `q4h` cron fire on the same game window, corrupting screenshots for both processes and crashing. **Real fix: buy each batch before it can be invalidated**, rather than holding the whole cart in memory across a reopen. `current_batch` (this session's checked-but-not-yet-bought items) is committed via a real, balance-verified `confirm_purchase` call -- exactly like a normal end-of-run purchase, just potentially several times per call instead of once -- immediately before any reopen, and once more at the very end. A committed batch moves into `purchased` and can never be undone by a later reopen, since the real account balance already reflects it. This function now owns its own purchase confirmation end-to-end (hence the required `balance_rect` and the `HANDLES_OWN_PURCHASE` flag below) -- `run_shop_tab` no longer buys on this path's behalf. If a batch purchase itself fails to verify, scanning stops immediately (further spending on top of an already-unclear balance state would only make a manual check harder), and every still-remaining target is reported with a distinct 'unrecognized_state' reason rather than the genuinely-benign "not found available". """ remaining = {name: price for name, price in targets} current_batch = [] purchased = [] prev_shot = None blocked_by_modal = False purchase_failed = False scroll_steps = 0 reopen_attempts = 0 def commit_current_batch(): """Buy whatever's checked right now, before anything (a reopen) can invalidate it. Returns False if the purchase itself doesn't verify (see confirm_purchase) -- a real, distinct failure from "nothing to buy", which the caller must stop on rather than paper over.""" nonlocal current_batch, purchase_failed if not current_batch: return True balance_before = detector.read_int(balance_rect) if balance_before is None: print("[shop] could not read balance before committing this batch -- stopping without buying") purchase_failed = True return False spent = sum(price for _, price in current_batch) if not confirm_purchase(driver, config, balance_rect=balance_rect, balance_before=balance_before, expected_spend=spent): print(f"[shop] purchase confirmation for this batch ({len(current_batch)} item(s), {spent}) did not resolve to a verified balance change -- stopping, check the game manually") purchase_failed = True return False print(f"[shop] bought {len(current_batch)} item(s) for {spent} this batch: {[name for name, _ in current_batch]}") purchased.extend(current_batch) current_batch = [] return True while scroll_steps < config.SHOP_NAME_SCAN_MAX_STEPS: if not remaining: break if navigation.is_modal_open(driver): print("[shop] an unexpected dialog is covering the shop grid -- stopping scan rather than reading a blocked frame as 'nothing available' (not dismissed automatically: this project doesn't guess how to close an unrecognized modal, since the wrong keypress here can log out or spend real currency)") blocked_by_modal = True break shot = driver.read_screenshot(detector.OCR_SHOT_PATH) if prev_shot is not None and (shot == prev_shot).all(): print("[shop] grid stopped scrolling -- reached the real bottom of the list") break prev_shot = shot no_match_streak = 0 stuck = False while remaining: match = _scan_current_view(driver, config, remaining) if match is None: no_match_streak += 1 if no_match_streak < config.SHOP_NO_MATCH_RETRIES: driver.wait(0.5) continue stuck = True break no_match_streak = 0 reopen_attempts = 0 current_batch.append((match, remaining.pop(match))) if not remaining: break if stuck and reopen_attempts < config.SHOP_REOPEN_MAX_ATTEMPTS: reopen_attempts += 1 print(f"[shop] no match after {config.SHOP_NO_MATCH_RETRIES} in-place rescans -- reopening the shop tab for a fresh render (attempt {reopen_attempts}/{config.SHOP_REOPEN_MAX_ATTEMPTS})") if not commit_current_batch(): break navigation.return_to_home(driver) driver.click(*config.SHOP_ICON) driver.wait(2) driver.click(*config.SHOP_TAB_COMMON) driver.wait(1.5) prev_shot = None continue driver.scroll(*config.SHOP_SCROLL_POINT, "down", clicks=config.SHOP_SCROLL_STEP_CLICKS) driver.wait(0.3) scroll_steps += 1 if not _ensure_grid_aligned(driver, config): print("[shop] grid scroll landed on a misaligned frame and could not realign -- stopping scan early (remaining targets may still be genuinely available)") break if not purchase_failed: commit_current_batch() skipped = [] for name in remaining: if purchase_failed: print(f"[shop] '{name}' scan stopped after a batch purchase failed to verify -- NOT confirmed unavailable, check the game manually") skipped.append((name, "unrecognized_state")) elif blocked_by_modal: print(f"[shop] '{name}' scan aborted by a blocking dialog -- NOT confirmed unavailable, check the game manually") skipped.append((name, "blocked_by_modal")) else: print(f"[shop] '{name}' not found available at its expected price {remaining[name]} -- skipping (sold out this cycle, or catalog changed)") skipped.append((name, "not_available")) return purchased, skipped select_targets_by_name.HANDLES_OWN_PURCHASE = True def confirm_purchase(driver, config, *, balance_rect, balance_before, expected_spend): """Click the bulk Buy button, then click through the purchase-confirm dialog and the reward-acquired banner. Both dim config.SHOP_OVERLAY_PROBE away from pure white; press Enter until it reads idle again, bounded by config.SHOP_PURCHASE_MAX_ENTER_PRESSES -- this project doesn't press keys past a bound against an unrecognized state (see navigation.wait_for_state). Real live false positive (2026-09-19): the overlay can already read "idle" on the very first check -- there's nothing in a single overlay-darkness read that distinguishes "confirmed and closed" from "the Buy click missed and the confirm dialog never opened at all". Confirmed live: a real cron run logged "bought 4 item(s)" for a real credit amount, but those exact 4 items were still sitting unbought at their base price hours later -- the overlay had simply never dimmed at any point this function actually checked it. Fixed by also requiring the currency balance to have actually dropped by `expected_spend` once the overlay reports idle -- re-read with the same stray-misread-digit retry tolerance SHOP_PRICE_OCR_RETRIES already uses elsewhere in this module, so one bad OCR frame on the balance itself can't sink an otherwise-real purchase. Returns True only once the overlay is idle AND the balance dropped by exactly `expected_spend`; False otherwise -- whether the overlay never cleared within the retry bound, or it cleared but the balance never moved (or moved by some other amount), meaning nothing was really bought despite looking "idle". """ driver.click(*config.SHOP_BUY_BUTTON) driver.wait(1.5) min_ch = config.SHOP_OVERLAY_IDLE_MIN_CHANNEL idle = False for _ in range(config.SHOP_PURCHASE_MAX_ENTER_PRESSES): r, g, b = driver.color_at(*config.SHOP_OVERLAY_PROBE) if r > min_ch and g > min_ch and b > min_ch: idle = True break driver.keypress("Return") driver.wait(1.5) if not idle: return False balance_after = None for attempt in range(1, config.SHOP_PRICE_OCR_RETRIES + 1): balance_after = detector.read_int(balance_rect) if balance_after is not None and balance_before - balance_after == expected_spend: return True if attempt < config.SHOP_PRICE_OCR_RETRIES: driver.wait(0.3) actual_spend = None if balance_after is None else balance_before - balance_after print(f"[shop] purchase overlay cleared but balance changed by {actual_spend}, expected {expected_spend} -- treating as not confirmed") return False def run_shop_tab(driver, config, *, tab_button, targets, balance_rect, currency_label, select_fn=select_targets): """Shared control flow for both shop tabs: open the tab, verify enough currency for everything configured, select+buy, report the outcome. Ported from the reference's common_shop.py/tactical_challenge_shop.py implement() -- both are this same shape (read assets, calculate cost, buy, verify), differing only in tab entry point and currency. `select_fn` defaults to the position-based select_targets (Tactical Shop's own (row, col, name, price) targets); shop_common.py passes select_targets_by_name instead, for its (name, price) targets -- see that function's docstring for why Common Shop needs name-based identification specifically. `select_fn` normally only selects (checkbox state); this function buys once at the end. select_targets_by_name is the one exception, flagged via its own `HANDLES_OWN_PURCHASE` attribute -- it needs to buy incrementally in its own batches (see its docstring's 2026-09-24 entries for why one end-of-scan purchase isn't safe for it), so this function defers to whatever it already bought instead of buying again. """ if not targets: print(f"[shop] no targets configured for {currency_label}, nothing to do") return "no_targets" driver.click(*tab_button) driver.wait(1.5) if not navigation.is_on_subscreen(driver): print("[shop] could not confirm shop tab opened, aborting without pressing further keys") return "navigation_failed" balance = detector.read_int(balance_rect) if balance is None: print(f"[shop] could not read {currency_label} balance, aborting without spending") return "balance_unreadable" total_cost = sum(target[-1] for target in targets) if balance < total_cost: print(f"[shop] insufficient {currency_label}: have {balance}, need {total_cost} -- stopping, nothing bought") return "inadequate_assets" if getattr(select_fn, "HANDLES_OWN_PURCHASE", False): # select_targets_by_name buys as it goes (possibly in several # batches, each independently balance-verified) rather than # returning an unbought selection for this function to purchase in # one shot -- see that function's own docstring for why a single # end-of-scan purchase isn't safe for it. `purchased` below is # already real, confirmed spending, not a pending cart. purchased, skipped = select_fn(driver, config, targets, balance_rect=balance_rect) if not purchased: if any(reason == "unrecognized_state" for _, reason in skipped): print("[shop] a batch purchase failed to verify partway through -- stopping, check the game manually") return "unrecognized_state" print("[shop] nothing purchased (all targets skipped)") return "nothing_selected" spent = sum(price for _, price in purchased) msg = f"[shop] bought {len(purchased)} item(s) for {spent} {currency_label}" if skipped: msg += f", skipped {len(skipped)}" print(msg) return "purchased" selected, skipped = select_fn(driver, config, targets) if not selected: print("[shop] nothing selected (all targets skipped), cancelling") return "nothing_selected" spent = sum(price for _, price in selected) if not confirm_purchase(driver, config, balance_rect=balance_rect, balance_before=balance, expected_spend=spent): print("[shop] purchase confirmation did not resolve to a verified balance change within the retry bound -- stopping, check the game manually") return "unrecognized_state" msg = f"[shop] bought {len(selected)} item(s) for {spent} {currency_label}" if skipped: msg += f", skipped {len(skipped)}" print(msg) return "purchased"