200 lines
9.0 KiB
Python
200 lines
9.0 KiB
Python
from __future__ import annotations
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime, timedelta, timezone
|
|
import io
|
|
import json
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import time
|
|
|
|
from PIL import Image, ImageChops, ImageStat
|
|
from .capture import load_buttons
|
|
|
|
|
|
class Adb:
|
|
def __init__(self, executable="", serial=""):
|
|
self.executable = executable or shutil.which("adb") or r"C:\Program Files\adb_tools\adb.exe"
|
|
self.serial = serial
|
|
|
|
def run(self, *args, binary=False):
|
|
command = [self.executable] + (["-s", self.serial] if self.serial else []) + list(args)
|
|
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
result = subprocess.run(command, capture_output=True, timeout=12, creationflags=flags)
|
|
if result.returncode:
|
|
raise RuntimeError("ADB 操作失败,请检查连接、授权和设备编号")
|
|
return result.stdout if binary else result.stdout.decode("utf-8", errors="replace")
|
|
|
|
def screenshot(self):
|
|
raw = self.run("exec-out", "screencap", "-p", binary=True)
|
|
image = Image.open(io.BytesIO(raw)).convert("RGB")
|
|
return image
|
|
|
|
def foreground(self):
|
|
value = self.run("shell", "dumpsys", "activity", "activities")
|
|
lines = [s for s in value.splitlines() if "topResumedActivity=" in s or "mResumedActivity:" in s or "mResumedActivity=" in s]
|
|
return bool(lines) and all("air.net.pixvi.myrzx" in s for s in lines)
|
|
|
|
def tap(self, x, y):
|
|
if not self.foreground():
|
|
raise RuntimeError("游戏不在前台,刷图已停止")
|
|
self.run("shell", "input", "tap", str(int(x)), str(int(y)))
|
|
|
|
|
|
@dataclass
|
|
class FarmConfig:
|
|
stage_id: str = "bd00"
|
|
stage_level: str = "1"
|
|
daily_limit: int = 3
|
|
keep_stamina: int = 0
|
|
timeout: int = 240
|
|
threshold: float = 0.96
|
|
templates: dict = field(default_factory=dict)
|
|
capture_profile: str = ""
|
|
|
|
|
|
class FarmBudget:
|
|
def __init__(self, path):
|
|
self.path = Path(path)
|
|
self.records = json.loads(self.path.read_text(encoding="utf-8")) if self.path.exists() else {}
|
|
|
|
def key(self, snapshot, config):
|
|
day = datetime.fromtimestamp(snapshot.now, timezone(timedelta(hours=8))).strftime("%Y-%m-%d")
|
|
return f"{snapshot.raw['master']['id']}:{config.stage_id}:{day}"
|
|
|
|
def used(self, snapshot, config):
|
|
return self.records.get(self.key(snapshot, config), 0)
|
|
|
|
def reserve(self, snapshot, config):
|
|
key = self.key(snapshot, config)
|
|
self.records[key] = self.records.get(key, 0) + 1
|
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
temporary = self.path.with_suffix(".tmp")
|
|
temporary.write_text(json.dumps(self.records), encoding="utf-8")
|
|
temporary.replace(self.path)
|
|
|
|
def check(self, snapshot, config, catalog):
|
|
if time.time() - snapshot.received_at > 30:
|
|
return False, "角色状态超过30秒未刷新"
|
|
if self.used(snapshot, config) >= config.daily_limit:
|
|
return False, "已达到本日设置的刷图上限"
|
|
stage = catalog.data["stage_info"].get(config.stage_id)
|
|
if not stage:
|
|
return False, "未找到此关卡的数据"
|
|
base = stage.get("cost", {})
|
|
cost = float(base.get("ti", 0)) + float(stage.get("level", {}).get(config.stage_level, {}).get("cost", 0))
|
|
if float(snapshot.raw["master"].get("ti", 0)) < cost + config.keep_stamina:
|
|
return False, "剩余体力不足或已达到保留体力"
|
|
counts = {str(i["typeId"]): int(i.get("num", 0)) for i in snapshot.raw["items"]}
|
|
for item in base.get("items", []):
|
|
if counts.get(str(item["typeId"]), 0) < int(item["num"]):
|
|
return False, "关卡入场券/每日可用次数已不足"
|
|
if float(snapshot.raw["master"].get("money", 0)) < float(base.get("money", 0)):
|
|
return False, "关卡金币消耗不足"
|
|
if float(base.get("ke", 0)):
|
|
return False, "此关卡需要氪金,未启用"
|
|
return True, f"可继续,今日已开始 {self.used(snapshot, config)} 轮"
|
|
|
|
|
|
def matches(image, template, folder, threshold):
|
|
width, height = template["screen"]
|
|
if template.get("strict_resolution") and image.size != (width, height):
|
|
return False
|
|
if abs(image.width / image.height - width / height) > 0.02:
|
|
return False
|
|
image = image.resize((width, height))
|
|
box = tuple(template["box"])
|
|
crop = image.crop(box).convert("RGB")
|
|
with Image.open(Path(folder) / template["file"]) as reference:
|
|
diff = ImageChops.difference(crop, reference.convert("RGB"))
|
|
similarity = 1 - sum(ImageStat.Stat(diff).mean) / (3 * 255)
|
|
return similarity >= threshold
|
|
|
|
|
|
class FarmRunner:
|
|
def __init__(self, adb, catalog, folder):
|
|
self.adb, self.catalog = adb, catalog
|
|
self.folder = Path(folder)
|
|
self.budget = FarmBudget(self.folder / "daily_runs.json")
|
|
self.config = FarmConfig()
|
|
self.state = "idle"
|
|
self.started = 0
|
|
self.last_tap = 0
|
|
self.running = False
|
|
self.completed = 0
|
|
|
|
def start(self):
|
|
if self.config.capture_profile:
|
|
self.config.templates = load_buttons(self.folder / self.config.capture_profile, self.folder,
|
|
self.config.stage_id, self.config.stage_level, self.adb.serial)
|
|
if not {"entry", "victory", "stage"}.issubset(self.config.templates):
|
|
raise ValueError("先截取关卡名称、进入按钮和胜利结算按钮")
|
|
if any(t.get("stage_id") != self.config.stage_id for t in self.config.templates.values()):
|
|
raise ValueError("标定不属于当前关卡,请为所选关卡重新标定按钮")
|
|
if any(str(t.get("stage_level", "1")) != self.config.stage_level for t in self.config.templates.values()):
|
|
raise ValueError("按钮配置属于其他难度,请加载对应页面配置")
|
|
self.state, self.running = "idle", True
|
|
|
|
def stop(self):
|
|
self.running = False
|
|
|
|
def tick(self, snapshot):
|
|
if not self.running:
|
|
return "已停止"
|
|
if not self.adb.foreground():
|
|
self.stop()
|
|
raise RuntimeError("游戏不在前台,刷图已停止")
|
|
templates = self.config.templates
|
|
devices = {t["device_serial"] for t in templates.values() if t.get("device_serial")}
|
|
if devices:
|
|
serial = self.adb.serial or self.adb.run("get-serialno").strip()
|
|
if devices != {serial}:
|
|
self.stop()
|
|
raise RuntimeError("当前手机与截图配置的设备不一致,已停止")
|
|
image = self.adb.screenshot()
|
|
if any(t.get("strict_resolution") and list(image.size) != t["screen"] for t in templates.values()):
|
|
self.stop()
|
|
raise RuntimeError("手机分辨率已变化,请补拍对应页面并重新生成配置")
|
|
visible = {name: matches(image, value, self.folder, self.config.threshold) for name, value in templates.items()}
|
|
now = time.monotonic()
|
|
if self.state != "idle" and now - self.started > self.config.timeout:
|
|
self.stop()
|
|
raise RuntimeError("战斗/结算等待超时,已停止;请检查手机画面")
|
|
if visible.get("defeat"):
|
|
self.stop()
|
|
raise RuntimeError("检测到战斗失败,已停止刷图")
|
|
if now - self.last_tap < 2:
|
|
return "等待画面更新"
|
|
button = None
|
|
if visible.get("entry"):
|
|
if self.state == "settling":
|
|
self.completed += 1
|
|
self.state = "idle"
|
|
return "结算完成,等待刷新体力和次数"
|
|
if self.state == "idle":
|
|
if not visible.get("stage"):
|
|
return "准备页关卡名称不匹配,未点击进入"
|
|
allowed, reason = self.budget.check(snapshot, self.config, self.catalog)
|
|
if not allowed:
|
|
self.stop()
|
|
return reason
|
|
# Count attempts before tapping, including interrupted/failed attempts.
|
|
self.budget.reserve(snapshot, self.config)
|
|
self.state, self.started, button = "battle", now, "entry"
|
|
elif self.state in ("battle", "settling"):
|
|
if visible.get("victory"):
|
|
self.state, button = "settling", "victory"
|
|
elif self.state == "settling" and visible.get("continue"):
|
|
button = "continue"
|
|
elif self.state == "battle":
|
|
button = next((name for name in ("countdown", "auto_off") if visible.get(name)), None)
|
|
if button and self.running:
|
|
template = templates[button]
|
|
x1, y1, x2, y2 = template["box"]
|
|
width, height = template["screen"]
|
|
tap_x, tap_y = template.get("tap", [(x1 + x2) / 2, (y1 + y2) / 2])
|
|
self.adb.tap(tap_x * image.width / width, tap_y * image.height / height)
|
|
self.last_tap = now
|
|
return f"点击 {button};完成 {self.completed} 轮"
|
|
return "等待匹配按钮;请勿切换到其他关卡"
|