diff --git a/ranch_assistant/README.md b/ranch_assistant/README.md index ec73f46..cc6f51d 100644 --- a/ranch_assistant/README.md +++ b/ranch_assistant/README.md @@ -29,6 +29,8 @@ - 会话保存:成功读取角色后自动加密保存 Token、账号/区服/角色和请求编号,重启后可恢复。 - 自动孵蛋:按手动规则执行,提供开始执行、仅监控、停止按钮;支持十连优先、金币保留和每日购蛋额度。 可选随机30秒、60秒、2分钟或5分钟,每轮刷新完成后从0到所选上限重新取间隔;喂养遵守当前突破上限,满级后转到下一喂养目标。 + 空坑装填单独计时:有可用蛋时随机等待1~2秒装填一个坑位,确认成功后继续下一坑,不受整体刷新间隔影响。 + 每次装填前重新读取坑位和库存;无可用蛋、坑位已满或停止自动执行时暂停。此快速计时不会执行购蛋、派遣或其他操作。 原“牧场策略”并入此页的“牧场与赠礼策略”子页,内容超出高度时滚动显示;可导出、导入培养策略,跨账号按魔物种类匹配目标。 导入后所有自动执行开关保持关闭,文件不包含账号、密码、Token、会话或本机路径。 - 自动赠礼:在背包勾选可用物品,在牧场勾选目标并设置优先级,再到“牧场与赠礼策略”启用。 @@ -211,7 +213,7 @@ - 自定义表:`typeId, sell_money, sell_exp, time_total`(秒),可只提供部分 覆盖列;中文列名“编号、派遣金币、强化经验、孵化秒数”也支持。 - 测试:`python -m unittest discover -s ranch_assistant/tests -v`。 -- 131 项本地测试通过,覆盖登录、会话隔离、请求计数、成长同步、孵蛋与补货、批量喂养、派遣、赠礼、委托、扫荡和每日奖励。 +- 135 项本地测试通过,覆盖登录、会话隔离、请求计数、成长同步、孵蛋与补货、批量喂养、派遣、赠礼、委托、扫荡和每日奖励。 新增牧场树形/平铺切换、分组数量与空位、刷新保留折叠和控件、4S保留条件、随机刷新间隔及到期独立同步的回归测试。 双账号与大量库存的界面响应继续通过测试;测试使用本地模拟数据和模拟服务,不操作真实账号库存。 - 网络写请求发生异常后不会直接重试,以免重复消耗魔物或物品。 diff --git a/ranch_assistant/engine.py b/ranch_assistant/engine.py index bf5086a..06fc6af 100644 --- a/ranch_assistant/engine.py +++ b/ranch_assistant/engine.py @@ -16,6 +16,8 @@ class Engine: def __init__(self, catalog, client=None, budget_path=None): self.catalog, self.client = catalog, client self.planner = Planner(catalog) + self.hatch_planner = Planner(catalog) + self.pending_hatches = [] self.gift_planner = GiftPlanner(catalog) self.policy = Policy() self.quest_policy = QuestPolicy() @@ -128,7 +130,7 @@ class Engine: self.client.call("heartBeatService/keepAlive") return "会话心跳已更新" - def poll(self): + def poll(self, *, hatch_only=False, defer_hatch=False): self.last_executed = False settled = False if self.demo: @@ -139,7 +141,8 @@ class Engine: mon["mode"] = self.snapshot.expected_growth_mode(mon, self.catalog) else: self.read_snapshot() - settled = self.settle_pending_growth() + if not hatch_only: + settled = self.settle_pending_growth() message = "状态已刷新" + (";已请求孵化 / 成长结算" if settled else "") if self.snapshot.growth_pending(self.catalog): message += ";成长状态等待服务器确认,将自动检查" @@ -148,8 +151,11 @@ class Engine: except (ValueError, TypeError, KeyError, AttributeError) as error: self.auto = False return self.snapshot, [], "状态已读取;策略暂不可用:" + str(error) - if self.auto and plans: - action = plans[0] + actions = self.pending_hatches if hatch_only else plans + action = actions[0] if actions else None + if action and defer_hatch and action.kind == "hatch": + action = None + if self.auto and action is not None: self.last_executed = True if action.kind == "daily": entry = next(row for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger) if row.action == action) @@ -172,6 +178,12 @@ class Engine: if action.kind == "buy": self.record_draw(response.get("eggs") or []) self.read_snapshot() + if action.kind == "hatch": + stack_id = action.payload["eggs"][0]["stackId"] + slot = next((slot for slot in self.snapshot.raw["stacks"] if int(slot["id"]) == stack_id), None) + if slot is None or int(slot.get("monsterId") or 0) <= 0: + self.auto = False + raise ValueError("装填已返回,但坑位状态尚未同步;已停止,请刷新核对后再继续") if action.kind == "feed" and any(mid in self.snapshot.monsters for mid in action.payload["foods"]): self.auto = False raise ValueError("喂养已返回,但素材状态尚未同步;已停止,请刷新核对后再继续") @@ -195,6 +207,8 @@ class Engine: for key, count in eggs.items(): reserved[key] = max(reserved.get(key, 0), count) policy = replace(self.policy, reserved_types=list(set(self.policy.reserved_types) | types), reserved_eggs=reserved) + self.hatch_planner.notes = [] + self.pending_hatches = self.hatch_planner.hatch_actions(self.snapshot, policy) left = self.purchase_budget.remaining(self.snapshot.now, policy.daily_buy_money) daily = [row.action for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)] if self.daily_policy.enabled else [] sweep = self.sweeper.next(self.snapshot, self.sweep_policy) if self.sweep_policy.enabled and not self.demo else None diff --git a/ranch_assistant/gui.py b/ranch_assistant/gui.py index 7760451..ca82227 100644 --- a/ranch_assistant/gui.py +++ b/ranch_assistant/gui.py @@ -149,6 +149,11 @@ class Window(ActivityPages, W.QMainWindow): self.latest_render = None self.prepared_views = None self.next_poll = 0 + self.next_hatch = float("inf") + self.hatch_timer = C.QTimer(self) + self.hatch_timer.setSingleShot(True) + self.hatch_timer.setTimerType(C.Qt.TimerType.PreciseTimer) + self.hatch_timer.timeout.connect(self.schedule) self.client_pending = None self.password_login_result = None self.egg_rules = {} @@ -163,7 +168,7 @@ class Window(ActivityPages, W.QMainWindow): self.summary = W.QLabel() self.data_summary = W.QLabel("等待读取培育室、背包和牧场状态") self.interval = combo([("随机30秒", 30), ("随机60秒", 60), ("随机2分钟", 120), ("随机5分钟", 300)]) - self.interval.setToolTip("每轮完成后,从0到所选上限随机等待;请求串行执行。孵化/成长到期会单独同步。") + self.interval.setToolTip("整体刷新完成后,从0到所选上限随机等待。空坑装填独立随机1~2秒;孵化/成长到期会单独同步。") self.start_monitor = W.QPushButton("开始监控") self.start_monitor.setCheckable(True) self.start_monitor.toggled.connect(self.toggle_monitor) @@ -519,7 +524,7 @@ class Window(ActivityPages, W.QMainWindow): self.draw_status = W.QLabel("最近抽蛋:尚无记录") self.draw_status.setWordWrap(True) settings_layout.addWidget(self.draw_status) - note = W.QLabel("先在“背包魔物蛋”勾选并配置规则,再开始自动孵蛋。按手动优先级装填,成熟后按各行选择派遣、喂养或保留。\n锁定、星级、资质和等级上限保护仍生效;只处理本次培育的魔物。") + note = W.QLabel("先在“背包魔物蛋”勾选并配置规则,再开始自动孵蛋。空坑按手动优先级独立随机1~2秒装填,不受整体刷新间隔影响。\n成熟后按各行选择派遣、喂养或保留;锁定、星级、资质和等级上限保护仍生效,只处理本次培育的魔物。") note.setWordWrap(True) settings_layout.addWidget(note) settings_layout.addStretch() @@ -550,6 +555,8 @@ class Window(ActivityPages, W.QMainWindow): self.daily_buy_money.valueChanged.connect(self.update_workflow_status) for widget in (self.strategy, self.protect_quality, self.hatch_max_star): widget.currentIndexChanged.connect(self.update_workflow_status) + self.fill.toggled.connect(self.arm_hatching) + self.ranch_enabled.toggled.connect(self.arm_hatching) self.protect_star.valueChanged.connect(self.update_workflow_status) self.update_workflow_status() @@ -557,6 +564,7 @@ class Window(ActivityPages, W.QMainWindow): if not value: self.engine.auto = False self.pending_execute = False + self.arm_hatching() self.trace.emit("info", "自动执行状态", scope="local", enabled=value, monitoring=self.monitoring) self.update_workflow_status() @@ -1077,7 +1085,7 @@ class Window(ActivityPages, W.QMainWindow): def background(): started = time.perf_counter() value = function() - if kind in ("poll", "monster_lock", "manual_monsters", "expansion", "growth_sync", "daily_claim", "connected"): + if kind in ("poll", "hatch", "monster_lock", "manual_monsters", "expansion", "growth_sync", "daily_claim", "connected"): snapshot = value[1] if kind == "connected" else value[0] managed = set() if kind == "connected" else set(engine.planner.managed) preparing = time.perf_counter() @@ -1124,7 +1132,7 @@ class Window(ActivityPages, W.QMainWindow): note="worker总耗时包含网络;大列表在后续短批次更新") def apply_result(self, kind, value): - if kind in ("poll", "monster_lock", "manual_monsters", "expansion", "growth_sync", "daily_claim"): + if kind in ("poll", "hatch", "monster_lock", "manual_monsters", "expansion", "growth_sync", "daily_claim"): snapshot, plans, message = value self.render(snapshot, plans) self.report(message) @@ -1133,6 +1141,7 @@ class Window(ActivityPages, W.QMainWindow): self.next_poll = time.monotonic() + self.poll_delay() if "策略暂不可用" in message: self.execute.setChecked(False) + self.arm_hatching() elif kind == "heartbeat": self.report(value) elif kind == "connected": @@ -1256,7 +1265,7 @@ class Window(ActivityPages, W.QMainWindow): allow_items=self.quest_items.isChecked(), allow_monsters=self.quest_monsters.isChecked(), max_money=self.quest_money.value(), battle_tasks=self.quest_battles.isChecked(), item_reserves=reserves) - def refresh(self, checked=False, *, automated=False): + def refresh(self, checked=False, *, automated=False, hatch_only=False): if self.busy or self.closed: return try: @@ -1265,7 +1274,10 @@ class Window(ActivityPages, W.QMainWindow): self.engine.daily_policy = self.read_daily_policy() self.engine.sweep_policy = self.read_sweep_policy() self.engine.auto = self.execute.isChecked() and automated and self.monitoring - self.submit("poll", self.engine.poll) + if hatch_only: + self.hatch_timer.stop() + self.next_hatch = float("inf") + self.submit("hatch" if hatch_only else "poll", lambda: self.engine.poll(hatch_only=hatch_only, defer_hatch=not hatch_only)) except ValueError: if automated: self.error("请核对策略中的魔物编号和保留数量") @@ -1292,6 +1304,20 @@ class Window(ActivityPages, W.QMainWindow): self.next_poll = time.monotonic() + self.poll_delay() self.save_config(quiet=True) + def arm_hatching(self): + if (self.engine.pending_hatches and self.monitoring and self.execute.isChecked() + and self.ranch_enabled.isChecked() and self.fill.isChecked() and not self.closed): + if self.next_hatch < float("inf"): + if not self.hatch_timer.isActive(): + self.hatch_timer.start(max(0, round((self.next_hatch - time.monotonic()) * 1000))) + return + delay = random.uniform(1, 2) + self.next_hatch = time.monotonic() + delay + self.hatch_timer.start(round(delay * 1000)) + else: + self.hatch_timer.stop() + self.next_hatch = float("inf") + def schedule(self): if self.busy or self.closed: return @@ -1300,6 +1326,9 @@ class Window(ActivityPages, W.QMainWindow): self.submit("heartbeat", self.engine.keep_alive) elif not self.engine.demo and self.engine.heartbeat_enabled and self.engine.growth_sync_due(): self.submit("growth_sync", self.engine.sync_growth) + elif (self.monitoring and self.execute.isChecked() and self.fill.isChecked() + and self.ranch_enabled.isChecked() and now >= self.next_hatch): + self.refresh(automated=True, hatch_only=True) elif self.monitoring and now >= self.next_poll: self.refresh(automated=True) @@ -1705,6 +1734,7 @@ class Window(ActivityPages, W.QMainWindow): def closeEvent(self, event): self.closed = True self.timer.stop() + self.hatch_timer.stop() if hasattr(self, "activity_save_timer"): self.activity_save_timer.stop() if hasattr(self.eggs, "row_batch"): diff --git a/ranch_assistant/model.py b/ranch_assistant/model.py index 5e08d35..fbfbaa2 100644 --- a/ranch_assistant/model.py +++ b/ranch_assistant/model.py @@ -532,6 +532,12 @@ class Planner: self.notes.append(f"{name} 已保留:{reason}") if actions: return self.batch_actions(actions, snapshot, policy) + return self.hatch_actions(snapshot, policy) or self.purchase(snapshot, policy, daily_left) + + def hatch_actions(self, snapshot, policy): + if not policy.enabled or not policy.fill: + return [] + actions = [] vip_info = snapshot.raw.get("activityHistory", {}).get("vipInfo") or {} vip = seconds(vip_info.get("vipTime")) > snapshot.now empty = [s for s in snapshot.raw["stacks"] if policy.fill and int(s.get("monsterId") or 0) <= 0 and (int(s.get("position", -1)) != 3 or vip)] @@ -556,7 +562,7 @@ class Planner: self.notes.append("有空坑,当前没有符合已勾选规则和保留数量的蛋" if policy.manual_eggs else "有空坑,当前没有符合星级、收益和保留数量设置的蛋") if not actions and not self.notes: self.notes.append("等待孵化 / 成长,成熟后按保护条件处理") - return actions or self.purchase(snapshot, policy, daily_left) + return actions def batch_actions(self, actions, snapshot, policy): monsters = snapshot.monsters diff --git a/ranch_assistant/tests/test_hatch_timing.py b/ranch_assistant/tests/test_hatch_timing.py new file mode 100644 index 0000000..9d465a7 --- /dev/null +++ b/ranch_assistant/tests/test_hatch_timing.py @@ -0,0 +1,161 @@ +import copy +from dataclasses import asdict +import os +import time +import unittest +from unittest.mock import patch + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +from PySide6 import QtWidgets as W +from PySide6.QtTest import QTest + +from ranch_assistant.api import Session +from ranch_assistant.engine import Engine, demo_snapshot +from ranch_assistant.gui import Window +from ranch_assistant.model import Catalog, EggRule, Policy, Snapshot +from ranch_assistant.tests.test_core import workspace_temp + + +class HatchClient: + def __init__(self, catalog): + self.value = copy.deepcopy(demo_snapshot(catalog).raw) + self.template = self.value["monsters"][0] | {"mode": 2} + self.value["monsters"] = [] + self.value["stacks"] = [{"id": 1, "position": 0, "monsterId": -1}, + {"id": 2, "position": 1, "monsterId": -1}, {"id": 4, "position": 3, "monsterId": -1}] + self.value["items"] = [{"id": 501, "typeId": self.template["typeId"], "num": 5}] + self.calls = [] + self.session = Session("http://127.0.0.1/", "synthetic-test-token") + self.stale = False + + def snapshot(self): + return Snapshot(copy.deepcopy(self.value)) + + def call(self, path, payload): + self.calls.append((path, payload)) + if self.stale: + return {} + if path != "stackService/stackAddMonster": + raise AssertionError("Fast hatching executed another action") + egg = payload["eggs"][0] + mid = 1000 + len(self.calls) + next(slot for slot in self.value["stacks"] if slot["id"] == egg["stackId"])["monsterId"] = mid + next(item for item in self.value["items"] if item["id"] == egg["itemId"])["num"] -= 1 + self.value["monsters"].append(self.template | {"id": mid, "mode": 0, "timeStart": int(time.time() * 1000)}) + return {} + + def persist_session(self): + pass + + def close(self): + pass + + +def policy_for(client): + return Policy(manual_eggs=True, protect_star=6, protect_quality=5, buy=True, + egg_rules={str(client.template["typeId"]): asdict(EggRule(enabled=True, action="sell"))}) + + +class HatchTimingTests(unittest.TestCase): + def test_fast_hatching_skips_other_actions_and_retains_vip_and_reserve_limits(self): + catalog = Catalog() + client = HatchClient(catalog) + client.value["monsters"].append(client.template) + client.value["stacks"][0]["monsterId"] = client.template["id"] + engine = Engine(catalog, client) + engine.policy = policy_for(client) + engine.policy.reserved_eggs = {str(client.template["typeId"]): 4} + engine.auto = True + engine.read_snapshot() + self.assertEqual(engine.plans()[0].kind, "sell") + snapshot, _, _ = engine.poll(hatch_only=True) + self.assertEqual([path for path, _ in client.calls], ["stackService/stackAddMonster"]) + self.assertEqual(client.calls[0][1]["eggs"][0]["stackId"], 2) + self.assertIn(client.template["id"], snapshot.monsters) + self.assertFalse(engine.pending_hatches) + self.assertEqual(client.value["stacks"][2]["monsterId"], -1) + + def test_fast_worker_rechecks_stock_and_never_falls_back_to_buying(self): + catalog = Catalog() + client = HatchClient(catalog) + engine = Engine(catalog, client) + engine.policy = policy_for(client) + engine.auto = True + engine.poll(defer_hatch=True) + self.assertEqual(client.calls, []) + self.assertTrue(engine.pending_hatches) + client.value["items"][0]["num"] = 0 + client.value["monsters"].append(client.template | {"mode": 0, "timeStart": 1}) + engine.poll(hatch_only=True) + self.assertEqual(client.calls, []) + self.assertFalse(engine.pending_hatches) + + def test_unconfirmed_hatch_stops_automation_before_another_fill(self): + catalog = Catalog() + client = HatchClient(catalog) + client.stale = True + engine = Engine(catalog, client) + engine.policy = policy_for(client) + engine.auto = True + with self.assertRaisesRegex(ValueError, "坑位状态尚未同步"): + engine.poll(hatch_only=True) + self.assertFalse(engine.auto) + engine.poll(hatch_only=True) + self.assertEqual(len(client.calls), 1) + + +class HatchTimerGuiTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.app = W.QApplication.instance() or W.QApplication([]) + + def wait(self, window): + for _ in range(500): + self.app.processEvents() + QTest.qWait(2) + if not window.busy: + return + self.fail("Background hatch did not finish") + + def test_short_hatch_timer_does_not_change_poll_deadline_and_stops_on_pause(self): + with workspace_temp() as folder: + window = Window(folder) + window.timer.stop() + try: + self.wait(window) + client = HatchClient(window.catalog) + window.engine = Engine(window.catalog, client) + window.engine.last_heartbeat = time.monotonic() + window.egg_rules = policy_for(client).egg_rules + window.start_monitor.setChecked(True) + window.execute.setChecked(True) + with patch.object(window, "poll_delay", return_value=300), patch("ranch_assistant.gui.random.uniform", return_value=1.5) as draw: + window.refresh(automated=True) + self.wait(window) + deadline = window.next_poll + self.assertEqual(client.calls, []) + self.assertTrue(window.hatch_timer.isActive()) + self.assertEqual(window.hatch_timer.interval(), 1500) + self.assertEqual(draw.call_args.args, (1, 2)) + hatch_deadline = window.next_hatch + window.refresh(automated=True) + self.wait(window) + self.assertEqual(window.next_hatch, hatch_deadline) + self.assertEqual(draw.call_count, 1) + deadline = window.next_poll + window.next_hatch = time.monotonic() - 1 + window.schedule() + self.wait(window) + self.assertEqual(len(client.calls), 1) + self.assertEqual(window.next_poll, deadline) + self.assertTrue(window.hatch_timer.isActive()) + window.stop_workflow() + self.assertFalse(window.hatch_timer.isActive()) + window.schedule() + self.assertEqual(len(client.calls), 1) + finally: + window.close() + + +if __name__ == "__main__": + unittest.main()