"""User-triggered page samples, grouped by device, resolution and stage.""" from __future__ import annotations from datetime import datetime, timedelta, timezone import hashlib import json from pathlib import Path import re from PIL import Image PAGES = ( ("stage_ready", "关卡准备页", "需看到关卡名称、选中难度和进入按钮", True), ("battle_start", "战斗倒计时页", "需看到触摸开始 / 开始倒计时", False), ("auto_off", "自动战斗关闭状态", "需看到自动按钮处于关闭状态", False), ("auto_on", "自动战斗开启状态", "需看到自动按钮处于开启状态", False), ("victory", "胜利结算页", "需看到胜利标识和领取 / 继续按钮", True), ("continue", "后续确认页", "胜利后如还有奖励确认 / 返回页面,截取此页", False), ("defeat", "失败结算页", "如方便,保留失败页面以识别停止条件", False), ) BUTTON_PAGES = {"stage": "stage_ready", "entry": "stage_ready", "countdown": "battle_start", "auto_off": "auto_off", "victory": "victory", "continue": "continue", "defeat": "defeat"} def component(value): return re.sub(r"[^a-zA-Z0-9_.-]", "_", str(value))[:100].strip(".") or "device" def read_profile(path, root): path, root = Path(path).resolve(), Path(root).resolve() if not path.is_relative_to(root): raise ValueError("截图配置路径不在本地状态目录内") profile = json.loads(path.read_text(encoding="utf-8")) if profile.get("schema_version") != 1 or not isinstance(profile.get("captures"), dict): raise ValueError("无法识别此截图配置") return profile def saved_profiles(root, stage_id, level, serial=""): result = [] for path in (Path(root) / "capture_profiles").glob("*/*/*/profile.json"): try: profile = read_profile(path, root) if (str(profile["stage_id"]) == str(stage_id) and str(profile["stage_level"]) == str(level) and (not serial or profile["device_serial"] == serial)): result.append((path.resolve(), profile)) except (OSError, ValueError, KeyError, TypeError): continue return sorted(result, key=lambda item: item[0].stat().st_mtime, reverse=True) def save_page(root, image, serial, stage_id, level, page): if page not in {p[0] for p in PAGES}: raise ValueError("未知截图页面") root = Path(root).resolve() folder = root / "capture_profiles" / component(serial) / f"{image.width}x{image.height}" / f"{component(stage_id)}_{component(level)}" folder.mkdir(parents=True, exist_ok=True) path = folder / "profile.json" profile = json.loads(path.read_text(encoding="utf-8")) if path.exists() else { "schema_version": 1, "device_serial": serial, "stage_id": stage_id, "stage_level": str(level), "resolution": list(image.size), "app_package": "air.net.pixvi.myrzx", "captures": {}} if (profile["device_serial"] != serial or str(profile["stage_id"]) != str(stage_id) or profile["stage_level"] != str(level) or profile["resolution"] != list(image.size)): raise ValueError("截图目录中的设备或关卡记录不一致") target = folder / (page + ".png") image.save(target) profile["captures"][page] = {"file": target.name, "sha256": hashlib.sha256(target.read_bytes()).hexdigest(), "captured_at": datetime.now(timezone(timedelta(hours=8))).isoformat(timespec="seconds")} temporary = path.with_suffix(".tmp") temporary.write_text(json.dumps(profile, ensure_ascii=False, indent=2), encoding="utf-8") temporary.replace(path) return path, profile def write_buttons(profile_path, root, regions): """Create templates from regions reviewed by the assistant in saved samples.""" profile_path = Path(profile_path).resolve() profile = read_profile(profile_path, root) if not {"stage", "entry", "victory"}.issubset(regions): raise ValueError("需提供关卡标题、进入和胜利区域") width, height = profile["resolution"] templates, sources = {}, {} for name, region in regions.items(): page = BUTTON_PAGES[name] record = profile["captures"][page] source = (profile_path.parent / record["file"]).resolve() if not source.is_relative_to(Path(root).resolve()) or hashlib.sha256(source.read_bytes()).hexdigest() != record["sha256"]: raise ValueError("截图文件与记录不一致") box = list(region["box"]) tap = list(region.get("tap", [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2])) if (len(box) != 4 or not 0 <= box[0] < box[2] <= width or not 0 <= box[1] < box[3] <= height or len(tap) != 2 or not 0 <= tap[0] < width or not 0 <= tap[1] < height): raise ValueError("按钮区域或点击位置超出截图范围") filename = f"button_{name}.png" with Image.open(source) as image: image.crop(box).save(profile_path.parent / filename) templates[name] = {"file": filename, "box": box, "tap": tap} sources[page] = record["sha256"] buttons = {k: profile[k] for k in ("schema_version", "device_serial", "stage_id", "stage_level", "resolution")} buttons.update(source_captures=sources, templates=templates) path = profile_path.with_name("buttons.json") temporary = path.with_suffix(".tmp") temporary.write_text(json.dumps(buttons, ensure_ascii=False, indent=2), encoding="utf-8") temporary.replace(path) load_buttons(profile_path, root, profile["stage_id"], profile["stage_level"]) return path def load_buttons(profile_path, root, stage_id, level, serial=""): profile_path, root = Path(profile_path).resolve(), Path(root).resolve() profile = read_profile(profile_path, root) path = profile_path.with_name("buttons.json") buttons = json.loads(path.read_text(encoding="utf-8")) if str(buttons["stage_id"]) != str(stage_id) or str(buttons["stage_level"]) != str(level): raise ValueError("按钮配置与所选关卡/难度不一致") if str(profile["stage_id"]) != str(stage_id) or str(profile["stage_level"]) != str(level): raise ValueError("页面截图属于其他关卡或难度") if buttons["resolution"] != profile["resolution"] or buttons.get("device_serial") != profile["device_serial"]: raise ValueError("按钮配置与当前设备或分辨率不一致") if serial and profile["device_serial"] != serial: raise ValueError("按钮配置属于其他设备") sources = buttons.get("source_captures", {}) if not sources or any(profile["captures"].get(k, {}).get("sha256") != v for k, v in sources.items()): raise ValueError("页面截图已更新,需要重新生成按钮配置") if not {"stage_ready", "victory"}.issubset(sources): raise ValueError("按钮配置缺少必需页面来源") for key, digest in sources.items(): source = (path.parent / profile["captures"][key]["file"]).resolve() if not source.is_relative_to(root) or hashlib.sha256(source.read_bytes()).hexdigest() != digest: raise ValueError("截图文件与记录不一致,请重新截图并生成配置") templates = {} for name, original in buttons.get("templates", {}).items(): item = dict(original) image_path = (path.parent / item["file"]).resolve() if not image_path.is_relative_to(root) or not image_path.is_file(): raise ValueError("按钮模板图片缺失或路径无效") item["file"] = str(image_path.relative_to(root)) item["stage_id"], item["stage_level"] = str(stage_id), str(level) item["screen"] = buttons["resolution"] item["device_serial"] = profile["device_serial"] item["strict_resolution"] = True width, height = buttons["resolution"] box = item.get("box", []) if (len(box) != 4 or not 0 <= box[0] < box[2] <= width or not 0 <= box[1] < box[3] <= height): raise ValueError("按钮识别区域超出截图范围") tap = item.get("tap", [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2]) if len(tap) != 2 or not 0 <= tap[0] < width or not 0 <= tap[1] < height: raise ValueError("按钮点击位置超出截图范围") with Image.open(image_path) as reference: if reference.size != (box[2] - box[0], box[3] - box[1]): raise ValueError("按钮模板尺寸与识别区域不一致") templates[name] = item if not {"stage", "entry", "victory"}.issubset(templates): raise ValueError("按钮配置缺少关卡名称、进入或胜利模板") return templates