Add region stage selection, eligible sweeps and daily rewards
This commit is contained in:
@@ -4,6 +4,29 @@ Implemented in `ranch_assistant`; launch `Start_Ranch_Helper.cmd`.
|
|||||||
See `ranch_assistant/README.md` for login, strategies and page screenshots.
|
See `ranch_assistant/README.md` for login, strategies and page screenshots.
|
||||||
The successful V4 combat package was not modified or rebuilt.
|
The successful V4 combat package was not modified or rebuilt.
|
||||||
|
|
||||||
|
## Stage tree, built-in sweep and daily rewards
|
||||||
|
|
||||||
|
The stage page now groups the shipped 1178 stages by region, with account-specific
|
||||||
|
unlocked difficulty choices, stars, possible drops, per-stage checkboxes and local
|
||||||
|
daily attempt limits. Wire progress is a list of difficulty IDs, not a boolean
|
||||||
|
array. The previous search missed the pinyin `saodang` methods: ordinary stages
|
||||||
|
with all three difficulties cleared have an official sweep branch that reuses
|
||||||
|
stageStart/battleEnd/recordBattleResult without battle simulation. This branch is
|
||||||
|
implemented only with the original eligibility conditions. Events and uncertain
|
||||||
|
writes stop with a persisted pending record; no automatic replay occurs.
|
||||||
|
|
||||||
|
每日事务 groups sign-in gifts, seven-day check-ins, cumulative rewards, eligible
|
||||||
|
VIP daily gifts and mail attachment claims. Refreshes remain read-only; explicit
|
||||||
|
selection and execution are required. Null VIPs, millisecond/second timestamps,
|
||||||
|
JSON mail rewards and stale reads are handled. New policy and budget files remain
|
||||||
|
role-isolated. Full local suite: 100 tests passed. Live reward/sweep use is still
|
||||||
|
unverified; no real account or phone was operated during this work.
|
||||||
|
|
||||||
|
The screenshot page remains necessary for ADB real battles such as special
|
||||||
|
pudding stages; it is not required for the eligible API sweeps. Its content is
|
||||||
|
now scrollable and table rows fit native buttons, preventing overlap when the log
|
||||||
|
is enlarged. See `STAGES_DAILY.md` for source evidence and endpoint details.
|
||||||
|
|
||||||
## Current workflow
|
## Current workflow
|
||||||
|
|
||||||
- The compact native page is named 自动孵蛋. The backpack table has per-species
|
- The compact native page is named 自动孵蛋. The backpack table has per-species
|
||||||
@@ -98,9 +121,9 @@ The successful V4 combat package was not modified or rebuilt.
|
|||||||
resources, advance satisfied steps and claim rewards. Needed eggs/monster
|
resources, advance satisfied steps and claim rewards. Needed eggs/monster
|
||||||
types are reserved against ranch actions. Battles and subsequent story steps
|
types are reserved against ranch actions. Battles and subsequent story steps
|
||||||
wait for the game; automatic navigation to each quest battle is not implemented.
|
wait for the game; automatic navigation to each quest battle is not implemented.
|
||||||
- The map view shows stage/difficulty unlock and pass records from the account
|
- The map tree shows account difficulty unlocks, stars and possible rewards.
|
||||||
snapshot, and can choose a normal ADB farming target. There is no claimed
|
The official eligible-stage sweep reuses the existing stage endpoints;
|
||||||
standalone instant-sweep endpoint or headless battle simulator.
|
special stages can instead choose a normal ADB farming target.
|
||||||
- The incubation view includes closed positions and the separate VIP slot.
|
- The incubation view includes closed positions and the separate VIP slot.
|
||||||
Real snapshots use monsterId=-1 for an empty slot; <=0 values now count as
|
Real snapshots use monsterId=-1 for an empty slot; <=0 values now count as
|
||||||
empty and negative IDs never enter the managed-monster set. Offline replay of
|
empty and negative IDs never enter the managed-monster set. Offline replay of
|
||||||
@@ -158,7 +181,8 @@ The successful V4 combat package was not modified or rebuilt.
|
|||||||
- `NetStage.as`, `BattleData.as`, `BattlePanel.as`: ordinary stage start,
|
- `NetStage.as`, `BattleData.as`, `BattlePanel.as`: ordinary stage start,
|
||||||
local simulation and `battleEnd` containing kills, damage, time, formation
|
local simulation and `battleEnd` containing kills, damage, time, formation
|
||||||
and other fields. This is not merely a success flag. Server-side validation
|
and other fields. This is not merely a success flag. Server-side validation
|
||||||
remains unknown. No sweep endpoint was found in the inspected network classes.
|
remains unknown. `StageStartPanel.doSaodangBattle` separately implements the
|
||||||
|
built-in all-difficulties-cleared sweep using the same network endpoints.
|
||||||
- `MYRCryptor.as` and `tools/extract_ranch_catalog.py`: MD5 resource paths,
|
- `MYRCryptor.as` and `tools/extract_ranch_catalog.py`: MD5 resource paths,
|
||||||
zlib/AMF3 table decoding. Extracted 749 monsters, 1,178 stages, 78 special-stage
|
zlib/AMF3 table decoding. Extracted 749 monsters, 1,178 stages, 78 special-stage
|
||||||
entries and 83 recurring task definitions, plus rooms, server and game settings.
|
entries and 83 recurring task definitions, plus rooms, server and game settings.
|
||||||
@@ -169,7 +193,9 @@ method informs the configurable strategy; numeric values come from the APK.
|
|||||||
|
|
||||||
## Validation and remaining inputs
|
## Validation and remaining inputs
|
||||||
|
|
||||||
88 unit/integration tests pass: local encrypted HTTP and inventory actions,
|
100 unit/integration tests pass: eligible-stage sweep and daily claim workflows,
|
||||||
|
pending writes and role/day budgets, stage tree/rule restoration and scroll
|
||||||
|
geometry, plus local encrypted HTTP and inventory actions,
|
||||||
SDK password form/headers -> two Android regions -> selected region entry ->
|
SDK password form/headers -> two Android regions -> selected region entry ->
|
||||||
snapshot, verification/limited-login stops, recurring tasks and protections,
|
snapshot, verification/limited-login stops, recurring tasks and protections,
|
||||||
map unlocks per difficulty, screenshot/profile storage and invalidation, fake
|
map unlocks per difficulty, screenshot/profile storage and invalidation, fake
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# 地图、内置扫荡与每日事务
|
||||||
|
|
||||||
|
数据来源:用户提供的 1.9.68 APK、已反编译 AS3,以及现有本地日志的只读回放。
|
||||||
|
新流程由本地假客户端与 Qt 测试验证,未连接官方账号执行领奖、开战或扫荡。
|
||||||
|
|
||||||
|
## 地图状态
|
||||||
|
|
||||||
|
- `element/master/HistoryVo.as:415`:`unlockStage`、`passStage` 的网络格式是
|
||||||
|
`{ "0101": ["1", "2"] }`;AS3 转成每难度布尔字段。不能把原列表的数组下标当难度标记。
|
||||||
|
- `element/stage/StageVo.as:20`:星级是最高已通关难度,0~3;全通要求1、2、3都存在。
|
||||||
|
- `element/city/CityVo.as:46`:难度2/3还需通过地区的 `openHardModeStage` /
|
||||||
|
`openExtraModeStage` 指定关卡;空配置不设额外门槛。
|
||||||
|
- `levelLock`、`closed`、`stage_sp.condition` 继续限制可选难度和当前开放状态。
|
||||||
|
- `stage_info` 的 `tagname` 是界面编号,例如1-1;内部编号为0101。
|
||||||
|
- 地区名来自 `game_setting.cityInfo`,不另有 `city_info.json` 文件。
|
||||||
|
- 每个难度的 `reward` 保存金币/经验和随机物品/魔物池。界面列出可能奖励,
|
||||||
|
物品名来自 `item_info`;随机池不意味着每件必掉。原先裁剪资料丢弃了这些字段,现已保留。
|
||||||
|
|
||||||
|
## 内置扫荡
|
||||||
|
|
||||||
|
此前“未发现独立扫荡接口”不足以判断没有扫荡功能;拼音 `saodang` 才是实际方法名。
|
||||||
|
|
||||||
|
- `panel/stage/StagePanel.as:421`:按钮开放条件严格为
|
||||||
|
`!curstage.special && !curstage.posmode && curstage.getAllLevelPass()`。
|
||||||
|
- `panel/stage/StageStartPanel.as:81`:`startSaodang()` 设置扫荡模式后复用 `start()`。
|
||||||
|
当前难度有任务或触发随机事件时退出扫荡分支,不能直接继续普通扫荡结算。
|
||||||
|
- `StageStartPanel.as:183`:`doSaodangBattle()` 使用当前所选战队ID和默认战斗统计,
|
||||||
|
不运行实际战斗模拟。辅助仅在上述条件满足时复用该官方分支。
|
||||||
|
|
||||||
|
| 顺序 | 请求 | 参数/处理 |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | `stageService/stageStart` | `stageTypeId`, `stageLevel`;检查`triggerEvent`,遇事件停止 |
|
||||||
|
| 2 | `battleService/battleEnd` | `battleData`;结构见`BattleData.as`、`BattlePosition.as`,阵容取实际战队 |
|
||||||
|
| 3 | `battleService/recordBattleResult` | `stageId`, `cityId`(原客户端取编号第二个字符), `result` |
|
||||||
|
| 4 | `masterService/masterQueryDetail` | 重读体力、物品、魔物经验、进度等权威状态 |
|
||||||
|
|
||||||
|
辅助不向未全通关关卡使用此分支;特殊活动仍通过手机实战。
|
||||||
|
本地次数按角色/北京时间日期/关卡/难度记账,发请求前预留;它不代表官方每日剩余次数。
|
||||||
|
异常或事件保留本地pending记录,禁止自动重发;用户在游戏内处理后可清除。
|
||||||
|
手机实战与接口扫荡互斥,其他牧场/每日/委托操作在同一worker里串行。
|
||||||
|
|
||||||
|
## 每日与邮件
|
||||||
|
|
||||||
|
| 项目 | 状态来源 | 领取请求 | 条件 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 每日签到礼包 | `activityHistory.dailyGift` | `dailyGiftService/dailyGiftSign` | 本日未领 |
|
||||||
|
| 七日签到 | `activityHistory.dailyCheck` | `dailyCheckService/dailyCheck` | `checkDay<7`且本日未领 |
|
||||||
|
| 累计签到奖励 | `dailyGift`及`activity_info.loopCheckReward` | `dailyGiftService/dailyLoopReward` | 活动开放且累计天数达标 |
|
||||||
|
| VIP日奖 | `activityHistory.vipInfo` | `vipService/getReward` | 已有有效资格且本日未领 |
|
||||||
|
| 邮件附件 | 快照的`mails` | `mailService/mailGetReward` | `mailId`;有附件、未领、未过期 |
|
||||||
|
|
||||||
|
- `NetActi.as`、`center/ActiCenter.as`、`element/master/ActivityHistoryVo.as`是签到请求及字段证据。
|
||||||
|
- `dailyGiftCheckTime`、`checkTime`、`getTime`等统一兼容毫秒/秒,日期按北京时间比较。
|
||||||
|
`None`不参与`int(None)`转换。VIP为空显示无资格。
|
||||||
|
- `ActivityHistoryVo.loopCheckRewardDayNum()`取连续签到数、距上次累计领奖日差、活动目标的最小值。
|
||||||
|
- `center/MailCenter.as:44`:`reward`是JSON字符串,`isGetReward==1`为已领,`createTime`为毫秒。
|
||||||
|
`element/msg/MailVo.as`按日历日计算普通邮件七天期限。
|
||||||
|
- 刷新只读已有快照字段;领取必须点按钮或启用自动策略。不会发送
|
||||||
|
`dailyGiftUpdate`、付费开通VIP、邮件删除/已读请求。
|
||||||
|
- 每次写请求前持久化本日尝试标记;响应旧数据或网络结果不明时不会反复领取。
|
||||||
|
|
||||||
|
截图页仍用于ADB手机实战,使用可滚动容器和符合按钮实际高度的行高;
|
||||||
|
接口扫荡和每日事务不依赖截图。保持原生Qt样式,未修改窗口边框。
|
||||||
@@ -32,8 +32,11 @@
|
|||||||
支持复制/导出,自动保存本地脱敏日志。
|
支持复制/导出,自动保存本地脱敏日志。
|
||||||
- 自动委托:按每日剩余接取次数、解锁城市和库存,接取、推进已满足条件的步骤、
|
- 自动委托:按每日剩余接取次数、解锁城市和库存,接取、推进已满足条件的步骤、
|
||||||
领取奖励;列表显示奖励金币和氪金数量。提交金币、道具、魔物分别受策略限制。战斗步骤等待游戏实际完成。
|
领取奖励;列表显示奖励金币和氪金数量。提交金币、道具、魔物分别受策略限制。战斗步骤等待游戏实际完成。
|
||||||
- 地图关卡:显示资料表中的关卡及各难度,按账号返回的解锁/通关记录筛选,
|
- 地图关卡:按地区折叠显示安装包内的关卡、难度、掉落及账号解锁/通关记录,
|
||||||
可以设为 ADB 自动战斗目标。
|
每关可勾选、选择已解锁难度和本日上限;满足游戏原有条件的普通关卡可接口扫荡,
|
||||||
|
其余可设为 ADB 自动战斗目标。
|
||||||
|
- 每日事务:集中查看每日签到礼包、七日签到、累计奖励、VIP日奖和邮件附件;
|
||||||
|
可立即领取勾选项目,或开启监控时自动领取。刷新本身只读。
|
||||||
- 页面截图配置:每个页面一个截图按钮,自动保存原图与设备、分辨率、关卡、难度。
|
- 页面截图配置:每个页面一个截图按钮,自动保存原图与设备、分辨率、关卡、难度。
|
||||||
截图无需登录或 Token,不会点击或切换手机页面;由助手查看样本后生成按钮配置。
|
截图无需登录或 Token,不会点击或切换手机页面;由助手查看样本后生成按钮配置。
|
||||||
- 布丁史莱姆牧场:通过 ADB 操作手机里的实际战斗;根据当前体力、
|
- 布丁史莱姆牧场:通过 ADB 操作手机里的实际战斗;根据当前体力、
|
||||||
@@ -229,7 +232,9 @@
|
|||||||
- 自定义表:`typeId, sell_money, sell_exp, time_total`(秒),可只提供部分
|
- 自定义表:`typeId, sell_money, sell_exp, time_total`(秒),可只提供部分
|
||||||
覆盖列;中文列名“编号、派遣金币、强化经验、孵化秒数”也支持。
|
覆盖列;中文列名“编号、派遣金币、强化经验、孵化秒数”也支持。
|
||||||
- 测试:`python -m unittest discover -s ranch_assistant/tests -v`。
|
- 测试:`python -m unittest discover -s ranch_assistant/tests -v`。
|
||||||
- 88 项测试通过,新增加密HTTP十连→实际赠蛋→负数空坑孵化→成长结算→派遣→余额刷新、逐种优先级和补货、
|
- 100 项测试通过,覆盖难度列表解析、扫荡条件/请求顺序/异常暂停/跨角色每日额度、
|
||||||
|
签到与邮件JSON/空VIP/时间单位/失败不重试、树形规则恢复和截图页不重叠;以及
|
||||||
|
加密HTTP十连→实际赠蛋→负数空坑孵化→成长结算→派遣→余额刷新、逐种优先级和补货、
|
||||||
多目标喂养优先级、锁定/手动派遣/喂养、开坑与建牧场的费用复核和取消确认、金币/库存/每日额度限制、
|
多目标喂养优先级、锁定/手动派遣/喂养、开坑与建牧场的费用复核和取消确认、金币/库存/每日额度限制、
|
||||||
购蛋超时记账、突破等级上限、星级筛选、启动/停止/忙时排队和委托奖励显示;也覆盖多账号并行/重启恢复、账号和角色隔离、请求计数持久化、超时恢复、错角色阻止、
|
购蛋超时记账、突破等级上限、星级筛选、启动/停止/忙时排队和委托奖励显示;也覆盖多账号并行/重启恢复、账号和角色隔离、请求计数持久化、超时恢复、错角色阻止、
|
||||||
右键只读刷新、空值响应显示、心跳、关闭页签,以及四位年份的进入签名、APK 追踪渠道、区服引用还原/去重、两个角色显示、选二区登录、本地错误去重,
|
右键只读刷新、空值响应显示、心跳、关闭页签,以及四位年份的进入签名、APK 追踪渠道、区服引用还原/去重、两个角色显示、选二区登录、本地错误去重,
|
||||||
@@ -248,7 +253,25 @@
|
|||||||
已接委托需要的魔物种类和蛋会纳入牧场保留。
|
已接委托需要的魔物种类和蛋会纳入牧场保留。
|
||||||
“也接取需要实战的委托”只允许接取此类任务,当前不会自动导航到每项委托的专用战斗。
|
“也接取需要实战的委托”只允许接取此类任务,当前不会自动导航到每项委托的专用战斗。
|
||||||
|
|
||||||
现有客户端普通关卡流程是 `stageStart` → 本地实际战斗 → `battleEnd`,
|
普通关卡首次通关仍需在游戏内实际战斗。客户端有 `startSaodang` /
|
||||||
结算包含击杀、伤害、剩余时间、阵容等战斗数据,并非只传一个成功标志。
|
`doSaodangBattle` 扫荡分支:普通、非剧情定位关卡的三个难度全部通关后才开放。
|
||||||
当前静态检查未找到独立扫荡接口;本程序的刷图是通过 ADB 在游戏中正常战斗。
|
它复用 `stageStart` → `battleEnd` → `recordBattleResult`,无需本地战斗演算或手机截图。
|
||||||
没有实现脱离手机的完整战斗模拟,也没有伪造胜利记录。
|
此前只搜索英文 sweep 和中文“扫荡”漏掉了这个拼音方法;现已按该分支实现。
|
||||||
|
|
||||||
|
在“地图关卡”展开地区,每关勾选“刷图”、选择难度、输入“本日上限”,再点击“开始扫荡”。
|
||||||
|
星级是服务器通关进度计算出来的,只读。未解锁难度不能选;特殊关卡、未全通关、剧情任务、
|
||||||
|
体力/金币/门票不足的关卡会显示原因并跳过。次数按角色、日期、关卡和难度保存,
|
||||||
|
是本地已开始次数,不冒充服务器每日限制。扫荡和ADB实战不能同时运行。
|
||||||
|
一次扫荡内部的几个请求顺序执行,完成后重读账号状态;开启其他策略时与孵蛋/委托逐轮串行。
|
||||||
|
触发随机事件或请求结果不明确时停止,不提交后续结算;在游戏内处理后可清除本地待处理记录。
|
||||||
|
|
||||||
|
“每日事务”选择要处理的奖励类别,点“领取勾选项目”可立即领取;
|
||||||
|
点“开始每日事务”会打开统一监控和自动执行,只处理符合状态的项目。
|
||||||
|
VIP奖励只对已有资格领取;不会购买VIP或升级礼包。邮件仅领取附件,不删除邮件。
|
||||||
|
启动/重启默认仍只读,自动化需要手动开始。勾选项、战队、保留体力及刷图规则按角色保存。
|
||||||
|
网络写请求发送前保存本地记录,异常不直接重试;本日已提交但服务器仍返回旧状态的奖励会明确提示。
|
||||||
|
|
||||||
|
资料包含此APK的1178个关卡、各难度奖励和2079种道具名称。
|
||||||
|
这些是安装包配置中的可能掉落,并非实时掉落概率保证;后续热更新新增数据需要重新提取。
|
||||||
|
本次签到、领邮件和扫荡均由本地模拟验证,尚未在真实账号上执行验证。
|
||||||
|
静态证据与字段规则见 `analysis/STAGES_DAILY.md`。
|
||||||
|
|||||||
@@ -0,0 +1,290 @@
|
|||||||
|
"""Native Qt pages for stage selection and daily rewards."""
|
||||||
|
from PySide6 import QtCore as C, QtWidgets as W
|
||||||
|
|
||||||
|
from .daily import DailyPolicy, entries
|
||||||
|
from .maps import stages
|
||||||
|
from .native_widgets import IntegerInput
|
||||||
|
from .sweeping import SweepPolicy
|
||||||
|
|
||||||
|
|
||||||
|
def number(value, maximum=9999):
|
||||||
|
widget = IntegerInput()
|
||||||
|
widget.setRange(0, maximum)
|
||||||
|
widget.setValue(value)
|
||||||
|
return widget
|
||||||
|
|
||||||
|
|
||||||
|
class ActivityPages:
|
||||||
|
def maps_tab(self):
|
||||||
|
self.map_rules = {}
|
||||||
|
self.map_page = W.QWidget()
|
||||||
|
layout = W.QVBoxLayout(self.map_page)
|
||||||
|
line = W.QHBoxLayout()
|
||||||
|
self.map_search = W.QLineEdit()
|
||||||
|
self.map_search.setPlaceholderText("搜索关卡编号、名称或掉落物品")
|
||||||
|
self.only_unlocked = W.QCheckBox("只看账号已解锁")
|
||||||
|
self.only_unlocked.setChecked(True)
|
||||||
|
for widget in (self.map_search, self.only_unlocked):
|
||||||
|
line.addWidget(widget)
|
||||||
|
for label, function in (("刷新关卡", self.refresh), ("展开地区", lambda: self.maps_tree.expandAll()),
|
||||||
|
("折叠地区", lambda: self.maps_tree.collapseAll()), ("转到手机实战", self.choose_map)):
|
||||||
|
button = W.QPushButton(label)
|
||||||
|
button.clicked.connect(function)
|
||||||
|
line.addWidget(button)
|
||||||
|
layout.addLayout(line)
|
||||||
|
line = W.QHBoxLayout()
|
||||||
|
self.map_enabled = W.QCheckBox("启用勾选关卡的自动扫荡")
|
||||||
|
self.map_keep_ti = number(0)
|
||||||
|
self.map_team = W.QComboBox()
|
||||||
|
for name in ("teamA", "teamB", "teamC"):
|
||||||
|
self.map_team.addItem(name, name)
|
||||||
|
line.addWidget(self.map_enabled)
|
||||||
|
line.addWidget(W.QLabel("保留体力"))
|
||||||
|
line.addWidget(self.map_keep_ti)
|
||||||
|
line.addWidget(W.QLabel("使用战队"))
|
||||||
|
line.addWidget(self.map_team)
|
||||||
|
start = W.QPushButton("开始扫荡")
|
||||||
|
start.clicked.connect(lambda: self.start_activities("maps"))
|
||||||
|
stop = W.QPushButton("停止扫荡")
|
||||||
|
stop.clicked.connect(lambda: self.map_enabled.setChecked(False))
|
||||||
|
reset = W.QPushButton("处理未完成记录…")
|
||||||
|
reset.clicked.connect(self.clear_sweep_pending)
|
||||||
|
for button in (start, stop, reset):
|
||||||
|
line.addWidget(button)
|
||||||
|
line.addStretch()
|
||||||
|
layout.addLayout(line)
|
||||||
|
self.maps_summary = W.QLabel("登录后读取实际解锁状态")
|
||||||
|
self.maps_summary.setWordWrap(True)
|
||||||
|
layout.addWidget(self.maps_summary)
|
||||||
|
self.maps_tree = W.QTreeWidget()
|
||||||
|
self.maps_tree.setHeaderLabels(["刷图", "关卡", "名称", "难度", "星级", "扫荡状态", "体力 / 门票", "可能掉落", "本日上限", "本日已开始"])
|
||||||
|
self.maps_tree.setAlternatingRowColors(True)
|
||||||
|
self.maps_tree.setUniformRowHeights(False)
|
||||||
|
self.maps_tree.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||||
|
self.maps_tree.itemChanged.connect(self.map_item_changed)
|
||||||
|
for col, width in enumerate((100, 82, 160, 130, 70, 210, 120, 340, 100, 92)):
|
||||||
|
self.maps_tree.setColumnWidth(col, width)
|
||||||
|
layout.addWidget(self.maps_tree, 1)
|
||||||
|
note = W.QLabel("星级来自实际通关难度,不能手动修改。普通关卡三个难度全部通关后可扫荡;每行勾选、选择难度并输入本日次数上限。\n未满足扫荡条件的关卡可“转到手机实战”;扫荡按表格顺序逐关执行,使用所选战队。掉落来自安装包配置,随机物品并非必掉。")
|
||||||
|
note.setWordWrap(True)
|
||||||
|
layout.addWidget(note)
|
||||||
|
self.tabs.addTab(self.map_page, "地图关卡")
|
||||||
|
self.map_search.textChanged.connect(self.render_maps)
|
||||||
|
self.only_unlocked.toggled.connect(self.render_maps)
|
||||||
|
self.map_enabled.toggled.connect(self.activity_settings_changed)
|
||||||
|
self.map_keep_ti.valueChanged.connect(self.activity_settings_changed)
|
||||||
|
self.map_team.currentIndexChanged.connect(self.activity_settings_changed)
|
||||||
|
|
||||||
|
def read_sweep_policy(self):
|
||||||
|
import copy
|
||||||
|
return SweepPolicy(self.map_enabled.isChecked(), copy.deepcopy(self.map_rules), self.map_keep_ti.value(), self.map_team.currentData())
|
||||||
|
|
||||||
|
def activity_settings_changed(self, *args):
|
||||||
|
if self.closed:
|
||||||
|
return
|
||||||
|
# Stop takes effect immediately, even if the current request is in flight.
|
||||||
|
if hasattr(self, "map_enabled") and not self.map_enabled.isChecked():
|
||||||
|
self.engine.sweep_policy.enabled = False
|
||||||
|
if hasattr(self, "daily_enabled") and not self.daily_enabled.isChecked():
|
||||||
|
self.engine.daily_policy.enabled = False
|
||||||
|
if hasattr(self, "default_config"):
|
||||||
|
if not hasattr(self, "activity_save_timer"):
|
||||||
|
self.activity_save_timer = C.QTimer(self)
|
||||||
|
self.activity_save_timer.setSingleShot(True)
|
||||||
|
self.activity_save_timer.timeout.connect(lambda: self.save_config(quiet=True))
|
||||||
|
self.activity_save_timer.start(350)
|
||||||
|
|
||||||
|
def map_item_changed(self, item, column):
|
||||||
|
key = item.data(0, C.Qt.ItemDataRole.UserRole)
|
||||||
|
if key and column == 0:
|
||||||
|
self.map_rule_changed(key, enabled=item.checkState(0) == C.Qt.CheckState.Checked)
|
||||||
|
|
||||||
|
def map_rule_changed(self, key, **changes):
|
||||||
|
self.map_rules[key] = {"enabled": False, "level": "3", "limit": 3} | self.map_rules.get(key, {}) | changes
|
||||||
|
self.activity_settings_changed()
|
||||||
|
if "level" in changes:
|
||||||
|
C.QTimer.singleShot(0, self.render_maps)
|
||||||
|
|
||||||
|
def render_maps(self, *args):
|
||||||
|
if not hasattr(self, "maps_tree") or self.engine.snapshot is None:
|
||||||
|
return
|
||||||
|
focused = W.QApplication.focusWidget()
|
||||||
|
if isinstance(focused, W.QLineEdit) and self.maps_tree.isAncestorOf(focused):
|
||||||
|
return
|
||||||
|
snapshot = self.engine.snapshot
|
||||||
|
all_rows = stages(self.catalog, snapshot)
|
||||||
|
grouped = {}
|
||||||
|
for row in all_rows:
|
||||||
|
grouped.setdefault(row.stage_id, []).append(row)
|
||||||
|
query = self.map_search.text().strip().casefold()
|
||||||
|
expanded = {self.maps_tree.topLevelItem(i).text(0) for i in range(self.maps_tree.topLevelItemCount()) if self.maps_tree.topLevelItem(i).isExpanded()}
|
||||||
|
old = self.maps_tree.currentItem()
|
||||||
|
selected = old.data(0, C.Qt.ItemDataRole.UserRole) if old else None
|
||||||
|
first_render = not self.maps_tree.topLevelItemCount()
|
||||||
|
blocker = C.QSignalBlocker(self.maps_tree)
|
||||||
|
self.maps_tree.clear()
|
||||||
|
cities, shown = {}, 0
|
||||||
|
policy = self.read_sweep_policy()
|
||||||
|
for key, options in sorted(grouped.items(), key=lambda pair: (pair[1][0].city, pair[1][0].number, pair[0])):
|
||||||
|
first = options[0]
|
||||||
|
if self.only_unlocked.isChecked() and not any(s.unlocked for s in options):
|
||||||
|
continue
|
||||||
|
if query and query not in (first.city_name + key + first.number + first.name + " ".join(s.drops for s in options)).casefold():
|
||||||
|
continue
|
||||||
|
shown += 1
|
||||||
|
city = cities.get(first.city)
|
||||||
|
if city is None:
|
||||||
|
city = W.QTreeWidgetItem(self.maps_tree, [first.city_name])
|
||||||
|
city.setFirstColumnSpanned(True)
|
||||||
|
city.setExpanded(first_render or first.city_name in expanded)
|
||||||
|
cities[first.city] = city
|
||||||
|
rule = self.map_rules.get(key, {})
|
||||||
|
chosen = next((s for s in options if s.level == str(rule.get("level"))), None) if rule else None
|
||||||
|
chosen = chosen or next((s for s in reversed(options) if s.unlocked), first)
|
||||||
|
reason = self.engine.sweeper.reason(snapshot, chosen, policy)
|
||||||
|
item = W.QTreeWidgetItem(city, ["", first.number, first.name, "", "★" * first.stars + "☆" * (3 - first.stars),
|
||||||
|
reason or "可扫荡", str(chosen.stamina) + (" / " + chosen.tickets if chosen.tickets else ""), chosen.drops, "", str(self.engine.sweeper.used(snapshot, chosen))])
|
||||||
|
item.setData(0, C.Qt.ItemDataRole.UserRole, key)
|
||||||
|
item.setCheckState(0, C.Qt.CheckState.Checked if rule.get("enabled") else C.Qt.CheckState.Unchecked)
|
||||||
|
if not any(s.unlocked and s.open for s in options):
|
||||||
|
item.setFlags(item.flags() & ~C.Qt.ItemFlag.ItemIsUserCheckable)
|
||||||
|
for col in (5, 6, 7):
|
||||||
|
item.setToolTip(col, item.text(col))
|
||||||
|
difficulty = W.QComboBox()
|
||||||
|
for s in options:
|
||||||
|
difficulty.addItem(f"难度 {s.level}" + ("(已通关)" if s.passed else ""), s.level)
|
||||||
|
difficulty.model().item(difficulty.count() - 1).setEnabled(s.unlocked and s.open)
|
||||||
|
difficulty.setCurrentIndex(difficulty.findData(chosen.level))
|
||||||
|
# Keep displayed defaults and execution defaults identical.
|
||||||
|
self.map_rules.setdefault(key, {"enabled": False, "level": chosen.level, "limit": 3})
|
||||||
|
if not rule.get("enabled"):
|
||||||
|
self.map_rules[key]["level"] = chosen.level
|
||||||
|
difficulty.currentIndexChanged.connect(lambda index, key=key, widget=difficulty: self.map_rule_changed(key, level=widget.currentData()))
|
||||||
|
limit = number(rule.get("limit", 3), 999)
|
||||||
|
limit.valueChanged.connect(lambda value, key=key: self.map_rule_changed(key, limit=value))
|
||||||
|
item.setSizeHint(0, C.QSize(90, max(difficulty.sizeHint().height(), limit.sizeHint().height()) + 4))
|
||||||
|
self.maps_tree.setItemWidget(item, 3, difficulty)
|
||||||
|
self.maps_tree.setItemWidget(item, 8, limit)
|
||||||
|
if key == selected:
|
||||||
|
self.maps_tree.setCurrentItem(item)
|
||||||
|
del blocker
|
||||||
|
pending = self.engine.sweeper.state.get("pending")
|
||||||
|
self.maps_summary.setText(f"已解锁 {sum(s.unlocked for s in all_rows)} 个难度;显示 {shown} 关;勾选 {sum(bool(r.get('enabled')) for r in self.map_rules.values())} 关。" +
|
||||||
|
(f" 待处理:{pending['stage']} / {pending['phase']}" if pending else "") +
|
||||||
|
(" 正在执行扫荡计划。" if self.map_enabled.isChecked() and self.execute.isChecked() and self.monitoring else " 扫荡已停止。"))
|
||||||
|
|
||||||
|
def choose_map(self):
|
||||||
|
item = self.maps_tree.currentItem()
|
||||||
|
key = item.data(0, C.Qt.ItemDataRole.UserRole) if item else None
|
||||||
|
if not key:
|
||||||
|
return
|
||||||
|
level = self.maps_tree.itemWidget(item, 3).currentData()
|
||||||
|
stage = next(s for s in stages(self.catalog, self.engine.snapshot) if s.stage_id == key and s.level == level)
|
||||||
|
if not stage.unlocked or not stage.open:
|
||||||
|
self.report("所选关卡未解锁或当前未开放")
|
||||||
|
return
|
||||||
|
if self.stage.findData(key) < 0:
|
||||||
|
self.stage.addItem(f"{stage.number} {stage.name}", key)
|
||||||
|
self.stage.setCurrentIndex(self.stage.findData(key))
|
||||||
|
self.stage_level.setCurrentIndex(self.stage_level.findData(level))
|
||||||
|
self.tabs.setCurrentWidget(self.screen.parentWidget())
|
||||||
|
self.report("已设置手机实战目标;手机需打开该关卡准备页并配置截图")
|
||||||
|
|
||||||
|
def clear_sweep_pending(self):
|
||||||
|
if self.busy:
|
||||||
|
self.report("请等待当前请求完成")
|
||||||
|
return
|
||||||
|
pending = self.engine.sweeper.state.get("pending")
|
||||||
|
if not pending:
|
||||||
|
self.report("没有未完成的扫荡记录")
|
||||||
|
return
|
||||||
|
if W.QMessageBox.question(self, "清除本地待处理记录", f"{pending['stage']}:{pending['phase']}\n请先在游戏内确认并处理该关卡。确认已处理后清除记录?") == W.QMessageBox.StandardButton.Yes:
|
||||||
|
self.engine.sweeper.state["pending"] = None
|
||||||
|
self.engine.sweeper.save()
|
||||||
|
self.render_maps()
|
||||||
|
|
||||||
|
def daily_tab(self):
|
||||||
|
self.daily_page = W.QWidget()
|
||||||
|
layout = W.QVBoxLayout(self.daily_page)
|
||||||
|
line = W.QHBoxLayout()
|
||||||
|
self.daily_enabled = W.QCheckBox("监控时自动领取勾选奖励")
|
||||||
|
line.addWidget(self.daily_enabled)
|
||||||
|
self.daily_checks = {}
|
||||||
|
for key, label in (("gift", "每日签到礼包"), ("check", "七日签到"), ("loop", "累计奖励"), ("vip", "VIP日奖"), ("mail", "邮件附件")):
|
||||||
|
check = W.QCheckBox(label)
|
||||||
|
check.setChecked(True)
|
||||||
|
check.toggled.connect(self.activity_settings_changed)
|
||||||
|
self.daily_checks[key] = check
|
||||||
|
line.addWidget(check)
|
||||||
|
line.addStretch()
|
||||||
|
layout.addLayout(line)
|
||||||
|
line = W.QHBoxLayout()
|
||||||
|
for label, function in (("刷新状态", self.refresh), ("领取勾选项目", self.claim_daily),
|
||||||
|
("开始每日事务", lambda: self.start_activities("daily")), ("停止每日事务", lambda: self.daily_enabled.setChecked(False))):
|
||||||
|
button = W.QPushButton(label)
|
||||||
|
button.clicked.connect(function)
|
||||||
|
line.addWidget(button)
|
||||||
|
line.addStretch()
|
||||||
|
layout.addLayout(line)
|
||||||
|
self.daily_table = W.QTableWidget(0, 3)
|
||||||
|
self.daily_table.setHorizontalHeaderLabels(["项目 / 邮件", "状态", "奖励 / 附件"])
|
||||||
|
self.daily_table.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||||
|
self.daily_table.setAlternatingRowColors(True)
|
||||||
|
self.daily_table.horizontalHeader().setStretchLastSection(True)
|
||||||
|
self.daily_table.setColumnWidth(0, 280)
|
||||||
|
self.daily_table.setColumnWidth(1, 230)
|
||||||
|
layout.addWidget(self.daily_table, 1)
|
||||||
|
note = W.QLabel("刷新只读取状态。“领取勾选项目”立即处理当前可领奖励;自动领取还需开启监控和“自动执行已启用策略”。邮件仅领取附件。")
|
||||||
|
note.setWordWrap(True)
|
||||||
|
layout.addWidget(note)
|
||||||
|
self.tabs.addTab(self.daily_page, "每日事务")
|
||||||
|
self.daily_enabled.toggled.connect(self.activity_settings_changed)
|
||||||
|
|
||||||
|
def read_daily_policy(self):
|
||||||
|
return DailyPolicy(self.daily_enabled.isChecked(), [key for key, check in self.daily_checks.items() if check.isChecked()])
|
||||||
|
|
||||||
|
def render_daily(self):
|
||||||
|
rows = entries(self.catalog, self.engine.snapshot, self.engine.daily_ledger)
|
||||||
|
self.daily_table.setRowCount(len(rows))
|
||||||
|
for i, row in enumerate(rows):
|
||||||
|
for j, text in enumerate((row.name, row.status, row.reward)):
|
||||||
|
item = W.QTableWidgetItem(text)
|
||||||
|
item.setToolTip(text)
|
||||||
|
self.daily_table.setItem(i, j, item)
|
||||||
|
|
||||||
|
def claim_daily(self):
|
||||||
|
if self.busy:
|
||||||
|
self.report("请等待当前请求完成")
|
||||||
|
return
|
||||||
|
self.stop_workflow()
|
||||||
|
self.engine.daily_policy = self.read_daily_policy()
|
||||||
|
self.submit("daily_claim", self.engine.claim_daily)
|
||||||
|
|
||||||
|
def start_activities(self, page):
|
||||||
|
if page == "maps":
|
||||||
|
if self.engine.demo:
|
||||||
|
self.report("请先登录账号,再开始扫荡")
|
||||||
|
return
|
||||||
|
if self.farm.running:
|
||||||
|
self.report("请先停止手机实战,再开始接口扫荡")
|
||||||
|
return
|
||||||
|
if not any(r.get("enabled") for r in self.map_rules.values()):
|
||||||
|
self.report("请先勾选关卡,并设置难度和本日次数上限")
|
||||||
|
return
|
||||||
|
if not self.busy and self.engine.snapshot and not self.engine.sweeper.next(self.engine.snapshot, self.read_sweep_policy()):
|
||||||
|
self.report("勾选关卡当前均不可扫荡;请查看每行扫荡状态、本日上限和已开始次数")
|
||||||
|
return
|
||||||
|
self.map_enabled.setChecked(True)
|
||||||
|
else:
|
||||||
|
if not any(c.isChecked() for c in self.daily_checks.values()):
|
||||||
|
self.report("请先勾选需要领取的奖励")
|
||||||
|
return
|
||||||
|
self.daily_enabled.setChecked(True)
|
||||||
|
self.save_config(quiet=True)
|
||||||
|
self.start_monitor.setChecked(True)
|
||||||
|
self.execute.setChecked(True)
|
||||||
|
self.next_poll = 0
|
||||||
|
if self.busy:
|
||||||
|
self.pending_execute = True
|
||||||
|
else:
|
||||||
|
self.refresh(automated=True)
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"""Read-only daily status and explicitly selected, free reward claims."""
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .maps import reward_summary
|
||||||
|
from .model import Action, seconds
|
||||||
|
from .quests import CN
|
||||||
|
|
||||||
|
|
||||||
|
def day(now):
|
||||||
|
return datetime.fromtimestamp(now, CN).date().isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
class DailyLedger:
|
||||||
|
def __init__(self, path=None):
|
||||||
|
self.path = Path(path) if path else None
|
||||||
|
self.state = json.loads(self.path.read_text(encoding="utf-8")) if self.path and self.path.exists() else {}
|
||||||
|
|
||||||
|
def seen(self, snapshot, key):
|
||||||
|
return key in self.state.get(f"{snapshot.raw['master']['id']}:{day(snapshot.now)}", [])
|
||||||
|
|
||||||
|
def record(self, snapshot, key):
|
||||||
|
role_day = f"{snapshot.raw['master']['id']}:{day(snapshot.now)}"
|
||||||
|
self.state = {role_day: list(dict.fromkeys(self.state.get(role_day, []) + [key]))}
|
||||||
|
if self.path:
|
||||||
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
temp = self.path.with_suffix(".tmp")
|
||||||
|
temp.write_text(json.dumps(self.state), encoding="utf-8")
|
||||||
|
temp.replace(self.path)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DailyPolicy:
|
||||||
|
enabled: bool = False
|
||||||
|
selected: list[str] = field(default_factory=lambda: ["gift", "check", "loop", "vip", "mail"])
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DailyEntry:
|
||||||
|
key: str
|
||||||
|
name: str
|
||||||
|
status: str
|
||||||
|
reward: str
|
||||||
|
action: Action | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def entries(catalog, snapshot, ledger=None):
|
||||||
|
activity = snapshot.raw.get("activityHistory") or {}
|
||||||
|
table = catalog.data.get("activity_info", {})
|
||||||
|
result = []
|
||||||
|
today = day(snapshot.now)
|
||||||
|
|
||||||
|
def add(key, name, ready, status, reward, path, payload=None):
|
||||||
|
if ready and ledger and ledger.seen(snapshot, key):
|
||||||
|
ready, status = False, "本日已提交,请核对服务器状态"
|
||||||
|
result.append(DailyEntry(key, name, "可领取" if ready else status, reward_summary(catalog, reward),
|
||||||
|
Action(kind="daily", path=path, payload=payload or {}, description="领取" + name) if ready else None))
|
||||||
|
|
||||||
|
gift = activity.get("dailyGift")
|
||||||
|
if isinstance(gift, dict):
|
||||||
|
stamp = seconds(gift.get("dailyGiftCheckTime"))
|
||||||
|
ready = not stamp or day(stamp) < today
|
||||||
|
level = max(1, int(gift.get("dailyGiftLevel") or 1))
|
||||||
|
shown_level = level if ready else 5 if int(gift.get("dailyGiftCount") or 0) > 5 else max(1, level - 1)
|
||||||
|
add("gift", "每日签到礼包", ready, "今日已领取", table.get("dailyGift", {}).get(str(shown_level)), "dailyGiftService/dailyGiftSign")
|
||||||
|
else:
|
||||||
|
add("gift", "每日签到礼包", False, "状态未返回", None, "")
|
||||||
|
|
||||||
|
check = activity.get("dailyCheck")
|
||||||
|
if isinstance(check, dict):
|
||||||
|
count = int(check.get("checkDay") or 0)
|
||||||
|
stamp = seconds(check.get("checkTime"))
|
||||||
|
add("check", f"七日签到(已领{count}/7)", count < 7 and (not stamp or day(stamp) < today),
|
||||||
|
"已全部领取" if count >= 7 else "今日已领取", table.get("dailyCheck", {}).get(str(min(count, 6))), "dailyCheckService/dailyCheck")
|
||||||
|
else:
|
||||||
|
add("check", "七日签到", False, "状态未返回", None, "")
|
||||||
|
|
||||||
|
loop = table.get("loopCheckReward") or {}
|
||||||
|
target = int(loop.get("dayNum") or 0)
|
||||||
|
count = min(int((gift or {}).get("dailyGiftCount") or 0), target)
|
||||||
|
if gift:
|
||||||
|
stamp, previous = seconds(gift.get("dailyGiftCheckTime")), seconds(gift.get("dailyRewardGetTime"))
|
||||||
|
count = max(0, min(count, (datetime.fromtimestamp(stamp, CN).date() - datetime.fromtimestamp(previous, CN).date()).days))
|
||||||
|
add("loop", "累计签到奖励", bool(gift and loop.get("open") and target and count >= target),
|
||||||
|
f"累计 {count}/{target} 天" if loop.get("open") else "活动未开放", loop.get("reward"), "dailyGiftService/dailyLoopReward")
|
||||||
|
|
||||||
|
vip = activity.get("vipInfo") or {}
|
||||||
|
expiry = seconds(vip.get("vipTime"))
|
||||||
|
stamp = seconds(vip.get("getTime"))
|
||||||
|
active = expiry > snapshot.now and day(expiry) > today
|
||||||
|
add("vip", "VIP每日奖励", active and (not stamp or day(stamp) < today), "今日已领取" if active else "无有效VIP资格",
|
||||||
|
catalog.data["game_setting"].get("vipReward"), "vipService/getReward")
|
||||||
|
|
||||||
|
for mail in snapshot.raw.get("mails") or []:
|
||||||
|
mid = int(mail["id"])
|
||||||
|
reward = reward_summary(catalog, mail.get("reward"))
|
||||||
|
# MailVo.overday: normal mail lasts seven calendar days.
|
||||||
|
stamp = seconds(mail.get("createTime"))
|
||||||
|
expired = bool(stamp and (datetime.fromtimestamp(snapshot.now, CN).date() - datetime.fromtimestamp(stamp, CN).date()).days >= 7)
|
||||||
|
claimed = mail.get("isGetReward") in (1, True, "1")
|
||||||
|
key = f"mail:{mid}"
|
||||||
|
add(key, "邮件:" + str(mail.get("title") or mid), bool(reward and reward != "附件格式未知" and not claimed and not expired),
|
||||||
|
"已过期" if expired else "已领取" if claimed else "无附件" if not reward else "附件格式未知", mail.get("reward"), "mailService/mailGetReward", {"mailId": mid})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def selected_entries(catalog, snapshot, policy, ledger):
|
||||||
|
return [row for row in entries(catalog, snapshot, ledger) if row.action and
|
||||||
|
(row.key in policy.selected or row.key.startswith("mail:") and "mail" in policy.selected)]
|
||||||
File diff suppressed because one or more lines are too long
@@ -3,7 +3,9 @@ from dataclasses import replace
|
|||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import time
|
import time
|
||||||
from .model import Catalog, Planner, Policy, Snapshot, seconds
|
from .model import Action, Catalog, Planner, Policy, Snapshot, seconds
|
||||||
|
from .daily import DailyLedger, DailyPolicy, selected_entries
|
||||||
|
from .sweeping import SweepPolicy, SweepRunner
|
||||||
from .quests import QuestPolicy, TaskPlanner
|
from .quests import QuestPolicy, TaskPlanner
|
||||||
from .market import PurchaseBudget
|
from .market import PurchaseBudget
|
||||||
from .management import expansion_quote, manual_monster_actions
|
from .management import expansion_quote, manual_monster_actions
|
||||||
@@ -25,6 +27,11 @@ class Engine:
|
|||||||
self.last_draw = ""
|
self.last_draw = ""
|
||||||
self.growth_cache = {}
|
self.growth_cache = {}
|
||||||
self.growth_attempts = {}
|
self.growth_attempts = {}
|
||||||
|
folder = Path(budget_path).parent if budget_path else None
|
||||||
|
self.daily_policy = DailyPolicy()
|
||||||
|
self.daily_ledger = DailyLedger(folder / "daily_claims.json" if folder else None)
|
||||||
|
self.sweep_policy = SweepPolicy()
|
||||||
|
self.sweeper = SweepRunner(catalog, folder / "sweep_runs.json" if folder else None)
|
||||||
|
|
||||||
def read_snapshot(self):
|
def read_snapshot(self):
|
||||||
self.snapshot = self.client.snapshot()
|
self.snapshot = self.client.snapshot()
|
||||||
@@ -136,6 +143,17 @@ class Engine:
|
|||||||
return self.snapshot, [], "状态已读取;策略暂不可用:" + str(error)
|
return self.snapshot, [], "状态已读取;策略暂不可用:" + str(error)
|
||||||
if self.auto and plans:
|
if self.auto and plans:
|
||||||
action = plans[0]
|
action = plans[0]
|
||||||
|
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)
|
||||||
|
self.claim_daily_entry(entry)
|
||||||
|
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + action.description
|
||||||
|
if action.kind == "sweep":
|
||||||
|
stage = self.sweeper.next(self.snapshot, self.sweep_policy)
|
||||||
|
if self.demo:
|
||||||
|
return self.snapshot, plans, "扫荡需要登录真实账号;演示不会提交战斗"
|
||||||
|
self.sweeper.run(self.client, self.snapshot, stage, self.sweep_policy)
|
||||||
|
self.read_snapshot()
|
||||||
|
return self.snapshot, self.plans(), f"扫荡完成:{stage.number} {stage.name} / 难度{stage.level}"
|
||||||
if action.kind == "buy":
|
if action.kind == "buy":
|
||||||
price = int(self.catalog.data["markets"][action.payload["id"]]["money"])
|
price = int(self.catalog.data["markets"][action.payload["id"]]["money"])
|
||||||
self.purchase_budget.record(self.snapshot.now, price * action.payload["num"], self.policy.daily_buy_money)
|
self.purchase_budget.record(self.snapshot.now, price * action.payload["num"], self.policy.daily_buy_money)
|
||||||
@@ -167,7 +185,30 @@ class Engine:
|
|||||||
reserved[key] = max(reserved.get(key, 0), count)
|
reserved[key] = max(reserved.get(key, 0), count)
|
||||||
policy = replace(self.policy, reserved_types=list(set(self.policy.reserved_types) | types), reserved_eggs=reserved)
|
policy = replace(self.policy, reserved_types=list(set(self.policy.reserved_types) | types), reserved_eggs=reserved)
|
||||||
left = self.purchase_budget.remaining(self.snapshot.now, policy.daily_buy_money)
|
left = self.purchase_budget.remaining(self.snapshot.now, policy.daily_buy_money)
|
||||||
return quests + self.planner.plan(self.snapshot, policy, left)
|
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
|
||||||
|
sweep_actions = [Action(kind="sweep", path="", payload={}, description=f"扫荡 {sweep.number} {sweep.name} / 难度{sweep.level}")] if sweep else []
|
||||||
|
return daily + quests + self.planner.plan(self.snapshot, policy, left) + sweep_actions
|
||||||
|
|
||||||
|
def claim_daily_entry(self, entry):
|
||||||
|
self.daily_ledger.record(self.snapshot, entry.key)
|
||||||
|
if not self.demo:
|
||||||
|
self.client.call(entry.action.path, entry.action.payload)
|
||||||
|
self.read_snapshot()
|
||||||
|
|
||||||
|
def claim_daily(self):
|
||||||
|
self.auto = False
|
||||||
|
if not self.demo:
|
||||||
|
self.read_snapshot()
|
||||||
|
# Fresh status after every claim, bounded by the initially available IDs.
|
||||||
|
keys = [row.key for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)]
|
||||||
|
done = 0
|
||||||
|
for key in keys:
|
||||||
|
row = next((r for r in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger) if r.key == key), None)
|
||||||
|
if row:
|
||||||
|
self.claim_daily_entry(row)
|
||||||
|
done += 1
|
||||||
|
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + f"已处理 {done} 项勾选奖励;自动执行已暂停"
|
||||||
|
|
||||||
def record_draw(self, eggs):
|
def record_draw(self, eggs):
|
||||||
totals = {}
|
totals = {}
|
||||||
|
|||||||
+50
-65
@@ -18,7 +18,9 @@ from .management import expansion_quote, manual_monster_actions
|
|||||||
from .native_widgets import IntegerInput, use_native_scrollbars
|
from .native_widgets import IntegerInput, use_native_scrollbars
|
||||||
from .login import PasswordLogin, device_id, server_labels
|
from .login import PasswordLogin, device_id, server_labels
|
||||||
from .quests import QuestPolicy
|
from .quests import QuestPolicy
|
||||||
from .maps import stages
|
from .daily import DailyPolicy
|
||||||
|
from .sweeping import SweepPolicy
|
||||||
|
from .activity_gui import ActivityPages
|
||||||
from .capture import PAGES, load_buttons, read_profile, saved_profiles, save_page
|
from .capture import PAGES, load_buttons, read_profile, saved_profiles, save_page
|
||||||
from .credentials import CredentialStore
|
from .credentials import CredentialStore
|
||||||
from .debug import TraceLog
|
from .debug import TraceLog
|
||||||
@@ -154,7 +156,7 @@ def fill_table(widget, rows, sorting=True):
|
|||||||
widget.setSortingEnabled(sorting)
|
widget.setSortingEnabled(sorting)
|
||||||
|
|
||||||
|
|
||||||
class Window(W.QMainWindow):
|
class Window(ActivityPages, W.QMainWindow):
|
||||||
network_event = C.Signal(object)
|
network_event = C.Signal(object)
|
||||||
profile_changed = C.Signal(str)
|
profile_changed = C.Signal(str)
|
||||||
|
|
||||||
@@ -307,6 +309,7 @@ class Window(W.QMainWindow):
|
|||||||
self.yield_tab()
|
self.yield_tab()
|
||||||
self.quests_tab()
|
self.quests_tab()
|
||||||
self.maps_tab()
|
self.maps_tab()
|
||||||
|
self.daily_tab()
|
||||||
self.farm_tab()
|
self.farm_tab()
|
||||||
self.capture_tab()
|
self.capture_tab()
|
||||||
self.plans = table(["操作", "下一步计划(每轮只执行一项,并重新读取状态)"])
|
self.plans = table(["操作", "下一步计划(每轮只执行一项,并重新读取状态)"])
|
||||||
@@ -548,11 +551,12 @@ class Window(W.QMainWindow):
|
|||||||
def start_workflow(self):
|
def start_workflow(self):
|
||||||
try:
|
try:
|
||||||
policy = self.read_policy()
|
policy = self.read_policy()
|
||||||
if not (policy.enabled and any((policy.buy, policy.fill, policy.dispatch, policy.collect, policy.feed))) and not self.quest_enabled.isChecked():
|
other = self.quest_enabled.isChecked() or self.daily_enabled.isChecked() or self.map_enabled.isChecked()
|
||||||
|
if not (policy.enabled and any((policy.buy, policy.fill, policy.dispatch, policy.collect, policy.feed))) and not other:
|
||||||
self.report("请先勾选至少一项功能,并启用对应策略")
|
self.report("请先勾选至少一项功能,并启用对应策略")
|
||||||
return
|
return
|
||||||
self.read_quest_policy()
|
self.read_quest_policy()
|
||||||
if policy.enabled and not any(rule["enabled"] for rule in policy.egg_rules.values()) and not self.quest_enabled.isChecked():
|
if policy.enabled and not any(rule["enabled"] for rule in policy.egg_rules.values()) and not other:
|
||||||
self.report("请先在“背包魔物蛋”勾选要孵化的蛋,并设置优先级和孵出后的去向")
|
self.report("请先在“背包魔物蛋”勾选要孵化的蛋,并设置优先级和孵出后的去向")
|
||||||
self.tabs.setCurrentWidget(self.egg_page)
|
self.tabs.setCurrentWidget(self.egg_page)
|
||||||
return
|
return
|
||||||
@@ -588,6 +592,8 @@ class Window(W.QMainWindow):
|
|||||||
try:
|
try:
|
||||||
self.engine.policy = self.read_policy()
|
self.engine.policy = self.read_policy()
|
||||||
self.engine.quest_policy = self.read_quest_policy()
|
self.engine.quest_policy = self.read_quest_policy()
|
||||||
|
self.engine.daily_policy = self.read_daily_policy()
|
||||||
|
self.engine.sweep_policy = self.read_sweep_policy()
|
||||||
except ValueError:
|
except ValueError:
|
||||||
self.report("请先修正孵蛋规则中的编号和保留数量")
|
self.report("请先修正孵蛋规则中的编号和保留数量")
|
||||||
return
|
return
|
||||||
@@ -722,58 +728,6 @@ class Window(W.QMainWindow):
|
|||||||
layout.addWidget(self.quests_table)
|
layout.addWidget(self.quests_table)
|
||||||
self.tabs.addTab(tab, "自动委托")
|
self.tabs.addTab(tab, "自动委托")
|
||||||
|
|
||||||
def maps_tab(self):
|
|
||||||
tab, layout = W.QWidget(), W.QVBoxLayout()
|
|
||||||
tab.setLayout(layout)
|
|
||||||
line = W.QHBoxLayout()
|
|
||||||
self.map_search = W.QLineEdit()
|
|
||||||
self.map_search.setPlaceholderText("地图名称或关卡编号")
|
|
||||||
self.map_search.textChanged.connect(self.render_maps)
|
|
||||||
self.only_unlocked = W.QCheckBox("只看账号已解锁")
|
|
||||||
self.only_unlocked.setChecked(True)
|
|
||||||
self.only_unlocked.toggled.connect(self.render_maps)
|
|
||||||
choose = W.QPushButton("设为自动战斗目标")
|
|
||||||
choose.clicked.connect(self.choose_map)
|
|
||||||
line.addWidget(self.map_search)
|
|
||||||
line.addWidget(self.only_unlocked)
|
|
||||||
line.addWidget(choose)
|
|
||||||
layout.addLayout(line)
|
|
||||||
self.maps_summary = W.QLabel("登录后显示账号实际解锁状态")
|
|
||||||
layout.addWidget(self.maps_summary)
|
|
||||||
self.maps_table = table(["城市", "关卡编号", "名称", "难度", "已解锁", "已通关", "当前开放", "体力", "入场道具"])
|
|
||||||
layout.addWidget(self.maps_table)
|
|
||||||
note = W.QLabel("当前客户端未发现独立扫荡接口。此处可查看关卡和设置正常自动战斗目标;纯接口即时结算尚未实现。")
|
|
||||||
note.setWordWrap(True)
|
|
||||||
layout.addWidget(note)
|
|
||||||
self.tabs.addTab(tab, "地图关卡")
|
|
||||||
|
|
||||||
def render_maps(self, *args):
|
|
||||||
if not hasattr(self, "maps_table") or self.engine.snapshot is None:
|
|
||||||
return
|
|
||||||
all_rows = stages(self.catalog, self.engine.snapshot)
|
|
||||||
query = self.map_search.text().strip()
|
|
||||||
visible = [s for s in all_rows if (not self.only_unlocked.isChecked() or s.unlocked) and (not query or query in s.name or query in s.stage_id)]
|
|
||||||
fill_table(self.maps_table, [[s.city, s.stage_id, s.name, int(s.level), "是" if s.unlocked else "否", "是" if s.passed else "否", "是" if s.open else "否", s.stamina, s.tickets] for s in visible])
|
|
||||||
self.maps_summary.setText(f"账号已解锁 {sum(s.unlocked for s in all_rows)} 个关卡难度;当前显示 {len(visible)} 项")
|
|
||||||
|
|
||||||
def choose_map(self):
|
|
||||||
row = self.maps_table.currentRow()
|
|
||||||
if row < 0:
|
|
||||||
return
|
|
||||||
stage_id = self.maps_table.item(row, 1).text()
|
|
||||||
level = self.maps_table.item(row, 3).text()
|
|
||||||
if self.maps_table.item(row, 4).text() != "是" or self.maps_table.item(row, 6).text() != "是":
|
|
||||||
self.report("所选关卡未解锁或当前未开放")
|
|
||||||
return
|
|
||||||
index = self.stage.findData(stage_id)
|
|
||||||
if index < 0:
|
|
||||||
self.stage.addItem(self.maps_table.item(row, 2).text() + " " + stage_id, stage_id)
|
|
||||||
index = self.stage.count() - 1
|
|
||||||
self.stage.setCurrentIndex(index)
|
|
||||||
self.stage_level.setCurrentIndex(self.stage_level.findData(level))
|
|
||||||
self.tabs.setCurrentWidget(self.screen.parentWidget())
|
|
||||||
self.report("已设置自动战斗目标;手机需打开相应关卡准备页")
|
|
||||||
|
|
||||||
def farm_tab(self):
|
def farm_tab(self):
|
||||||
tab, horizontal = W.QWidget(), W.QHBoxLayout()
|
tab, horizontal = W.QWidget(), W.QHBoxLayout()
|
||||||
tab.setLayout(horizontal)
|
tab.setLayout(horizontal)
|
||||||
@@ -794,8 +748,8 @@ class Window(W.QMainWindow):
|
|||||||
self.template = combo([("进入关卡按钮(必需)", "entry"), ("胜利结算按钮(必需)", "victory"),
|
self.template = combo([("进入关卡按钮(必需)", "entry"), ("胜利结算按钮(必需)", "victory"),
|
||||||
("关卡名称区域(必需,仅识别)", "stage"), ("触摸开始倒计时", "countdown"), ("自动战斗未开启图标", "auto_off"), ("结算下一步按钮", "continue"), ("失败标识(只检测不点击)", "defeat")])
|
("关卡名称区域(必需,仅识别)", "stage"), ("触摸开始倒计时", "countdown"), ("自动战斗未开启图标", "auto_off"), ("结算下一步按钮", "continue"), ("失败标识(只检测不点击)", "defeat")])
|
||||||
form.addRow("框选的按钮类型", self.template)
|
form.addRow("框选的按钮类型", self.template)
|
||||||
guide = W.QPushButton("打开页面截图配置(推荐,无需框选)")
|
guide = W.QPushButton("打开ADB实战截图配置(扫荡无需截图)")
|
||||||
guide.clicked.connect(lambda: self.tabs.setCurrentWidget(self.capture_rows.parentWidget()))
|
guide.clicked.connect(lambda: self.tabs.setCurrentWidget(self.capture_scroll))
|
||||||
form.addRow(guide)
|
form.addRow(guide)
|
||||||
capture = W.QPushButton("手工标定(可选):截图并在右侧框选")
|
capture = W.QPushButton("手工标定(可选):截图并在右侧框选")
|
||||||
capture.clicked.connect(self.capture)
|
capture.clicked.connect(self.capture)
|
||||||
@@ -820,7 +774,13 @@ class Window(W.QMainWindow):
|
|||||||
def capture_tab(self):
|
def capture_tab(self):
|
||||||
tab, layout = W.QWidget(), W.QVBoxLayout()
|
tab, layout = W.QWidget(), W.QVBoxLayout()
|
||||||
tab.setLayout(layout)
|
tab.setLayout(layout)
|
||||||
note = W.QLabel("按下列页面截图即可,不需要手工框选。先在“体力刷图”选择设备、关卡和难度。\n你玩到对应页面时点击该行截图;截图过程中不会自动点击或切换手机页面。")
|
self.capture_page_widget = tab
|
||||||
|
scroll = W.QScrollArea()
|
||||||
|
scroll.setWidgetResizable(True)
|
||||||
|
scroll.setWidget(tab)
|
||||||
|
self.capture_scroll = scroll
|
||||||
|
layout.setSizeConstraint(W.QLayout.SizeConstraint.SetMinimumSize)
|
||||||
|
note = W.QLabel("此页仅用于ADB手机实战;地图接口扫荡和每日事务不需要截图。\n先在“体力刷图”选择设备、关卡和难度。你玩到对应页面时点击该行截图,无需手工框选;截图不会自动点击或切换手机页面。")
|
||||||
note.setWordWrap(True)
|
note.setWordWrap(True)
|
||||||
layout.addWidget(note)
|
layout.addWidget(note)
|
||||||
self.capture_target = W.QLabel()
|
self.capture_target = W.QLabel()
|
||||||
@@ -830,8 +790,7 @@ class Window(W.QMainWindow):
|
|||||||
self.capture_profiles.currentIndexChanged.connect(self.select_capture_profile)
|
self.capture_profiles.currentIndexChanged.connect(self.select_capture_profile)
|
||||||
layout.addWidget(self.capture_profiles)
|
layout.addWidget(self.capture_profiles)
|
||||||
self.capture_rows = W.QTableWidget(len(PAGES), 4)
|
self.capture_rows = W.QTableWidget(len(PAGES), 4)
|
||||||
self.capture_rows.setMinimumHeight(200)
|
self.capture_rows.verticalHeader().setDefaultSectionSize(max(28, self.fontMetrics().height() + 12))
|
||||||
self.capture_rows.verticalHeader().setDefaultSectionSize(22)
|
|
||||||
self.capture_rows.setHorizontalHeaderLabels(["页面", "截图需要包含", "操作", "状态"])
|
self.capture_rows.setHorizontalHeaderLabels(["页面", "截图需要包含", "操作", "状态"])
|
||||||
self.capture_rows.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
|
self.capture_rows.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||||
self.capture_rows.cellClicked.connect(self.preview_capture)
|
self.capture_rows.cellClicked.connect(self.preview_capture)
|
||||||
@@ -844,6 +803,9 @@ class Window(W.QMainWindow):
|
|||||||
button.clicked.connect(lambda checked=False, page=key: self.capture_page(page))
|
button.clicked.connect(lambda checked=False, page=key: self.capture_page(page))
|
||||||
self.capture_rows.setCellWidget(index, 2, button)
|
self.capture_rows.setCellWidget(index, 2, button)
|
||||||
self.capture_rows.setItem(index, 3, W.QTableWidgetItem("未截图"))
|
self.capture_rows.setItem(index, 3, W.QTableWidgetItem("未截图"))
|
||||||
|
self.capture_rows.setRowHeight(index, max(28, button.sizeHint().height() + 4))
|
||||||
|
height = self.capture_rows.horizontalHeader().sizeHint().height() + sum(self.capture_rows.rowHeight(i) for i in range(len(PAGES))) + 30
|
||||||
|
self.capture_rows.setFixedHeight(height)
|
||||||
layout.addWidget(self.capture_rows)
|
layout.addWidget(self.capture_rows)
|
||||||
line = W.QHBoxLayout()
|
line = W.QHBoxLayout()
|
||||||
refresh = W.QPushButton("检查已保存截图")
|
refresh = W.QPushButton("检查已保存截图")
|
||||||
@@ -862,7 +824,8 @@ class Window(W.QMainWindow):
|
|||||||
self.capture_preview = Screen(selectable=False)
|
self.capture_preview = Screen(selectable=False)
|
||||||
self.capture_preview.setMinimumHeight(140)
|
self.capture_preview.setMinimumHeight(140)
|
||||||
layout.addWidget(self.capture_preview, 1)
|
layout.addWidget(self.capture_preview, 1)
|
||||||
self.tabs.addTab(tab, "页面截图配置")
|
self.tabs.addTab(scroll, "页面截图配置")
|
||||||
|
self.tabs.setTabToolTip(self.tabs.indexOf(scroll), "仅用于ADB手机实战;接口扫荡和每日事务无需截图")
|
||||||
self.stage.currentIndexChanged.connect(self.refresh_capture_profiles)
|
self.stage.currentIndexChanged.connect(self.refresh_capture_profiles)
|
||||||
self.stage_level.currentIndexChanged.connect(self.refresh_capture_profiles)
|
self.stage_level.currentIndexChanged.connect(self.refresh_capture_profiles)
|
||||||
self.serial.editingFinished.connect(self.refresh_capture_profiles)
|
self.serial.editingFinished.connect(self.refresh_capture_profiles)
|
||||||
@@ -1160,7 +1123,7 @@ class Window(W.QMainWindow):
|
|||||||
if tab is self.yields.parentWidget():
|
if tab is self.yields.parentWidget():
|
||||||
self.render_catalog()
|
self.render_catalog()
|
||||||
self.report("收益资料已从本地表刷新")
|
self.report("收益资料已从本地表刷新")
|
||||||
elif tab is self.capture_rows.parentWidget():
|
elif tab is self.capture_scroll:
|
||||||
self.refresh_capture_profiles()
|
self.refresh_capture_profiles()
|
||||||
else:
|
else:
|
||||||
self.refresh()
|
self.refresh()
|
||||||
@@ -1270,7 +1233,7 @@ class Window(W.QMainWindow):
|
|||||||
self.error("显示数据时出错:" + str(error))
|
self.error("显示数据时出错:" + str(error))
|
||||||
|
|
||||||
def apply_result(self, kind, value):
|
def apply_result(self, kind, value):
|
||||||
if kind in ("poll", "monster_lock", "manual_monsters", "expansion", "growth_sync"):
|
if kind in ("poll", "monster_lock", "manual_monsters", "expansion", "growth_sync", "daily_claim"):
|
||||||
snapshot, plans, message = value
|
snapshot, plans, message = value
|
||||||
self.render(snapshot, plans)
|
self.render(snapshot, plans)
|
||||||
self.report(message)
|
self.report(message)
|
||||||
@@ -1333,6 +1296,8 @@ class Window(W.QMainWindow):
|
|||||||
try:
|
try:
|
||||||
self.engine.policy = self.read_policy()
|
self.engine.policy = self.read_policy()
|
||||||
self.engine.quest_policy = self.read_quest_policy()
|
self.engine.quest_policy = self.read_quest_policy()
|
||||||
|
self.engine.daily_policy = self.read_daily_policy()
|
||||||
|
self.engine.sweep_policy = self.read_sweep_policy()
|
||||||
fill_table(self.plans, [[action.kind, action.description] for action in self.engine.plans()])
|
fill_table(self.plans, [[action.kind, action.description] for action in self.engine.plans()])
|
||||||
except (ValueError, TypeError, KeyError, AttributeError) as error:
|
except (ValueError, TypeError, KeyError, AttributeError) as error:
|
||||||
self.report("状态已显示;策略暂不可用:" + str(error))
|
self.report("状态已显示;策略暂不可用:" + str(error))
|
||||||
@@ -1423,6 +1388,8 @@ class Window(W.QMainWindow):
|
|||||||
try:
|
try:
|
||||||
self.engine.policy = self.read_policy()
|
self.engine.policy = self.read_policy()
|
||||||
self.engine.quest_policy = self.read_quest_policy()
|
self.engine.quest_policy = self.read_quest_policy()
|
||||||
|
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.engine.auto = self.execute.isChecked() and automated and self.monitoring
|
||||||
self.next_poll = time.monotonic() + self.interval.currentData()
|
self.next_poll = time.monotonic() + self.interval.currentData()
|
||||||
self.submit("poll", self.engine.poll)
|
self.submit("poll", self.engine.poll)
|
||||||
@@ -1534,6 +1501,7 @@ class Window(W.QMainWindow):
|
|||||||
self.catalog.data["task_info"][key].get("reward", {}).get("money", 0),
|
self.catalog.data["task_info"][key].get("reward", {}).get("money", 0),
|
||||||
self.catalog.data["task_info"][key].get("reward", {}).get("ke", 0), text] for key, name, status, text, _ in quest_rows])
|
self.catalog.data["task_info"][key].get("reward", {}).get("ke", 0), text] for key, name, status, text, _ in quest_rows])
|
||||||
self.render_maps()
|
self.render_maps()
|
||||||
|
self.render_daily()
|
||||||
except (ValueError, TypeError, KeyError, AttributeError) as error:
|
except (ValueError, TypeError, KeyError, AttributeError) as error:
|
||||||
self.report("基础数据已显示;委托或地图暂不可用:" + str(error))
|
self.report("基础数据已显示;委托或地图暂不可用:" + str(error))
|
||||||
left = snapshot.raw.get("history", {}).get("loopTaskNum", "未知")
|
left = snapshot.raw.get("history", {}).get("loopTaskNum", "未知")
|
||||||
@@ -1732,6 +1700,10 @@ class Window(W.QMainWindow):
|
|||||||
self.farm.stop()
|
self.farm.stop()
|
||||||
self.start_farm.setText("开始布丁牧场刷图")
|
self.start_farm.setText("开始布丁牧场刷图")
|
||||||
return
|
return
|
||||||
|
if self.map_enabled.isChecked() and self.execute.isChecked():
|
||||||
|
self.start_farm.setChecked(False)
|
||||||
|
self.report("请先停止地图页的接口扫荡,再开始手机实战")
|
||||||
|
return
|
||||||
if self.busy or self.engine.demo or self.engine.snapshot is None:
|
if self.busy or self.engine.demo or self.engine.snapshot is None:
|
||||||
self.start_farm.setChecked(False)
|
self.start_farm.setChecked(False)
|
||||||
self.report("请先连接真实手机会话,等待刷新完成后再开始刷图")
|
self.report("请先连接真实手机会话,等待刷新完成后再开始刷图")
|
||||||
@@ -1757,7 +1729,9 @@ class Window(W.QMainWindow):
|
|||||||
|
|
||||||
def config_value(self):
|
def config_value(self):
|
||||||
self.update_farm_config()
|
self.update_farm_config()
|
||||||
return {"policy": asdict(self.read_policy()), "quest_policy": asdict(self.read_quest_policy()), "farm": asdict(self.farm.config), "overrides": copy.deepcopy(self.catalog.overrides),
|
return {"policy": asdict(self.read_policy()), "quest_policy": asdict(self.read_quest_policy()),
|
||||||
|
"daily_policy": asdict(self.read_daily_policy()), "sweep_policy": asdict(self.read_sweep_policy()),
|
||||||
|
"farm": asdict(self.farm.config), "overrides": copy.deepcopy(self.catalog.overrides),
|
||||||
"log_visible": self.show_log.isChecked(), "log_sizes": self.log_splitter.sizes() if self.show_log.isChecked() else self.log_sizes,
|
"log_visible": self.show_log.isChecked(), "log_sizes": self.log_splitter.sizes() if self.show_log.isChecked() else self.log_sizes,
|
||||||
"yield_stars": [star for star, check in self.yield_stars.items() if check.isChecked()],
|
"yield_stars": [star for star, check in self.yield_stars.items() if check.isChecked()],
|
||||||
"adb_path": self.adb_path.text(), "serial": self.serial.text().strip(), "interval": self.interval.currentData(),
|
"adb_path": self.adb_path.text(), "serial": self.serial.text().strip(), "interval": self.interval.currentData(),
|
||||||
@@ -1792,6 +1766,15 @@ class Window(W.QMainWindow):
|
|||||||
self.log.setVisible(self.show_log.isChecked())
|
self.log.setVisible(self.show_log.isChecked())
|
||||||
self.show_log.setText("隐藏日志" if self.show_log.isChecked() else "显示日志")
|
self.show_log.setText("隐藏日志" if self.show_log.isChecked() else "显示日志")
|
||||||
policy = Policy(**value.get("policy", {}))
|
policy = Policy(**value.get("policy", {}))
|
||||||
|
daily = DailyPolicy(**value.get("daily_policy", {}))
|
||||||
|
self.daily_enabled.setChecked(daily.enabled)
|
||||||
|
for key, check in self.daily_checks.items():
|
||||||
|
check.setChecked(key in daily.selected)
|
||||||
|
sweep = SweepPolicy(**value.get("sweep_policy", {}))
|
||||||
|
self.map_rules = copy.deepcopy(sweep.rules)
|
||||||
|
self.map_enabled.setChecked(sweep.enabled)
|
||||||
|
self.map_keep_ti.setValue(sweep.keep_stamina)
|
||||||
|
self.map_team.setCurrentIndex(max(0, self.map_team.findData(sweep.team)))
|
||||||
self.egg_rules = copy.deepcopy(policy.egg_rules)
|
self.egg_rules = copy.deepcopy(policy.egg_rules)
|
||||||
self.feed_targets = copy.deepcopy(policy.feed_targets)
|
self.feed_targets = copy.deepcopy(policy.feed_targets)
|
||||||
for widget, data in ((self.strategy, policy.strategy), (self.protect_quality, policy.protect_quality), (self.egg_order, policy.egg_order), (self.interval, value.get("interval", 10)),
|
for widget, data in ((self.strategy, policy.strategy), (self.protect_quality, policy.protect_quality), (self.egg_order, policy.egg_order), (self.interval, value.get("interval", 10)),
|
||||||
@@ -1846,6 +1829,8 @@ class Window(W.QMainWindow):
|
|||||||
def closeEvent(self, event):
|
def closeEvent(self, event):
|
||||||
self.closed = True
|
self.closed = True
|
||||||
self.timer.stop()
|
self.timer.stop()
|
||||||
|
if hasattr(self, "activity_save_timer"):
|
||||||
|
self.activity_save_timer.stop()
|
||||||
self.pending_refresh = None
|
self.pending_refresh = None
|
||||||
self.engine.auto = False
|
self.engine.auto = False
|
||||||
self.monitoring = False
|
self.monitoring = False
|
||||||
|
|||||||
+58
-7
@@ -1,5 +1,40 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from .quests import condition_ok, indexed
|
import json
|
||||||
|
from .quests import condition_ok, stage_has_level
|
||||||
|
|
||||||
|
|
||||||
|
def reward_summary(catalog, reward):
|
||||||
|
"""List configured possible rewards without rolling the random pool."""
|
||||||
|
if isinstance(reward, str):
|
||||||
|
try:
|
||||||
|
reward = json.loads(reward)
|
||||||
|
except ValueError:
|
||||||
|
return "附件格式未知"
|
||||||
|
if not isinstance(reward, dict):
|
||||||
|
return ""
|
||||||
|
parts = [f"{label} {reward[key]}" for key, label in (("money", "金币"), ("ke", "氪金"), ("ti", "体力"), ("exp", "经验")) if reward.get(key)]
|
||||||
|
names = catalog.data.get("item_names", {})
|
||||||
|
for piece in reward.get("rewards") or []:
|
||||||
|
if not isinstance(piece, dict):
|
||||||
|
continue
|
||||||
|
if piece.get("num", 0) > 0 and float(piece.get("chance", 1)) > 0:
|
||||||
|
for mon in piece.get("monsters") or []:
|
||||||
|
key = str(mon["name"])
|
||||||
|
parts.append(catalog.monster(key).get("name", key) + ("蛋" if not piece.get("monMode") else ""))
|
||||||
|
if piece.get("item_num", 0) > 0 and float(piece.get("item_chance", 1)) > 0:
|
||||||
|
for item in piece.get("items") or []:
|
||||||
|
values = str(item["name"]).split(",")
|
||||||
|
count = ""
|
||||||
|
if len(values) >= 3:
|
||||||
|
count = " ×" + (values[1] if values[1] == values[2] else values[1] + "~" + values[2])
|
||||||
|
parts.append(names.get(values[0], values[0]) + count)
|
||||||
|
for item in reward.get("items") or []:
|
||||||
|
key = str(item.get("type", item.get("typeId", "?")))
|
||||||
|
parts.append(f"{names.get(key, key)} ×{item.get('num', 1)}")
|
||||||
|
for mon in reward.get("mons") or []:
|
||||||
|
key = str(mon.get("type", "?"))
|
||||||
|
parts.append(f"{catalog.monster(key).get('name', key)}{'蛋' if not mon.get('mode') else ''} ×{mon.get('num', 1)}")
|
||||||
|
return ";".join(dict.fromkeys(parts))
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -13,19 +48,35 @@ class Stage:
|
|||||||
open: bool
|
open: bool
|
||||||
stamina: int
|
stamina: int
|
||||||
tickets: str
|
tickets: str
|
||||||
|
number: str = ""
|
||||||
|
city_name: str = ""
|
||||||
|
stars: int = 0
|
||||||
|
sweep: bool = False
|
||||||
|
drops: str = ""
|
||||||
|
reason: str = ""
|
||||||
|
|
||||||
|
|
||||||
def stages(catalog, snapshot):
|
def stages(catalog, snapshot):
|
||||||
history = snapshot.raw.get("history", {})
|
history = snapshot.raw.get("history") or {}
|
||||||
|
cities = catalog.data["game_setting"].get("cityInfo", {})
|
||||||
result = []
|
result = []
|
||||||
for key, row in catalog.data["stage_info"].items():
|
for key, row in catalog.data["stage_info"].items():
|
||||||
special = catalog.data.get("stage_sp", {}).get(key, {})
|
special = catalog.data.get("stage_sp", {}).get(key, {})
|
||||||
opened = not row.get("closed") and condition_ok(special.get("condition"), snapshot)
|
opened = not row.get("closed") and condition_ok(special.get("condition"), snapshot)
|
||||||
|
city = int(row.get("city") or 0)
|
||||||
|
city_info = cities.get(str(city), {})
|
||||||
|
passed_levels = [i for i in (1, 2, 3) if stage_has_level(history, "passStage", key, i)]
|
||||||
|
sweep = not row.get("special") and not row.get("posmode") and len(passed_levels) == 3
|
||||||
for level, info in row.get("level", {}).items():
|
for level, info in row.get("level", {}).items():
|
||||||
unlocked = indexed(indexed(history.get("unlockStage"), key), level, False) == True
|
unlocked = stage_has_level(history, "unlockStage", key, level)
|
||||||
passed = indexed(indexed(history.get("passStage"), key), level, False) == True
|
passed = stage_has_level(history, "passStage", key, level)
|
||||||
|
gate = city_info.get({"2": "openHardModeStage", "3": "openExtraModeStage"}.get(str(level), ""))
|
||||||
|
unlocked = unlocked and not info.get("levelLock") and (not gate or stage_has_level(history, "passStage", gate, 1))
|
||||||
base = row.get("cost") or {}
|
base = row.get("cost") or {}
|
||||||
tickets = ", ".join(f"{i['typeId']}×{i['num']}" for i in base.get("items", []))
|
tickets = ", ".join(f"{catalog.data.get('item_names', {}).get(str(i['typeId']), i['typeId'])}×{i['num']}" for i in base.get("items", []))
|
||||||
result.append(Stage(key, str(level), row.get("name", key), int(row.get("city", 0)), unlocked, passed, opened,
|
reason = "未解锁" if not unlocked else "当前未开放" if not opened else "特殊关卡需手机实战" if row.get("special") or row.get("posmode") else "需三个难度全部通关" if not sweep else "可扫荡"
|
||||||
int(base.get("ti", 0)) + int(info.get("cost", 0)), tickets))
|
result.append(Stage(key, str(level), row.get("name") or key, city, unlocked, passed, opened,
|
||||||
|
int(base.get("ti") or 0) + int(info.get("cost") or 0), tickets,
|
||||||
|
row.get("tagname") or key, city_info.get("name", f"地区 {city}"), max(passed_levels, default=0),
|
||||||
|
sweep and unlocked and opened, reward_summary(catalog, info.get("reward")), reason))
|
||||||
return result
|
return result
|
||||||
|
|||||||
@@ -15,6 +15,18 @@ def indexed(value, key, default=None):
|
|||||||
return default
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
def stage_has_level(history, field, stage_id, level):
|
||||||
|
"""Wire histories contain difficulty ID lists; AS3 expands them to flags."""
|
||||||
|
value = indexed(history.get(field), stage_id)
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return indexed(value, level, False) is True
|
||||||
|
if isinstance(value, list):
|
||||||
|
if value and all(isinstance(v, bool) or v is None for v in value):
|
||||||
|
return indexed(value, level, False) is True
|
||||||
|
return str(level) in {str(v) for v in value}
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def condition_ok(condition, snapshot):
|
def condition_ok(condition, snapshot):
|
||||||
if not condition:
|
if not condition:
|
||||||
return True
|
return True
|
||||||
@@ -38,7 +50,7 @@ def condition_ok(condition, snapshot):
|
|||||||
return False
|
return False
|
||||||
for field, source in (("passStage", "passStage"), ("unlockStage", "unlockStage")):
|
for field, source in (("passStage", "passStage"), ("unlockStage", "unlockStage")):
|
||||||
for key in condition.get(field) or []:
|
for key in condition.get(field) or []:
|
||||||
if not indexed(indexed(history.get(source), key), 1, False):
|
if not stage_has_level(history, source, key, 1):
|
||||||
return False
|
return False
|
||||||
now = datetime.fromtimestamp(snapshot.now, CN)
|
now = datetime.fromtimestamp(snapshot.now, CN)
|
||||||
if condition.get("week") is not None and (now.weekday() + 1) % 7 not in condition["week"]:
|
if condition.get("week") is not None and (now.weekday() + 1) % 7 not in condition["week"]:
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
"""The built-in three-difficulty-cleared sweep path from StageStartPanel."""
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .daily import day
|
||||||
|
from .maps import stages
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SweepPolicy:
|
||||||
|
enabled: bool = False
|
||||||
|
rules: dict = field(default_factory=dict)
|
||||||
|
keep_stamina: int = 0
|
||||||
|
team: str = "teamA"
|
||||||
|
|
||||||
|
|
||||||
|
class SweepRunner:
|
||||||
|
def __init__(self, catalog, path=None):
|
||||||
|
self.catalog = catalog
|
||||||
|
self.path = Path(path) if path else None
|
||||||
|
self.state = json.loads(self.path.read_text(encoding="utf-8")) if self.path and self.path.exists() else {"counts": {}, "pending": None}
|
||||||
|
|
||||||
|
def save(self):
|
||||||
|
if self.path:
|
||||||
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
temp = self.path.with_suffix(".tmp")
|
||||||
|
temp.write_text(json.dumps(self.state, ensure_ascii=False), encoding="utf-8")
|
||||||
|
temp.replace(self.path)
|
||||||
|
|
||||||
|
def key(self, snapshot, stage):
|
||||||
|
return f"{snapshot.raw['master']['id']}:{day(snapshot.now)}:{stage.stage_id}:{stage.level}"
|
||||||
|
|
||||||
|
def used(self, snapshot, stage):
|
||||||
|
return int(self.state["counts"].get(self.key(snapshot, stage), 0))
|
||||||
|
|
||||||
|
def team_ids(self, snapshot, policy):
|
||||||
|
team = next((t for t in snapshot.raw.get("teams", []) if t.get("teamName") == policy.team and t.get("teamType") == "battleTeam"), {})
|
||||||
|
ids = [int(mid) for mid in team.get("monsters", []) if mid and int(mid) > 0]
|
||||||
|
return [mid for mid in ids if mid in snapshot.monsters]
|
||||||
|
|
||||||
|
def reason(self, snapshot, stage, policy):
|
||||||
|
if self.state.get("pending"):
|
||||||
|
return "有未完成的扫荡,请先在游戏内检查"
|
||||||
|
if not stage.sweep:
|
||||||
|
return stage.reason
|
||||||
|
if not self.team_ids(snapshot, policy):
|
||||||
|
return "所选战队无有效魔物"
|
||||||
|
positions = self.catalog.data.get("stage_task_positions", {})
|
||||||
|
for task in snapshot.raw.get("currentTasks", []):
|
||||||
|
steps = positions.get(str(task.get("typeId")), [])
|
||||||
|
index = int(task.get("curStep") or 1) - 1
|
||||||
|
position = steps[index] if 0 <= index < len(steps) else ""
|
||||||
|
if position == f"city{stage.city}_wild_stage{stage.stage_id}_level{stage.level}":
|
||||||
|
return "该难度有当前剧情任务,请先在游戏内完成"
|
||||||
|
base = self.catalog.data["stage_info"][stage.stage_id].get("cost") or {}
|
||||||
|
master = snapshot.raw["master"]
|
||||||
|
if float(master.get("ti") or 0) < stage.stamina + policy.keep_stamina:
|
||||||
|
return "体力不足或已达保留体力"
|
||||||
|
if base.get("ke"):
|
||||||
|
return "需要氪金,未启用"
|
||||||
|
if float(master.get("money") or 0) < float(base.get("money") or 0):
|
||||||
|
return "金币不足"
|
||||||
|
for item in base.get("items") or []:
|
||||||
|
owned = sum(int(i.get("num") or 0) for i in snapshot.raw.get("items", []) if str(i.get("typeId")) == str(item["typeId"]))
|
||||||
|
if owned < int(item["num"]):
|
||||||
|
return "入场券不足"
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def next(self, snapshot, policy):
|
||||||
|
for stage in sorted(stages(self.catalog, snapshot), key=lambda s: (s.city, s.number, s.stage_id, s.level)):
|
||||||
|
rule = policy.rules.get(stage.stage_id) or {}
|
||||||
|
if not rule.get("enabled") or str(rule.get("level", "3")) != stage.level:
|
||||||
|
continue
|
||||||
|
if self.used(snapshot, stage) < max(0, int(rule.get("limit") or 0)) and not self.reason(snapshot, stage, policy):
|
||||||
|
return stage
|
||||||
|
return None
|
||||||
|
|
||||||
|
def run(self, client, snapshot, stage, policy):
|
||||||
|
rule = policy.rules.get(stage.stage_id) or {}
|
||||||
|
if not rule.get("enabled") or str(rule.get("level")) != stage.level or self.used(snapshot, stage) >= int(rule.get("limit") or 0):
|
||||||
|
raise ValueError("此关卡未勾选或已达本日次数上限")
|
||||||
|
reason = self.reason(snapshot, stage, policy)
|
||||||
|
if reason:
|
||||||
|
raise ValueError(reason)
|
||||||
|
key = self.key(snapshot, stage)
|
||||||
|
self.state["counts"][key] = self.used(snapshot, stage) + 1
|
||||||
|
self.state["pending"] = {"stage": stage.stage_id, "level": stage.level, "phase": "开始请求待确认"}
|
||||||
|
self.save() # Reserve before the first non-retryable write, including timeouts.
|
||||||
|
started = client.call("stageService/stageStart", {"stageTypeId": stage.stage_id, "stageLevel": stage.level})
|
||||||
|
flag = started.get("triggerEvent")
|
||||||
|
if flag is not False and not (type(flag) is int and flag == 0):
|
||||||
|
self.state["pending"]["phase"] = "遇到事件或响应缺少事件状态,请在游戏内处理"
|
||||||
|
self.save()
|
||||||
|
raise ValueError(self.state["pending"]["phase"])
|
||||||
|
# Exactly the official doSaodangBattle data; only for its eligible stages.
|
||||||
|
battle = {"battlePosition": {"battleType": "stage", "stageId": stage.stage_id, "stageLevel": stage.level, "taskTypeId": None, "taskStep": 0},
|
||||||
|
"win": True, "cheatNum": 0, "cheatRecords": "", "killMonster": {}, "battleMonIds": self.team_ids(snapshot, policy),
|
||||||
|
**{name: 0 for name in ("leftTime", "killNum", "totalDamage", "bossDamage", "deadNum", "aliveNum", "apLeft")}}
|
||||||
|
self.state["pending"]["phase"] = "扫荡结算待确认"
|
||||||
|
self.save()
|
||||||
|
result = client.call("battleService/battleEnd", {"battleData": battle})
|
||||||
|
self.state["pending"] = None
|
||||||
|
self.save()
|
||||||
|
client.call("battleService/recordBattleResult", {"stageId": stage.stage_id, "cityId": stage.stage_id[1:2], "result": 1})
|
||||||
|
return result
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||||
|
|
||||||
|
from ranch_assistant.daily import DailyLedger, DailyPolicy, entries
|
||||||
|
from ranch_assistant.engine import Engine, demo_snapshot
|
||||||
|
from ranch_assistant.maps import reward_summary, stages
|
||||||
|
from ranch_assistant.model import Catalog, Snapshot
|
||||||
|
from ranch_assistant.quests import condition_ok
|
||||||
|
from ranch_assistant.sweeping import SweepPolicy, SweepRunner
|
||||||
|
from ranch_assistant.tests.test_core import workspace_temp
|
||||||
|
|
||||||
|
|
||||||
|
def scenario():
|
||||||
|
catalog = Catalog()
|
||||||
|
# One ordinary stage, one not fully passed, one special activity.
|
||||||
|
catalog.data["stage_info"] = {k: catalog.data["stage_info"][k] for k in ("0101", "0102", "bd00")}
|
||||||
|
snapshot = demo_snapshot(catalog)
|
||||||
|
snapshot.raw["history"].update(unlockStage={"0101": ["1", "2", "3"], "0102": ["1"], "bd00": ["1", "2", "3"]},
|
||||||
|
passStage={"0101": ["1", "2", "3"], "0102": ["1"], "bd00": ["1", "2", "3"]})
|
||||||
|
snapshot.raw["teams"] = [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [900, 0]}]
|
||||||
|
yesterday = snapshot.now - 86400
|
||||||
|
snapshot.raw["activityHistory"] = {"dailyCheck": {"checkDay": 2, "checkTime": yesterday * 1000},
|
||||||
|
"dailyGift": {"dailyGiftCheckTime": yesterday * 1000, "dailyGiftLevel": 2, "dailyGiftCount": 2, "dailyRewardGetTime": None}, "vipInfo": None}
|
||||||
|
snapshot.raw["mails"] = [{"id": 12, "title": "测试邮件", "createTime": snapshot.now * 1000,
|
||||||
|
"isGetReward": 0, "reward": json.dumps({"money": 500, "items": [{"type": "30005", "num": 2}]})}]
|
||||||
|
return catalog, snapshot
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
def __init__(self, snapshot):
|
||||||
|
self.value = copy.deepcopy(snapshot.raw)
|
||||||
|
self.calls = []
|
||||||
|
self.trigger = False
|
||||||
|
self.fail = ""
|
||||||
|
|
||||||
|
def snapshot(self):
|
||||||
|
return Snapshot(copy.deepcopy(self.value))
|
||||||
|
|
||||||
|
def call(self, path, payload=None):
|
||||||
|
self.calls.append((path, payload))
|
||||||
|
if path == self.fail:
|
||||||
|
raise TimeoutError("test timeout")
|
||||||
|
if path == "stageService/stageStart":
|
||||||
|
return {"resCode": 0, "triggerEvent": self.trigger}
|
||||||
|
return {"resCode": 0, "reward": {"money": 1}}
|
||||||
|
|
||||||
|
|
||||||
|
class ActivityTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.catalog, self.snapshot = scenario()
|
||||||
|
|
||||||
|
def stage(self, key="0101", level="3"):
|
||||||
|
return next(s for s in stages(self.catalog, self.snapshot) if s.stage_id == key and s.level == level)
|
||||||
|
|
||||||
|
def test_wire_progress_star_difficulty_gates_and_drops(self):
|
||||||
|
first = self.stage()
|
||||||
|
self.assertTrue(first.unlocked and first.passed and first.sweep)
|
||||||
|
self.assertEqual((first.number, first.city_name, first.stars), ("1-1", "莉莉托斯", 3))
|
||||||
|
self.assertIn("金币", first.drops)
|
||||||
|
self.assertIn("绿色史莱姆蛋", self.stage(level="2").drops)
|
||||||
|
self.assertTrue(condition_ok({"passStage": ["0101"]}, self.snapshot))
|
||||||
|
self.assertFalse(self.stage("0102", "2").unlocked)
|
||||||
|
self.assertFalse(self.stage("0102", "1").sweep)
|
||||||
|
self.assertFalse(self.stage("bd00").sweep)
|
||||||
|
self.catalog.data["game_setting"]["cityInfo"]["1"]["openExtraModeStage"] = "locked_gate"
|
||||||
|
self.assertFalse(self.stage().unlocked)
|
||||||
|
|
||||||
|
def test_reward_text_does_not_treat_zero_rolls_as_drops(self):
|
||||||
|
reward = {"rewards": [{"num": 0, "monsters": [{"name": "1001010"}], "items": [{"name": "30005,1,2"}], "item_num": 0}]}
|
||||||
|
self.assertEqual(reward_summary(self.catalog, reward), "")
|
||||||
|
self.assertEqual(reward_summary(self.catalog, "bad json"), "附件格式未知")
|
||||||
|
|
||||||
|
def test_sweep_official_sequence_and_per_role_daily_limits(self):
|
||||||
|
with workspace_temp() as folder:
|
||||||
|
runner = SweepRunner(self.catalog, folder / "runs.json")
|
||||||
|
policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 1}})
|
||||||
|
client = FakeClient(self.snapshot)
|
||||||
|
runner.run(client, self.snapshot, self.stage(), policy)
|
||||||
|
self.assertEqual([p for p, _ in client.calls], ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
|
||||||
|
data = client.calls[1][1]["battleData"]
|
||||||
|
self.assertEqual(data["battleMonIds"], [900])
|
||||||
|
self.assertEqual(data["battlePosition"]["stageLevel"], "3")
|
||||||
|
self.assertIsNone(runner.state["pending"])
|
||||||
|
restored = SweepRunner(self.catalog, folder / "runs.json")
|
||||||
|
self.assertIsNone(restored.next(self.snapshot, policy))
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
restored.run(client, self.snapshot, self.stage(), policy)
|
||||||
|
self.snapshot.raw["master"]["id"] = 2
|
||||||
|
self.assertIsNotNone(restored.next(self.snapshot, policy))
|
||||||
|
|
||||||
|
def test_sweep_stops_on_events_and_unknown_or_failed_start(self):
|
||||||
|
for trigger in (True, None):
|
||||||
|
runner = SweepRunner(self.catalog)
|
||||||
|
policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}})
|
||||||
|
client = FakeClient(self.snapshot)
|
||||||
|
client.trigger = trigger
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
runner.run(client, self.snapshot, self.stage(), policy)
|
||||||
|
self.assertEqual(len(client.calls), 1)
|
||||||
|
self.assertTrue(runner.state["pending"])
|
||||||
|
with workspace_temp() as folder:
|
||||||
|
runner = SweepRunner(self.catalog, folder / "runs.json")
|
||||||
|
client.fail = "stageService/stageStart"
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
runner.run(client, self.snapshot, self.stage(), policy)
|
||||||
|
self.assertTrue(SweepRunner(self.catalog, folder / "runs.json").state["pending"])
|
||||||
|
|
||||||
|
def test_sweep_checks_team_stamina_and_active_story_before_writes(self):
|
||||||
|
runner = SweepRunner(self.catalog)
|
||||||
|
policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}}, keep_stamina=999)
|
||||||
|
self.assertIn("体力", runner.reason(self.snapshot, self.stage(), policy))
|
||||||
|
policy.keep_stamina = 0
|
||||||
|
policy.team = "teamC"
|
||||||
|
self.assertIn("战队", runner.reason(self.snapshot, self.stage(), policy))
|
||||||
|
policy.team = "teamA"
|
||||||
|
self.catalog.data["stage_task_positions"]["test"] = ["city1_wild_stage0101_level3"]
|
||||||
|
self.snapshot.raw["currentTasks"] = [{"typeId": "test", "curStep": 1}]
|
||||||
|
self.assertIn("剧情", runner.reason(self.snapshot, self.stage(), policy))
|
||||||
|
|
||||||
|
def test_daily_claim_eligibility_mail_json_and_null_vip(self):
|
||||||
|
rows = {r.key: r for r in entries(self.catalog, self.snapshot)}
|
||||||
|
self.assertTrue(rows["gift"].action and rows["check"].action and rows["mail:12"].action)
|
||||||
|
self.assertIsNone(rows["vip"].action)
|
||||||
|
self.assertIsNone(rows["loop"].action)
|
||||||
|
self.assertIn("500", rows["mail:12"].reward)
|
||||||
|
self.snapshot.raw["activityHistory"]["dailyCheck"].update(checkDay=7, checkTime=None)
|
||||||
|
self.snapshot.raw["mails"][0]["isGetReward"] = 1
|
||||||
|
rows = {r.key: r for r in entries(self.catalog, self.snapshot)}
|
||||||
|
self.assertIsNone(rows["check"].action)
|
||||||
|
self.assertIsNone(rows["mail:12"].action)
|
||||||
|
|
||||||
|
def test_daily_time_units_and_midnight_reset(self):
|
||||||
|
with workspace_temp() as folder:
|
||||||
|
ledger = DailyLedger(folder / "claims.json")
|
||||||
|
ledger.record(self.snapshot, "gift")
|
||||||
|
self.assertTrue(ledger.seen(self.snapshot, "gift"))
|
||||||
|
self.assertIsNone(next(r for r in entries(self.catalog, self.snapshot, ledger) if r.key == "gift").action)
|
||||||
|
self.snapshot.server_offset += 86400
|
||||||
|
self.assertFalse(DailyLedger(folder / "claims.json").seen(self.snapshot, "gift"))
|
||||||
|
self.snapshot.raw["activityHistory"]["dailyGift"]["dailyGiftCheckTime"] = self.snapshot.now
|
||||||
|
self.assertIsNone(next(r for r in entries(self.catalog, self.snapshot) if r.key == "gift").action)
|
||||||
|
|
||||||
|
def test_refresh_does_not_claim_and_manual_claims_do_not_repeat_stale_data(self):
|
||||||
|
client = FakeClient(self.snapshot)
|
||||||
|
engine = Engine(self.catalog, client)
|
||||||
|
engine.policy.enabled = False
|
||||||
|
engine.daily_policy = DailyPolicy(True, ["gift", "mail"])
|
||||||
|
engine.poll()
|
||||||
|
self.assertEqual(client.calls, [])
|
||||||
|
_, _, message = engine.claim_daily()
|
||||||
|
self.assertIn("2", message)
|
||||||
|
self.assertEqual([p for p, _ in client.calls], ["dailyGiftService/dailyGiftSign", "mailService/mailGetReward"])
|
||||||
|
engine.claim_daily()
|
||||||
|
self.assertEqual(len(client.calls), 2)
|
||||||
|
|
||||||
|
def test_auto_daily_is_one_action_and_no_purchase_or_vip_activation(self):
|
||||||
|
client = FakeClient(self.snapshot)
|
||||||
|
engine = Engine(self.catalog, client)
|
||||||
|
engine.policy.enabled = False
|
||||||
|
engine.daily_policy = DailyPolicy(True, ["gift", "check", "vip", "mail"])
|
||||||
|
engine.auto = True
|
||||||
|
engine.poll()
|
||||||
|
self.assertEqual(len(client.calls), 1)
|
||||||
|
self.assertEqual(client.calls[0][0], "dailyGiftService/dailyGiftSign")
|
||||||
|
|
||||||
|
def test_failed_daily_request_is_not_repeated_after_restart(self):
|
||||||
|
with workspace_temp() as folder:
|
||||||
|
client = FakeClient(self.snapshot)
|
||||||
|
client.fail = "dailyGiftService/dailyGiftSign"
|
||||||
|
engine = Engine(self.catalog, client, folder / "purchase.json")
|
||||||
|
engine.policy.enabled = False
|
||||||
|
engine.daily_policy = DailyPolicy(True, ["gift"])
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
engine.claim_daily()
|
||||||
|
engine = Engine(self.catalog, client, folder / "purchase.json")
|
||||||
|
engine.policy.enabled = False
|
||||||
|
engine.daily_policy = DailyPolicy(True, ["gift"])
|
||||||
|
engine.claim_daily()
|
||||||
|
self.assertEqual(len(client.calls), 1)
|
||||||
|
|
||||||
|
def test_auto_sweep_and_end_timeout_never_retry_settlement(self):
|
||||||
|
with workspace_temp() as folder:
|
||||||
|
client = FakeClient(self.snapshot)
|
||||||
|
client.fail = "battleService/battleEnd"
|
||||||
|
engine = Engine(self.catalog, client, folder / "purchase.json")
|
||||||
|
engine.policy.enabled = False
|
||||||
|
engine.sweep_policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}})
|
||||||
|
engine.auto = True
|
||||||
|
with self.assertRaises(TimeoutError):
|
||||||
|
engine.poll()
|
||||||
|
self.assertEqual(len(client.calls), 2)
|
||||||
|
restored = Engine(self.catalog, client, folder / "purchase.json")
|
||||||
|
restored.policy.enabled = False
|
||||||
|
restored.sweep_policy = engine.sweep_policy
|
||||||
|
restored.auto = True
|
||||||
|
restored.poll()
|
||||||
|
self.assertEqual(len(client.calls), 2)
|
||||||
|
|
||||||
|
|
||||||
|
class ActivityGuiTests(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
from PySide6.QtWidgets import QApplication
|
||||||
|
cls.app = QApplication.instance() or QApplication([])
|
||||||
|
|
||||||
|
def test_tree_rules_daily_page_and_scroll_layout(self):
|
||||||
|
from PySide6 import QtCore as C, QtWidgets as W
|
||||||
|
from PySide6.QtTest import QTest
|
||||||
|
from ranch_assistant.gui import Window
|
||||||
|
with workspace_temp() as folder:
|
||||||
|
window = Window(state_root=folder)
|
||||||
|
window.timer.stop()
|
||||||
|
try:
|
||||||
|
for _ in range(150):
|
||||||
|
self.app.processEvents()
|
||||||
|
QTest.qWait(5)
|
||||||
|
if not window.busy:
|
||||||
|
break
|
||||||
|
catalog, snapshot = scenario()
|
||||||
|
window.catalog = catalog
|
||||||
|
window.engine = Engine(catalog)
|
||||||
|
window.engine.snapshot = snapshot
|
||||||
|
window.render_maps()
|
||||||
|
window.render_daily()
|
||||||
|
self.assertEqual(window.maps_tree.topLevelItem(0).text(0), "莉莉托斯")
|
||||||
|
region = window.maps_tree.topLevelItem(0)
|
||||||
|
first = region.child(0)
|
||||||
|
first.setCheckState(0, C.Qt.CheckState.Checked)
|
||||||
|
self.assertTrue(window.map_rules["0101"]["enabled"])
|
||||||
|
difficulty = window.maps_tree.itemWidget(region.child(1), 3)
|
||||||
|
self.assertFalse(difficulty.model().item(1).isEnabled())
|
||||||
|
window.maps_tree.itemWidget(first, 8).setText("12")
|
||||||
|
self.assertEqual(window.map_rules["0101"]["limit"], 12)
|
||||||
|
self.assertGreater(window.daily_table.rowCount(), 4)
|
||||||
|
window.save_config(quiet=True)
|
||||||
|
settings = json.loads((folder / "settings.json").read_text(encoding="utf-8"))
|
||||||
|
self.assertEqual(settings["sweep_policy"]["rules"]["0101"]["limit"], 12)
|
||||||
|
window.resize(1100, 650)
|
||||||
|
window.show()
|
||||||
|
window.tabs.setCurrentWidget(window.capture_scroll)
|
||||||
|
window.log_splitter.setSizes([180, 450])
|
||||||
|
self.app.processEvents()
|
||||||
|
table_rect = window.capture_rows.geometry()
|
||||||
|
next_button = next(b for b in window.capture_page_widget.findChildren(W.QPushButton) if b.text() == "检查已保存截图")
|
||||||
|
self.assertGreater(next_button.geometry().top(), table_rect.bottom())
|
||||||
|
self.assertGreater(window.capture_scroll.verticalScrollBar().maximum(), 0)
|
||||||
|
self.assertEqual(window.styleSheet(), "")
|
||||||
|
finally:
|
||||||
|
window.close()
|
||||||
|
restored = Window(state_root=folder)
|
||||||
|
restored.timer.stop()
|
||||||
|
try:
|
||||||
|
for _ in range(150):
|
||||||
|
self.app.processEvents()
|
||||||
|
QTest.qWait(5)
|
||||||
|
if not restored.busy:
|
||||||
|
break
|
||||||
|
self.assertEqual(restored.map_rules["0101"]["limit"], 12)
|
||||||
|
self.assertFalse(restored.execute.isChecked())
|
||||||
|
self.assertFalse(restored.monitoring)
|
||||||
|
finally:
|
||||||
|
restored.close()
|
||||||
@@ -14,7 +14,7 @@ apk = next(p for p in root.glob("*.apk") if p.name.endswith("_1.9.68.apk"))
|
|||||||
tables = {}
|
tables = {}
|
||||||
with zipfile.ZipFile(apk) as archive:
|
with zipfile.ZipFile(apk) as archive:
|
||||||
tables["tjchannel"] = json.loads(archive.read("assets/tjchannel.json")) if "assets/tjchannel.json" in archive.namelist() else {"tjchannel": "unknow"}
|
tables["tjchannel"] = json.loads(archive.read("assets/tjchannel.json")) if "assets/tjchannel.json" in archive.namelist() else {"tjchannel": "unknow"}
|
||||||
for name in ("monster_info", "room_info", "game_setting", "stage_info", "stage_sp", "server_info", "task_info", "gacha_machine", "potential_info", "stack_price", "room_price", "item_info"):
|
for name in ("monster_info", "room_info", "game_setting", "stage_info", "stage_sp", "activity_info", "server_info", "task_info", "gacha_machine", "potential_info", "stack_price", "room_price", "item_info"):
|
||||||
path = "data/table/" + name + ".json"
|
path = "data/table/" + name + ".json"
|
||||||
raw = zlib.decompress(archive.read("assets/codes/" + hashlib.md5(path.encode()).hexdigest()))
|
raw = zlib.decompress(archive.read("assets/codes/" + hashlib.md5(path.encode()).hexdigest()))
|
||||||
reader = Reader(raw)
|
reader = Reader(raw)
|
||||||
@@ -28,8 +28,7 @@ with zipfile.ZipFile(apk) as archive:
|
|||||||
fields = {"type", "name", "star", "time_1", "time_2", "sell_money", "sell_exp", "hideLib", "npc", "atk", "def", "hp", "dex", "like"}
|
fields = {"type", "name", "star", "time_1", "time_2", "sell_money", "sell_exp", "hideLib", "npc", "atk", "def", "hp", "dex", "like"}
|
||||||
fields |= {p + "_grow_" + bound for p in ("atk", "def", "hp", "dex") for bound in ("min", "max")}
|
fields |= {p + "_grow_" + bound for p in ("atk", "def", "hp", "dex") for bound in ("min", "max")}
|
||||||
tables["monster_info"] = {str(k): {f: v for f, v in row.items() if f in fields} for k, row in tables["monster_info"].items()}
|
tables["monster_info"] = {str(k): {f: v for f, v in row.items() if f in fields} for k, row in tables["monster_info"].items()}
|
||||||
liked_items = {str(k) for row in tables["monster_info"].values() for k in (row.get("like") or {})}
|
tables["item_names"] = {str(key): row.get("name", str(key)) for key, row in tables.pop("item_info").items()}
|
||||||
tables["item_names"] = {str(key): row.get("name", str(key)) for key, row in tables.pop("item_info").items() if str(key) in liked_items}
|
|
||||||
|
|
||||||
# The market button uses sc_city + the selected city ID, even where the table's
|
# The market button uses sc_city + the selected city ID, even where the table's
|
||||||
# legacy city field still says 4. Exclude tavern/premium/event egg machines.
|
# legacy city field still says 4. Exclude tavern/premium/event egg machines.
|
||||||
@@ -37,10 +36,14 @@ tables["markets"] = {row["id"]: {k: row.get(k) for k in ("id", "money", "ke", "m
|
|||||||
{"city": int(row["id"][7:]), "name": tables["game_setting"]["cityInfo"][row["id"][7:]]["name"]}
|
{"city": int(row["id"][7:]), "name": tables["game_setting"]["cityInfo"][row["id"][7:]]["name"]}
|
||||||
for row in tables.pop("gacha_machine") if row["id"].startswith("sc_city")}
|
for row in tables.pop("gacha_machine") if row["id"].startswith("sc_city")}
|
||||||
tables["potential_info"] = {k: tables["potential_info"][k] for k in ("potentialLevelMaxAdd", "maxPotentialLevel")}
|
tables["potential_info"] = {k: tables["potential_info"][k] for k in ("potentialLevelMaxAdd", "maxPotentialLevel")}
|
||||||
tables["stage_info"] = {r["id"]: {"id": r["id"], "name": r.get("name", ""), "city": r.get("city", 0), "closed": r.get("closed", False), "cost": r.get("cost", {}),
|
tables["stage_info"] = {r["id"]: {f: r.get(f) for f in ("id", "name", "city", "closed", "cost", "tagname", "special", "posmode")} |
|
||||||
"level": {k: {f: v for f, v in level.items() if f in ("cost", "levelLock")} for k, level in r.get("level", {}).items()}}
|
{"level": {k: {f: v for f, v in level.items() if f in ("cost", "levelLock", "reward", "monExp")} for k, level in r.get("level", {}).items()}}
|
||||||
for r in tables["stage_info"]}
|
for r in tables["stage_info"]}
|
||||||
tables["game_setting"] = {k: v for k, v in tables["game_setting"].items() if k in ("monExpScale", "xyz", "xyz1", "cityInfo", "upStarAdd", "maxLike") or k.startswith("loopTask") or k.endswith("_xyz")}
|
tables["activity_info"] = {k: v for k, v in tables["activity_info"].items() if k in ("dailyCheck", "dailyGift", "loopCheckReward")}
|
||||||
|
# Only positions are needed to avoid starting a sweep through an active story task.
|
||||||
|
tables["stage_task_positions"] = {str(k): [s.get("position", "") for s in r.get("steps", [])] for k, r in tables["task_info"].items()
|
||||||
|
if any(str(s.get("position", "")).startswith("city") for s in r.get("steps", []))}
|
||||||
|
tables["game_setting"] = {k: v for k, v in tables["game_setting"].items() if k in ("monExpScale", "xyz", "xyz1", "cityInfo", "upStarAdd", "maxLike", "vipReward") or k.startswith("loopTask") or k.endswith("_xyz")}
|
||||||
task_fields = {"type", "typeId", "name", "des", "city", "closed", "condition", "startStep", "reward"}
|
task_fields = {"type", "typeId", "name", "des", "city", "closed", "condition", "startStep", "reward"}
|
||||||
step_fields = {"statusType", "statusValue", "condition", "des", "position", "npc", "afterStory", "auto"}
|
step_fields = {"statusType", "statusValue", "condition", "des", "position", "npc", "afterStory", "auto"}
|
||||||
tables["task_info"] = {str(k): {f: v for f, v in row.items() if f in task_fields} |
|
tables["task_info"] = {str(k): {f: v for f, v in row.items() if f in task_fields} |
|
||||||
|
|||||||
Reference in New Issue
Block a user