Fix gift item instance IDs and per-monster cooldown scheduling
Use bag instance IDs required by the client protocol. Apply confirmed feel and giftDate values across stale queries, skip cooling targets, and schedule ready gifts independently of random polling. Replan cultivation locally and retain local strategy errors in diagnostics.
This commit is contained in:
@@ -26,7 +26,7 @@
|
||||
| 牧场与魔物管理 | 默认平铺全部魔物,可切换为按牧场折叠分组;显示容量、空位、等级与突破上限、资质、参考属性、好感上限及喜欢的物品。支持详情查看、多选锁定/解锁、派遣、指定喂养,以及确认费用后新建牧场。 |
|
||||
| 自动孵蛋与补货 | 按手动规则完成金币市场买蛋/抽蛋、孵化、成长同步、成熟收取、派遣或喂养;支持优先十连、金币保留和每日购蛋额度。空坑按优先级独立随机1~2秒装填,不受整体刷新间隔影响。 |
|
||||
| 资质保留与经验喂养 | 支持星级、综合资质、四项全S(4S)保护,另可保留资质严格高于牧场同种培养代表的新魔物。经验喂养按目标优先级批量提交素材,遵守当前突破上限与停止等级,保护锁定、在队和委托所需魔物。 |
|
||||
| 自动赠礼与好感培养 | 在背包选择物品、牧场选择目标后自动赠礼;支持喜欢物品筛选、赠礼间隔、库存保留及当前好感上限。可自动为每种魔物选择唯一培养代表,依次按等级、好感、成长资质比较,完全相同时随机选定并记住。 |
|
||||
| 自动赠礼与好感培养 | 在背包选择物品、牧场选择目标后自动赠礼;跳过冷却目标,连续处理其他可送目标,在本地倒计时并到期核对状态。支持喜欢物品筛选、库存保留及当前好感上限。可在本地自动为每种魔物选择唯一培养代表,依次按等级、好感、成长资质比较,完全相同时随机选定并记住。 |
|
||||
| 每日事务 | 查看并领取每日签到礼包、七日签到、累计奖励、已有VIP日奖和邮件附件;支持手动领取及按勾选项目自动领取。 |
|
||||
| 自动委托 | 根据每日剩余次数、城市与库存接取委托,推进已满足条件的步骤并领奖;显示金币和氪金奖励,金币、道具及魔物提交可分别限制。需要实战的步骤等待用户在游戏内完成。 |
|
||||
| 自动扫荡 | 按地区折叠显示关卡、难度、通关星级及可能掉落;账号地图首次读取后本地缓存,仅手动刷新关卡时重新获取。逐关勾选、选择已解锁难度和本日次数上限,配置保留体力与战队;处理普通扫荡及探索奖励事件,记录实际奖励。 |
|
||||
@@ -55,7 +55,7 @@
|
||||
资料包含1178个关卡和2079种道具名称;客户端或接口更新后可能需要重新适配。
|
||||
|
||||
账号凭据、策略、地图缓存、购蛋/扫荡记录及统计数据库均保存在本机 `local_state/ranch_helper/`,按账号和角色隔离。
|
||||
本次发布通过 **201项本地测试**,覆盖会话隔离、策略开关、培养流程、奖励处理、统计与界面响应;测试使用模拟数据和模拟服务,不代表所有功能均已通过真实账号验证。
|
||||
当前代码通过 **209项本地测试**,覆盖会话隔离、策略开关、培养流程、奖励处理、统计与界面响应;测试使用模拟数据和模拟服务,不代表所有功能均已通过真实账号验证。
|
||||
详细配置与实现范围见[辅助使用说明](ranch_assistant/README.md)。
|
||||
|
||||
## 项目目录与测试
|
||||
|
||||
@@ -50,6 +50,11 @@
|
||||
勾选“每种魔物只培养一只,自动选择培养代表”后,自动为牧场中的每种魔物选一只,按等级 → 好感 → 综合成长资质排序,无需逐只勾选。
|
||||
综合资质相同再比较四项成长;各项均相同时随机选定并按账号/角色记住。列表显示代表的ID、等级、好感和资质,“刷新 / 预览培养对象”可更新预览。
|
||||
同种代表满好感或冷却时不改喂同种其他魔物;可继续处理其他种类。自动模式下代表会受自动派遣/喂养保护,手动模式保留原有目标优先级。
|
||||
手动目标也会逐只判断,前一只冷却不会挡住后面的可赠礼目标;可送目标按账号顺序连续处理,无需等待整体随机刷新。
|
||||
成功赠礼后以响应中的 `feel / giftDate` 更新好感及冷却,短暂滞后的查询结果不会覆盖已确认状态。
|
||||
请求的 `itemId` 使用背包物品实例编号,按物品种类设置的规则会在发送前匹配到实际库存;旧版误用了种类编号,已修正。
|
||||
全部进入冷却后在本地倒计时,到期重新核对状态再赠礼;没有允许物品、库存不足或已达当前好感上限时不发送赠礼请求。
|
||||
勾选自动培养代表或同种资质提升保护时,先在本地后台按已有快照重算,不为筛选单独请求服务器;实际赠礼前仍读取状态。
|
||||
两个新开关均默认关闭,修改后自动保存并纳入统一策略导入/导出;选定实例保存在角色目录的 `cultivation_choices.json`,不跨账号复制。
|
||||
- 收益资料:749 种魔物数据来自用户提供的 APK 1.9.68,支持名称搜索和1–5星分别筛选,
|
||||
可导入 CSV/XLSX 覆盖价格、经验和时间。
|
||||
@@ -243,7 +248,8 @@
|
||||
- 自定义表:`typeId, sell_money, sell_exp, time_total`(秒),可只提供部分
|
||||
覆盖列;中文列名“编号、派遣金币、强化经验、孵化秒数”也支持。
|
||||
- 测试:`python -m unittest discover -s ranch_assistant/tests -v`。
|
||||
- 201 项本地测试通过,覆盖登录、会话隔离、账号关闭与移除、菜单账号路由、数字框滚轮、地图缓存、请求计数、等级与体力结算、成长同步、孵蛋与补货、同种魔物培养与资质提升保护、批量喂养、派遣、赠礼、统一策略配置、委托、扫荡、奖励统计与体力效率和每日奖励。
|
||||
- 209 项本地测试通过,覆盖登录、会话隔离、账号关闭与移除、菜单账号路由、数字框滚轮、地图缓存、请求计数、等级与体力结算、成长同步、孵蛋与补货、同种魔物培养与资质提升保护、批量喂养、派遣、赠礼、统一策略配置、委托、扫荡、奖励统计与体力效率和每日奖励。
|
||||
赠礼覆盖手动目标冷却跳过、连续赠礼、独立到期调度、成功响应回写、滞后查询及本地培养筛选不发请求的回归测试;本地策略与页面异常写入调试日志并标记为本地错误。
|
||||
登录后自动刷新、顶部统一策略开关、关闭策略后继续刷新及多账号批量开关均有回归覆盖。
|
||||
新增牧场树形/平铺切换、分组数量与空位、刷新保留折叠和控件、4S保留条件、随机刷新间隔及到期独立同步的回归测试。
|
||||
双账号与大量库存的界面响应继续通过测试;测试使用本地模拟数据和模拟服务,不操作真实账号库存。
|
||||
|
||||
@@ -77,6 +77,7 @@ class Engine:
|
||||
mon.update({field: entry[field] for field in fields if field in entry})
|
||||
rows.append(mon)
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
self.gift_planner.apply_confirmed(self.snapshot)
|
||||
self.sweeper.recover_reward_event(self.snapshot, getattr(getattr(self.client, "trace", None), "path", None))
|
||||
return self.snapshot
|
||||
|
||||
@@ -211,6 +212,12 @@ class Engine:
|
||||
response = self.client.call(action.path, action.payload)
|
||||
if action.kind == "buy":
|
||||
self.record_draw(response.get("eggs") or [])
|
||||
if action.kind == "gift":
|
||||
try:
|
||||
self.gift_planner.remember_success(self.snapshot, action, response)
|
||||
except ValueError:
|
||||
self.auto = False
|
||||
raise
|
||||
self.read_snapshot(sync_master=not hatch_only)
|
||||
if action.kind == "hatch":
|
||||
stack_id = action.payload["eggs"][0]["stackId"]
|
||||
@@ -400,7 +407,7 @@ class Engine:
|
||||
raw["monsters"] = [m for m in raw["monsters"] if m["id"] != mid]
|
||||
elif action.kind == "gift":
|
||||
target = self.snapshot.monsters[action.payload["monsterId"]]
|
||||
item = next(i for i in raw["items"] if int(i["typeId"]) == action.payload["itemId"])
|
||||
item = next(i for i in raw["items"] if int(i["id"]) == action.payload["itemId"])
|
||||
gain = int(self.catalog.monster(target.get("typeId")).get("like", {}).get(str(item["typeId"]), 0))
|
||||
target["feel"] = max(0, min(self.catalog.max_feel(target), int(target.get("feel") or 0) + gain))
|
||||
target["giftTime"] = int(time.time())
|
||||
|
||||
+44
-12
@@ -1,4 +1,5 @@
|
||||
"""Conservative item gifting, using the original client's caps and cooldown."""
|
||||
import math
|
||||
from .model import Action, seconds
|
||||
from .cultivation import CultivationSelector
|
||||
|
||||
@@ -12,6 +13,31 @@ class GiftPlanner:
|
||||
self.catalog = catalog
|
||||
self.cultivation = cultivation or CultivationSelector(catalog)
|
||||
self.notes = []
|
||||
self.next_ready_at = None
|
||||
self.confirmed = {}
|
||||
|
||||
def remember_success(self, snapshot, action, response):
|
||||
try:
|
||||
feel = float(response["feel"])
|
||||
gifted_at = seconds(response["giftDate"])
|
||||
if not math.isfinite(feel) or feel < 0 or not math.isfinite(gifted_at) or gifted_at <= 0:
|
||||
raise ValueError("Invalid gift state")
|
||||
except (KeyError, TypeError, ValueError, OverflowError) as error:
|
||||
raise ValueError("赠礼已返回,但缺少有效的 feel / giftDate;已关闭策略,请刷新核对") from error
|
||||
mid = action.payload["monsterId"]
|
||||
self.confirmed[mid] = {"owner": str(snapshot.raw["master"]["id"]),
|
||||
"type": str(snapshot.monsters[mid]["typeId"]), "feel": int(feel), "giftTime": gifted_at}
|
||||
|
||||
def apply_confirmed(self, snapshot):
|
||||
current = snapshot.monsters
|
||||
for mid, entry in list(self.confirmed.items()):
|
||||
mon = current.get(mid)
|
||||
if (str(snapshot.raw["master"]["id"]) != entry["owner"] or mon is None
|
||||
or str(mon.get("typeId")) != entry["type"] or mon.get("process") != 3
|
||||
or seconds(mon.get("giftTime")) >= entry["giftTime"]):
|
||||
del self.confirmed[mid]
|
||||
else:
|
||||
mon.update(feel=entry["feel"], giftTime=entry["giftTime"])
|
||||
|
||||
def candidates(self, snapshot, policy):
|
||||
if policy.gift_auto_representative:
|
||||
@@ -29,6 +55,7 @@ class GiftPlanner:
|
||||
|
||||
def plan(self, snapshot, policy, quest_policy=None):
|
||||
self.notes = []
|
||||
self.next_ready_at = None
|
||||
if not policy.gift_enabled:
|
||||
return []
|
||||
if not any(rule.get("enabled") for rule in policy.gift_items.values()):
|
||||
@@ -41,6 +68,7 @@ class GiftPlanner:
|
||||
if item.get("lock") or item.get("feedLock"):
|
||||
blocked.add(key)
|
||||
stocks = {}
|
||||
instances = {}
|
||||
for key, rule in policy.gift_items.items():
|
||||
if not rule.get("enabled") or totals.get(key, 0) <= 0:
|
||||
continue
|
||||
@@ -50,33 +78,37 @@ class GiftPlanner:
|
||||
continue
|
||||
reserve = item_reserve(key, policy, quest_policy) if quest_policy else int(rule.get("reserve", 0))
|
||||
available = max(0, totals[key] - max(int(rule.get("reserve", 0)), reserve))
|
||||
if available:
|
||||
item = next((item for item in snapshot.raw["items"] if str(item.get("typeId")) == key
|
||||
and int(item.get("num") or 0) > 0 and int(item.get("id") or 0) > 0), None)
|
||||
if available and item is not None:
|
||||
stocks[key] = available
|
||||
instances[key] = int(item["id"])
|
||||
if not stocks:
|
||||
self.notes.append("自动赠礼:背包中没有符合开关和保留数量的物品")
|
||||
return []
|
||||
cooldown = int(self.catalog.data["game_setting"].get("monGiftTime", 7200))
|
||||
candidates = self.candidates(snapshot, policy) if policy.gift_auto_representative else [self.target(snapshot, policy)[0]]
|
||||
for target in candidates:
|
||||
if target is None:
|
||||
continue
|
||||
actions = []
|
||||
for target in self.candidates(snapshot, policy):
|
||||
limit = self.catalog.max_feel(target)
|
||||
if int(target.get("feel") or 0) >= limit:
|
||||
continue
|
||||
elapsed = snapshot.now - seconds(target.get("giftTime"))
|
||||
if elapsed < cooldown:
|
||||
if len(self.notes) < 6:
|
||||
self.notes.append(f"自动赠礼:{self.catalog.monster_label(target)} 还需等待 {int(cooldown - elapsed)} 秒")
|
||||
continue
|
||||
likes = self.catalog.monster(target.get("typeId")).get("like") or {}
|
||||
usable = [key for key in stocks if not policy.gift_liked_only or int(likes.get(key, 0)) > 0]
|
||||
if not usable:
|
||||
continue
|
||||
ready_at = max(snapshot.now, seconds(target.get("giftTime")) + cooldown)
|
||||
self.next_ready_at = ready_at if self.next_ready_at is None else min(self.next_ready_at, ready_at)
|
||||
if ready_at > snapshot.now:
|
||||
if len(self.notes) < 6:
|
||||
self.notes.append(f"自动赠礼:{self.catalog.monster_label(target)} 还需等待 {math.ceil(ready_at - snapshot.now)} 秒")
|
||||
continue
|
||||
key = max(usable, key=lambda k: (int(likes.get(k, 0)), stocks[k], -int(k)))
|
||||
gain = int(likes.get(key, 0))
|
||||
name = self.catalog.item_name(key)
|
||||
return [Action("gift", f"赠礼 {self.catalog.monster_label(target)} ← {name}(好感 {target.get('feel', 0)}/{limit},预计 {gain:+d})",
|
||||
"monsterService/monsterSendGift", {"monsterId": int(target["id"]), "itemId": int(key)})]
|
||||
actions.append(Action("gift", f"赠礼 {self.catalog.monster_label(target)} ← {name}(好感 {target.get('feel', 0)}/{limit},预计 {gain:+d})",
|
||||
"monsterService/monsterSendGift", {"monsterId": int(target["id"]), "itemId": instances[key]}))
|
||||
if actions:
|
||||
return actions
|
||||
self.notes.append("自动赠礼:培养代表已达好感上限、处于冷却或缺少允许的礼物" if policy.gift_auto_representative
|
||||
else "自动赠礼:未选择目标、目标已达当前好感上限或没有符合偏好的礼物")
|
||||
return []
|
||||
|
||||
+61
-3
@@ -147,11 +147,13 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.engine = Engine(self.catalog)
|
||||
self.busy, self.monitoring = False, False
|
||||
self.active_job = None
|
||||
self.pending_preview = False
|
||||
self.presentation_active = True
|
||||
self.latest_render = None
|
||||
self.prepared_views = None
|
||||
self.next_poll = 0
|
||||
self.next_hatch = float("inf")
|
||||
self.next_gift = float("inf")
|
||||
self.hatch_timer = C.QTimer(self)
|
||||
self.hatch_timer.setSingleShot(True)
|
||||
self.hatch_timer.setTimerType(C.Qt.TimerType.PreciseTimer)
|
||||
@@ -477,6 +479,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.gift_status.setWordWrap(True)
|
||||
for widget in (self.gift_enabled, self.gift_auto_representative, self.gift_liked_only, self.gift_status):
|
||||
layout.addWidget(widget)
|
||||
self.gift_clock = W.QLabel("策略已关闭")
|
||||
layout.addWidget(self.gift_clock)
|
||||
for widget in (self.gift_enabled, self.gift_auto_representative, self.gift_liked_only):
|
||||
widget.toggled.connect(self.update_gift_status)
|
||||
note = W.QLabel("自动模式按等级 → 好感 → 综合成长资质选择每种魔物的一只代表,全部相同时随机选定并记住;忽略手动勾选的重复目标。\n代表满好感或冷却时不改喂同种另一只,可继续处理其他种类。礼物开关和保留数量仍在“背包”设置。")
|
||||
@@ -629,6 +633,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.set_strategy_checked(False)
|
||||
self.engine.auto = False
|
||||
self.pending_execute = False
|
||||
self.next_gift = float("inf")
|
||||
self.update_gift_clock()
|
||||
self.arm_hatching()
|
||||
self.update_workflow_status()
|
||||
|
||||
@@ -850,6 +856,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
for secret in (self.token.text(), self.key.text(), self.password.text()):
|
||||
if secret:
|
||||
message = message.replace(secret, "<隐藏>")
|
||||
if "策略暂不可用" in message or "页面数据暂不可用" in message:
|
||||
self.trace.emit("error", "本地策略 / 页面处理", scope="local", message=message)
|
||||
self.log.appendPlainText(time.strftime("%H:%M:%S ") + message)
|
||||
|
||||
def remember_log_sizes(self, *args):
|
||||
@@ -1172,6 +1180,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
elif self.pending_refresh is not None:
|
||||
tab, self.pending_refresh = self.pending_refresh, None
|
||||
C.QTimer.singleShot(0, lambda: self.refresh_page(tab))
|
||||
elif self.pending_preview and not self.closed:
|
||||
C.QTimer.singleShot(0, self.preview_cultivation)
|
||||
elif self.pending_execute and self.monitoring and self.strategy_toggle.isChecked() and not self.closed:
|
||||
self.pending_execute = False
|
||||
C.QTimer.singleShot(0, lambda: self.refresh(automated=True))
|
||||
@@ -1195,9 +1205,9 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
note="worker总耗时包含网络;大列表在后续短批次更新")
|
||||
|
||||
def apply_result(self, kind, value):
|
||||
if kind in ("poll", "hatch", "monster_lock", "manual_monsters", "expansion", "growth_sync", "master_sync", "map_refresh", "daily_claim"):
|
||||
if kind in ("poll", "hatch", "monster_lock", "manual_monsters", "expansion", "growth_sync", "master_sync", "map_refresh", "daily_claim", "policy_preview"):
|
||||
snapshot, plans, message = value
|
||||
if not self.engine.demo and not self.closed:
|
||||
if kind != "policy_preview" and not self.engine.demo and not self.closed:
|
||||
self.monitoring = True
|
||||
self.engine.heartbeat_enabled = True
|
||||
self.render(snapshot, plans)
|
||||
@@ -1208,6 +1218,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
if "策略暂不可用" in message:
|
||||
self.stop_workflow()
|
||||
self.arm_hatching()
|
||||
self.arm_gifting()
|
||||
elif kind == "heartbeat":
|
||||
self.report(value)
|
||||
elif kind == "analysis":
|
||||
@@ -1384,7 +1395,32 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.hatch_timer.stop()
|
||||
self.next_hatch = float("inf")
|
||||
|
||||
def arm_gifting(self):
|
||||
ready_at = self.engine.gift_planner.next_ready_at
|
||||
if (self.monitoring and self.strategy_toggle.isChecked() and self.gift_enabled.isChecked()
|
||||
and not self.closed and self.engine.snapshot is not None and ready_at is not None):
|
||||
self.next_gift = time.monotonic() + max(0, ready_at - self.engine.snapshot.now)
|
||||
else:
|
||||
self.next_gift = float("inf")
|
||||
self.update_gift_clock()
|
||||
|
||||
def update_gift_clock(self):
|
||||
if not hasattr(self, "gift_clock"):
|
||||
return
|
||||
if not self.strategy_toggle.isChecked():
|
||||
text = "策略已关闭"
|
||||
elif not self.gift_enabled.isChecked():
|
||||
text = "自动赠礼未启用"
|
||||
elif self.next_gift == float("inf"):
|
||||
text = "当前没有符合条件的赠礼目标或物品,等待状态更新"
|
||||
else:
|
||||
remaining = self.next_gift - time.monotonic()
|
||||
text = "已有可赠礼目标,正在顺序处理" if remaining <= 0 else "下次可赠礼倒计时:" + duration(remaining)
|
||||
if self.gift_clock.text() != text:
|
||||
self.gift_clock.setText(text)
|
||||
|
||||
def schedule(self):
|
||||
self.update_gift_clock()
|
||||
if self.busy or self.closed:
|
||||
return
|
||||
now = time.monotonic()
|
||||
@@ -1399,6 +1435,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.refresh(automated=True, hatch_only=True)
|
||||
elif self.monitoring and now >= self.next_poll:
|
||||
self.refresh(automated=True)
|
||||
elif self.monitoring and self.strategy_toggle.isChecked() and now >= self.next_gift:
|
||||
self.refresh(automated=True)
|
||||
|
||||
def render(self, snapshot, plans):
|
||||
self.latest_render = (snapshot, plans)
|
||||
@@ -1738,19 +1776,39 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
return
|
||||
changed = any(asdict(getattr(self.engine, key)) != value[key]
|
||||
for key in ("policy", "quest_policy", "daily_policy", "sweep_policy"))
|
||||
local_selection_changed = any(getattr(self.engine.policy, key) != value["policy"][key]
|
||||
for key in ("gift_auto_representative", "keep_better_quality"))
|
||||
self.engine.policy = Policy(**value["policy"])
|
||||
self.engine.quest_policy = QuestPolicy(**value["quest_policy"])
|
||||
self.engine.daily_policy = DailyPolicy(**value["daily_policy"])
|
||||
self.engine.sweep_policy = SweepPolicy(**value["sweep_policy"])
|
||||
if changed and self.monitoring and self.strategy_toggle.isChecked():
|
||||
if local_selection_changed:
|
||||
self.pending_preview = True
|
||||
self.preview_cultivation()
|
||||
elif changed and self.monitoring and self.strategy_toggle.isChecked():
|
||||
if self.busy:
|
||||
self.pending_execute = True
|
||||
else:
|
||||
self.next_poll = 0
|
||||
self.arm_hatching()
|
||||
self.arm_gifting()
|
||||
self.statusBar().showMessage("规则已自动保存并应用", 3000)
|
||||
return value
|
||||
|
||||
def preview_cultivation(self):
|
||||
if self.closed or self.busy:
|
||||
return
|
||||
self.pending_preview = False
|
||||
if self.engine.snapshot is None:
|
||||
return
|
||||
engine = self.engine
|
||||
def preview():
|
||||
try:
|
||||
return engine.snapshot, engine.plans(), "培养对象已根据已有数据在本地更新"
|
||||
except (ValueError, TypeError, KeyError, AttributeError, OSError) as error:
|
||||
return engine.snapshot, [], f"本地策略暂不可用:{type(error).__name__}: {error}"
|
||||
self.submit("policy_preview", preview)
|
||||
|
||||
def save_config(self, *args, quiet=False):
|
||||
try:
|
||||
value = self.config_value()
|
||||
|
||||
@@ -16,6 +16,8 @@ from ranch_assistant.gui import Window
|
||||
from ranch_assistant.model import Catalog, Planner, Policy, Snapshot
|
||||
from ranch_assistant.policy_io import import_config, portable_config
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
from ranch_assistant.tests.test_accounts import fake_client, role_snapshot
|
||||
from ranch_assistant.api import Session
|
||||
|
||||
|
||||
def monster(catalog, mid, *, level=10, feel=0, scale=.3, species=1001010, process=3):
|
||||
@@ -174,3 +176,40 @@ class CultivationGuiTests(unittest.TestCase):
|
||||
self.assertTrue(window.gift_auto_representative.isChecked())
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_selecting_representatives_replans_locally_without_an_api_request(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
calls = []
|
||||
try:
|
||||
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
|
||||
session = Session("http://127.0.0.1/", "synthetic-token", account_id="fixture", server_id=1, role_id=101)
|
||||
client = fake_client(session, window.catalog, calls)
|
||||
window.result("connected", (client, Snapshot(role_snapshot(window.catalog, 101))))
|
||||
window.gift_auto_representative.setChecked(True)
|
||||
self.wait(lambda: not window.auto_save_timer.isActive() and not window.busy and bool(window.engine.cultivation.selected))
|
||||
self.assertEqual(calls, [])
|
||||
self.assertTrue(window.monitoring)
|
||||
self.assertFalse(window.strategy_toggle.isChecked())
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_local_selection_failure_is_recorded_as_local_and_keeps_monitoring(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
|
||||
window.monitoring = True
|
||||
with patch.object(window.engine.cultivation, "select", side_effect=ValueError("fixture-selection-failure")):
|
||||
window.gift_auto_representative.setChecked(True)
|
||||
self.wait(lambda: any("fixture-selection-failure" in e.get("message", "") for e in window.trace.events))
|
||||
self.wait(lambda: not window.busy)
|
||||
event = next(e for e in window.trace.events if "fixture-selection-failure" in e.get("message", ""))
|
||||
self.assertEqual(event["scope"], "local")
|
||||
self.assertEqual(event["kind"], "error")
|
||||
self.assertTrue(window.monitoring)
|
||||
self.assertFalse(window.strategy_toggle.isChecked())
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import copy
|
||||
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.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.gifts import GiftPlanner
|
||||
from ranch_assistant.gui import Window
|
||||
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
|
||||
NOW = 1_800_000_000
|
||||
GIFT = "monsterService/monsterSendGift"
|
||||
|
||||
|
||||
def gift_snapshot(catalog):
|
||||
raw = copy.deepcopy(demo_snapshot(catalog).raw)
|
||||
first = copy.deepcopy(next(m for m in raw["monsters"] if m["process"] == 3))
|
||||
first.update(id=1, feel=0, giftTime=0, entangleLevel=0)
|
||||
second = first | {"id": 2}
|
||||
raw.update(monsters=[first, second], stacks=[], teams=[],
|
||||
items=[{"id": 10, "typeId": 30005, "num": 10}])
|
||||
return Snapshot(raw)
|
||||
|
||||
|
||||
def gift_policy():
|
||||
return Policy(enabled=False, gift_enabled=True, gift_liked_only=False,
|
||||
gift_targets={"1": 1, "2": 2}, gift_items={"30005": {"enabled": True, "reserve": 0}})
|
||||
|
||||
|
||||
class GiftClient:
|
||||
def __init__(self, catalog):
|
||||
self.raw = gift_snapshot(catalog).raw
|
||||
self.calls = []
|
||||
self.response = {"feel": 10, "giftDate": NOW * 1000, "addFeel": 10}
|
||||
|
||||
def snapshot(self):
|
||||
# A successful query can briefly lag behind the confirmed gift result.
|
||||
return Snapshot(copy.deepcopy(self.raw))
|
||||
|
||||
def call(self, path, payload):
|
||||
self.calls.append((path, payload))
|
||||
if path != GIFT:
|
||||
raise AssertionError(path)
|
||||
return self.response
|
||||
|
||||
|
||||
class GiftTimingTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.catalog = Catalog()
|
||||
|
||||
def test_gift_request_uses_bag_instance_id_instead_of_item_type(self):
|
||||
snapshot = gift_snapshot(self.catalog)
|
||||
action = GiftPlanner(self.catalog).plan(snapshot, gift_policy())[0]
|
||||
self.assertEqual(action.payload["itemId"], 10)
|
||||
self.assertNotEqual(action.payload["itemId"], 30005)
|
||||
|
||||
def test_success_response_updates_each_monster_despite_stale_queries(self):
|
||||
with patch("ranch_assistant.model.time.time", return_value=NOW):
|
||||
client = GiftClient(self.catalog)
|
||||
engine = Engine(self.catalog, client)
|
||||
engine.policy = gift_policy()
|
||||
engine.auto = True
|
||||
first, _, _ = engine.poll()
|
||||
self.assertEqual(first.monsters[1]["feel"], 10)
|
||||
self.assertEqual(first.monsters[1]["giftTime"], NOW)
|
||||
engine.poll()
|
||||
engine.poll()
|
||||
self.assertEqual([payload["monsterId"] for _, payload in client.calls], [1, 2])
|
||||
|
||||
def test_next_due_uses_earliest_eligible_cooldown_and_ignores_full_targets(self):
|
||||
with patch("ranch_assistant.model.time.time", return_value=NOW):
|
||||
snapshot = gift_snapshot(self.catalog)
|
||||
snapshot.monsters[1]["giftTime"] = (NOW - 7200 + 120) * 1000
|
||||
snapshot.monsters[2]["giftTime"] = (NOW - 7200 + 15) * 1000
|
||||
planner = GiftPlanner(self.catalog)
|
||||
self.assertEqual(planner.plan(snapshot, gift_policy()), [])
|
||||
self.assertEqual(planner.next_ready_at, NOW + 15)
|
||||
snapshot.monsters[2]["feel"] = self.catalog.max_feel(snapshot.monsters[2])
|
||||
planner.plan(snapshot, gift_policy())
|
||||
self.assertEqual(planner.next_ready_at, NOW + 120)
|
||||
snapshot.raw["items"][0]["num"] = 0
|
||||
planner.plan(snapshot, gift_policy())
|
||||
self.assertIsNone(planner.next_ready_at)
|
||||
|
||||
def test_unconfirmed_gift_result_stops_before_another_write(self):
|
||||
with patch("ranch_assistant.model.time.time", return_value=NOW):
|
||||
client = GiftClient(self.catalog)
|
||||
client.response = {"feel": 10}
|
||||
engine = Engine(self.catalog, client)
|
||||
engine.policy = gift_policy()
|
||||
engine.auto = True
|
||||
with self.assertRaisesRegex(ValueError, "feel / giftDate"):
|
||||
engine.poll()
|
||||
self.assertFalse(engine.auto)
|
||||
engine.poll()
|
||||
self.assertEqual(len(client.calls), 1)
|
||||
|
||||
|
||||
class GiftTimingGuiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.app = W.QApplication.instance() or W.QApplication([])
|
||||
|
||||
def wait(self, window):
|
||||
for _ in range(600):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(2)
|
||||
if not window.busy:
|
||||
return
|
||||
self.fail("Gift worker did not finish")
|
||||
|
||||
def test_gifts_continue_without_waiting_for_poll_and_stop_at_each_cooldown(self):
|
||||
with workspace_temp() as folder, patch("ranch_assistant.model.time.time", return_value=NOW):
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.engine = Engine(window.catalog)
|
||||
window.engine.snapshot = gift_snapshot(window.catalog)
|
||||
policy = gift_policy()
|
||||
window.ranch_enabled.setChecked(False)
|
||||
window.gift_enabled.setChecked(True)
|
||||
window.gift_liked_only.setChecked(False)
|
||||
window.gift_targets = policy.gift_targets
|
||||
window.gift_items = policy.gift_items
|
||||
window.monitoring = True
|
||||
window.set_strategy_checked(True)
|
||||
with patch.object(window, "poll_delay", return_value=300):
|
||||
window.refresh(automated=True)
|
||||
self.wait(window)
|
||||
self.assertGreater(window.next_poll, time.monotonic() + 250)
|
||||
window.schedule()
|
||||
self.wait(window)
|
||||
self.assertTrue(all(m["giftTime"] > 0 for m in window.engine.snapshot.raw["monsters"]))
|
||||
self.assertGreater(window.next_gift, time.monotonic() + 7100)
|
||||
window.schedule()
|
||||
self.assertFalse(window.busy)
|
||||
due = window.next_gift
|
||||
window.next_poll = float("inf")
|
||||
with patch("ranch_assistant.model.time.time", return_value=NOW + 7201), patch("ranch_assistant.gui.time.monotonic", return_value=due + 1):
|
||||
window.schedule()
|
||||
self.wait(window)
|
||||
self.assertTrue(any(m["giftTime"] > NOW for m in window.engine.snapshot.raw["monsters"]))
|
||||
window.stop_workflow()
|
||||
self.assertEqual(window.next_gift, float("inf"))
|
||||
self.assertTrue(window.monitoring)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -43,7 +43,7 @@ class GiftTests(unittest.TestCase):
|
||||
|
||||
def test_liked_item_respects_reserve_cap_and_cooldown(self):
|
||||
action = self.planner.plan(self.snapshot, self.policy)[0]
|
||||
self.assertEqual(action.payload, {"monsterId": 900, "itemId": int(self.liked)})
|
||||
self.assertEqual(action.payload, {"monsterId": 900, "itemId": 2000})
|
||||
self.snapshot.raw["items"][-2]["num"] = 2
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy), [])
|
||||
self.snapshot.raw["items"][-2]["num"] = 3
|
||||
@@ -59,11 +59,21 @@ class GiftTests(unittest.TestCase):
|
||||
self.policy.gift_items[self.liked]["enabled"] = False
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy), [])
|
||||
self.policy.gift_liked_only = False
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["itemId"], int(self.disliked))
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["itemId"], 2001)
|
||||
|
||||
def test_quest_reserves_take_precedence(self):
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy, QuestPolicy(item_reserves={self.liked: 3})), [])
|
||||
|
||||
def test_cooling_manual_target_does_not_block_other_selected_targets(self):
|
||||
other = copy.deepcopy(self.target)
|
||||
other["id"] = 901
|
||||
self.snapshot.raw["monsters"].append(other)
|
||||
self.policy.gift_targets["901"] = 2
|
||||
self.target["giftTime"] = self.snapshot.now * 1000
|
||||
plans = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertTrue(plans, "A cooling first target blocked another ready target")
|
||||
self.assertEqual(plans[0].payload["monsterId"], 901)
|
||||
|
||||
def test_demo_consumes_one_item_and_clamps_feel(self):
|
||||
engine = Engine(self.catalog)
|
||||
engine.snapshot = self.snapshot
|
||||
|
||||
Reference in New Issue
Block a user